blob: 125a7302088421e58ecc60bafcbd42ed62b6b472 [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",
Sylvestre Ledru55635ce2014-11-17 19:41:49 +0000164 "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) {
Richard Smith64ecacf2015-02-19 00:39:05 +0000289 // 'bool' is an integral type; dispatch to the right place to handle it.
290 case ICK_Boolean_Conversion:
291 if (FromType->isRealFloatingType())
292 goto FloatingIntegralConversion;
293 if (FromType->isIntegralOrUnscopedEnumerationType())
294 goto IntegralConversion;
295 // Boolean conversions can be from pointers and pointers to members
296 // [conv.bool], and those aren't considered narrowing conversions.
297 return NK_Not_Narrowing;
298
Richard Smith66e05fe2012-01-18 05:21:49 +0000299 // -- from a floating-point type to an integer type, or
300 //
301 // -- from an integer type or unscoped enumeration type to a floating-point
302 // type, except where the source is a constant expression and the actual
303 // value after conversion will fit into the target type and will produce
304 // the original value when converted back to the original type, or
305 case ICK_Floating_Integral:
Richard Smith64ecacf2015-02-19 00:39:05 +0000306 FloatingIntegralConversion:
Richard Smith66e05fe2012-01-18 05:21:49 +0000307 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
308 return NK_Type_Narrowing;
309 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
310 llvm::APSInt IntConstantValue;
311 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
312 if (Initializer &&
313 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
314 // Convert the integer to the floating type.
315 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
316 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
317 llvm::APFloat::rmNearestTiesToEven);
318 // And back.
319 llvm::APSInt ConvertedValue = IntConstantValue;
320 bool ignored;
321 Result.convertToInteger(ConvertedValue,
322 llvm::APFloat::rmTowardZero, &ignored);
323 // If the resulting value is different, this was a narrowing conversion.
324 if (IntConstantValue != ConvertedValue) {
325 ConstantValue = APValue(IntConstantValue);
Richard Smith5614ca72012-03-23 23:55:39 +0000326 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000327 return NK_Constant_Narrowing;
328 }
329 } else {
330 // Variables are always narrowings.
331 return NK_Variable_Narrowing;
332 }
333 }
334 return NK_Not_Narrowing;
335
336 // -- from long double to double or float, or from double to float, except
337 // where the source is a constant expression and the actual value after
338 // conversion is within the range of values that can be represented (even
339 // if it cannot be represented exactly), or
340 case ICK_Floating_Conversion:
341 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
342 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
343 // FromType is larger than ToType.
344 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
345 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
346 // Constant!
347 assert(ConstantValue.isFloat());
348 llvm::APFloat FloatVal = ConstantValue.getFloat();
349 // Convert the source value into the target type.
350 bool ignored;
351 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
352 Ctx.getFloatTypeSemantics(ToType),
353 llvm::APFloat::rmNearestTiesToEven, &ignored);
354 // If there was no overflow, the source value is within the range of
355 // values that can be represented.
Richard Smith5614ca72012-03-23 23:55:39 +0000356 if (ConvertStatus & llvm::APFloat::opOverflow) {
357 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000358 return NK_Constant_Narrowing;
Richard Smith5614ca72012-03-23 23:55:39 +0000359 }
Richard Smith66e05fe2012-01-18 05:21:49 +0000360 } else {
361 return NK_Variable_Narrowing;
362 }
363 }
364 return NK_Not_Narrowing;
365
366 // -- from an integer type or unscoped enumeration type to an integer type
367 // that cannot represent all the values of the original type, except where
368 // the source is a constant expression and the actual value after
369 // conversion will fit into the target type and will produce the original
370 // value when converted back to the original type.
Richard Smith64ecacf2015-02-19 00:39:05 +0000371 case ICK_Integral_Conversion:
372 IntegralConversion: {
Richard Smith66e05fe2012-01-18 05:21:49 +0000373 assert(FromType->isIntegralOrUnscopedEnumerationType());
374 assert(ToType->isIntegralOrUnscopedEnumerationType());
375 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
376 const unsigned FromWidth = Ctx.getIntWidth(FromType);
377 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
378 const unsigned ToWidth = Ctx.getIntWidth(ToType);
379
380 if (FromWidth > ToWidth ||
Richard Smith25a80d42012-06-13 01:07:41 +0000381 (FromWidth == ToWidth && FromSigned != ToSigned) ||
382 (FromSigned && !ToSigned)) {
Richard Smith66e05fe2012-01-18 05:21:49 +0000383 // Not all values of FromType can be represented in ToType.
384 llvm::APSInt InitializerValue;
385 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
Richard Smith25a80d42012-06-13 01:07:41 +0000386 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
387 // Such conversions on variables are always narrowing.
388 return NK_Variable_Narrowing;
Richard Smith72cd8ea2012-06-19 21:28:35 +0000389 }
390 bool Narrowing = false;
391 if (FromWidth < ToWidth) {
Richard Smith25a80d42012-06-13 01:07:41 +0000392 // Negative -> unsigned is narrowing. Otherwise, more bits is never
393 // narrowing.
394 if (InitializerValue.isSigned() && InitializerValue.isNegative())
Richard Smith72cd8ea2012-06-19 21:28:35 +0000395 Narrowing = true;
Richard Smith25a80d42012-06-13 01:07:41 +0000396 } else {
Richard Smith66e05fe2012-01-18 05:21:49 +0000397 // Add a bit to the InitializerValue so we don't have to worry about
398 // signed vs. unsigned comparisons.
399 InitializerValue = InitializerValue.extend(
400 InitializerValue.getBitWidth() + 1);
401 // Convert the initializer to and from the target width and signed-ness.
402 llvm::APSInt ConvertedValue = InitializerValue;
403 ConvertedValue = ConvertedValue.trunc(ToWidth);
404 ConvertedValue.setIsSigned(ToSigned);
405 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
406 ConvertedValue.setIsSigned(InitializerValue.isSigned());
407 // If the result is different, this was a narrowing conversion.
Richard Smith72cd8ea2012-06-19 21:28:35 +0000408 if (ConvertedValue != InitializerValue)
409 Narrowing = true;
410 }
411 if (Narrowing) {
412 ConstantType = Initializer->getType();
413 ConstantValue = APValue(InitializerValue);
414 return NK_Constant_Narrowing;
Richard Smith66e05fe2012-01-18 05:21:49 +0000415 }
416 }
417 return NK_Not_Narrowing;
418 }
419
420 default:
421 // Other kinds of conversions are not narrowings.
422 return NK_Not_Narrowing;
423 }
424}
425
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000426/// dump - Print this standard conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000427/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000428void StandardConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000429 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000430 bool PrintedSomething = false;
431 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000432 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000433 PrintedSomething = true;
434 }
435
436 if (Second != ICK_Identity) {
437 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000438 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000439 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000440 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000441
442 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000443 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000444 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000445 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000446 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000447 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000448 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000449 PrintedSomething = true;
450 }
451
452 if (Third != ICK_Identity) {
453 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000454 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000455 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000456 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000457 PrintedSomething = true;
458 }
459
460 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000461 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000462 }
463}
464
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000465/// dump - Print this user-defined conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000466/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000467void UserDefinedConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000468 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000469 if (Before.First || Before.Second || Before.Third) {
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000470 Before.dump();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000471 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000472 }
Sebastian Redl72ef7bc2011-11-01 15:53:09 +0000473 if (ConversionFunction)
474 OS << '\'' << *ConversionFunction << '\'';
475 else
476 OS << "aggregate initialization";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000477 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000478 OS << " -> ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000479 After.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000480 }
481}
482
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000483/// dump - Print this implicit conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000484/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000485void ImplicitConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000486 raw_ostream &OS = llvm::errs();
Richard Smitha93f1022013-09-06 22:30:28 +0000487 if (isStdInitializerListElement())
488 OS << "Worst std::initializer_list element conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000489 switch (ConversionKind) {
490 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000491 OS << "Standard conversion: ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000492 Standard.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000493 break;
494 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000495 OS << "User-defined conversion: ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000496 UserDefined.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000497 break;
498 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000499 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000500 break;
John McCall0d1da222010-01-12 00:44:57 +0000501 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000502 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000503 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000504 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000505 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000506 break;
507 }
508
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000509 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000510}
511
John McCall0d1da222010-01-12 00:44:57 +0000512void AmbiguousConversionSequence::construct() {
513 new (&conversions()) ConversionSet();
514}
515
516void AmbiguousConversionSequence::destruct() {
517 conversions().~ConversionSet();
518}
519
520void
521AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
522 FromTypePtr = O.FromTypePtr;
523 ToTypePtr = O.ToTypePtr;
524 new (&conversions()) ConversionSet(O.conversions());
525}
526
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000527namespace {
Larisse Voufo98b20f12013-07-19 23:00:19 +0000528 // Structure used by DeductionFailureInfo to store
Richard Smith44ecdbd2013-01-31 05:19:49 +0000529 // template argument information.
530 struct DFIArguments {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000531 TemplateArgument FirstArg;
532 TemplateArgument SecondArg;
533 };
Larisse Voufo98b20f12013-07-19 23:00:19 +0000534 // Structure used by DeductionFailureInfo to store
Richard Smith44ecdbd2013-01-31 05:19:49 +0000535 // template parameter and template argument information.
536 struct DFIParamWithArguments : DFIArguments {
537 TemplateParameter Param;
538 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000539}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000540
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000541/// \brief Convert from Sema's representation of template deduction information
542/// to the form used in overload-candidate information.
Richard Smith17c00b42014-11-12 01:24:00 +0000543DeductionFailureInfo
544clang::MakeDeductionFailureInfo(ASTContext &Context,
545 Sema::TemplateDeductionResult TDK,
546 TemplateDeductionInfo &Info) {
Larisse Voufo98b20f12013-07-19 23:00:19 +0000547 DeductionFailureInfo Result;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000548 Result.Result = static_cast<unsigned>(TDK);
Richard Smith9ca64612012-05-07 09:03:25 +0000549 Result.HasDiagnostic = false;
Craig Topperc3ec1492014-05-26 06:22:03 +0000550 Result.Data = nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000551 switch (TDK) {
552 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000553 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000554 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000555 case Sema::TDK_TooManyArguments:
556 case Sema::TDK_TooFewArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000557 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000558
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000559 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000560 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000561 Result.Data = Info.Param.getOpaqueValue();
562 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000563
Richard Smith44ecdbd2013-01-31 05:19:49 +0000564 case Sema::TDK_NonDeducedMismatch: {
565 // FIXME: Should allocate from normal heap so that we can free this later.
566 DFIArguments *Saved = new (Context) DFIArguments;
567 Saved->FirstArg = Info.FirstArg;
568 Saved->SecondArg = Info.SecondArg;
569 Result.Data = Saved;
570 break;
571 }
572
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000573 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000574 case Sema::TDK_Underqualified: {
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000575 // FIXME: Should allocate from normal heap so that we can free this later.
576 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000577 Saved->Param = Info.Param;
578 Saved->FirstArg = Info.FirstArg;
579 Saved->SecondArg = Info.SecondArg;
580 Result.Data = Saved;
581 break;
582 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000583
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000584 case Sema::TDK_SubstitutionFailure:
Douglas Gregord09efd42010-05-08 20:07:26 +0000585 Result.Data = Info.take();
Richard Smith9ca64612012-05-07 09:03:25 +0000586 if (Info.hasSFINAEDiagnostic()) {
587 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
588 SourceLocation(), PartialDiagnostic::NullDiagnostic());
589 Info.takeSFINAEDiagnostic(*Diag);
590 Result.HasDiagnostic = true;
591 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000592 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000593
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000594 case Sema::TDK_FailedOverloadResolution:
Richard Smith8c6eeb92013-01-31 04:03:12 +0000595 Result.Data = Info.Expression;
596 break;
597
Richard Smith44ecdbd2013-01-31 05:19:49 +0000598 case Sema::TDK_MiscellaneousDeductionFailure:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000599 break;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000600 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000601
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000602 return Result;
603}
John McCall0d1da222010-01-12 00:44:57 +0000604
Larisse Voufo98b20f12013-07-19 23:00:19 +0000605void DeductionFailureInfo::Destroy() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000606 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
607 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000608 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000609 case Sema::TDK_InstantiationDepth:
610 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000611 case Sema::TDK_TooManyArguments:
612 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000613 case Sema::TDK_InvalidExplicitArguments:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000614 case Sema::TDK_FailedOverloadResolution:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000615 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000616
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000617 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000618 case Sema::TDK_Underqualified:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000619 case Sema::TDK_NonDeducedMismatch:
Douglas Gregorb02d6b32010-05-08 20:20:05 +0000620 // FIXME: Destroy the data?
Craig Topperc3ec1492014-05-26 06:22:03 +0000621 Data = nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000622 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000623
624 case Sema::TDK_SubstitutionFailure:
Richard Smith9ca64612012-05-07 09:03:25 +0000625 // FIXME: Destroy the template argument list?
Craig Topperc3ec1492014-05-26 06:22:03 +0000626 Data = nullptr;
Richard Smith9ca64612012-05-07 09:03:25 +0000627 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
628 Diag->~PartialDiagnosticAt();
629 HasDiagnostic = false;
630 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000631 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000632
Douglas Gregor461761d2010-05-08 18:20:53 +0000633 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000634 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000635 break;
636 }
637}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000638
Larisse Voufo98b20f12013-07-19 23:00:19 +0000639PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
Richard Smith9ca64612012-05-07 09:03:25 +0000640 if (HasDiagnostic)
641 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
Craig Topperc3ec1492014-05-26 06:22:03 +0000642 return nullptr;
Richard Smith9ca64612012-05-07 09:03:25 +0000643}
644
Larisse Voufo98b20f12013-07-19 23:00:19 +0000645TemplateParameter DeductionFailureInfo::getTemplateParameter() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000646 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
647 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000648 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000649 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000650 case Sema::TDK_TooManyArguments:
651 case Sema::TDK_TooFewArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000652 case Sema::TDK_SubstitutionFailure:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000653 case Sema::TDK_NonDeducedMismatch:
654 case Sema::TDK_FailedOverloadResolution:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000655 return TemplateParameter();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000656
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000657 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000658 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000659 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000660
661 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000662 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000663 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000664
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000665 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000666 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000667 break;
668 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000669
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000670 return TemplateParameter();
671}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000672
Larisse Voufo98b20f12013-07-19 23:00:19 +0000673TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
Douglas Gregord09efd42010-05-08 20:07:26 +0000674 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
Richard Smith44ecdbd2013-01-31 05:19:49 +0000675 case Sema::TDK_Success:
676 case Sema::TDK_Invalid:
677 case Sema::TDK_InstantiationDepth:
678 case Sema::TDK_TooManyArguments:
679 case Sema::TDK_TooFewArguments:
680 case Sema::TDK_Incomplete:
681 case Sema::TDK_InvalidExplicitArguments:
682 case Sema::TDK_Inconsistent:
683 case Sema::TDK_Underqualified:
684 case Sema::TDK_NonDeducedMismatch:
685 case Sema::TDK_FailedOverloadResolution:
Craig Topperc3ec1492014-05-26 06:22:03 +0000686 return nullptr;
Douglas Gregord09efd42010-05-08 20:07:26 +0000687
Richard Smith44ecdbd2013-01-31 05:19:49 +0000688 case Sema::TDK_SubstitutionFailure:
689 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000690
Richard Smith44ecdbd2013-01-31 05:19:49 +0000691 // Unhandled
692 case Sema::TDK_MiscellaneousDeductionFailure:
693 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000694 }
695
Craig Topperc3ec1492014-05-26 06:22:03 +0000696 return nullptr;
Douglas Gregord09efd42010-05-08 20:07:26 +0000697}
698
Larisse Voufo98b20f12013-07-19 23:00:19 +0000699const TemplateArgument *DeductionFailureInfo::getFirstArg() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000700 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
701 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000702 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000703 case Sema::TDK_InstantiationDepth:
704 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000705 case Sema::TDK_TooManyArguments:
706 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000707 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000708 case Sema::TDK_SubstitutionFailure:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000709 case Sema::TDK_FailedOverloadResolution:
Craig Topperc3ec1492014-05-26 06:22:03 +0000710 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000711
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000712 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000713 case Sema::TDK_Underqualified:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000714 case Sema::TDK_NonDeducedMismatch:
715 return &static_cast<DFIArguments*>(Data)->FirstArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000716
Douglas Gregor461761d2010-05-08 18:20:53 +0000717 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000718 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000719 break;
720 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000721
Craig Topperc3ec1492014-05-26 06:22:03 +0000722 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000723}
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000724
Larisse Voufo98b20f12013-07-19 23:00:19 +0000725const TemplateArgument *DeductionFailureInfo::getSecondArg() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000726 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
727 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000728 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000729 case Sema::TDK_InstantiationDepth:
730 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000731 case Sema::TDK_TooManyArguments:
732 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000733 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000734 case Sema::TDK_SubstitutionFailure:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000735 case Sema::TDK_FailedOverloadResolution:
Craig Topperc3ec1492014-05-26 06:22:03 +0000736 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000737
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000738 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000739 case Sema::TDK_Underqualified:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000740 case Sema::TDK_NonDeducedMismatch:
741 return &static_cast<DFIArguments*>(Data)->SecondArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000742
Douglas Gregor461761d2010-05-08 18:20:53 +0000743 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000744 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000745 break;
746 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000747
Craig Topperc3ec1492014-05-26 06:22:03 +0000748 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000749}
750
Larisse Voufo98b20f12013-07-19 23:00:19 +0000751Expr *DeductionFailureInfo::getExpr() {
Richard Smith8c6eeb92013-01-31 04:03:12 +0000752 if (static_cast<Sema::TemplateDeductionResult>(Result) ==
753 Sema::TDK_FailedOverloadResolution)
754 return static_cast<Expr*>(Data);
755
Craig Topperc3ec1492014-05-26 06:22:03 +0000756 return nullptr;
Richard Smith8c6eeb92013-01-31 04:03:12 +0000757}
758
Benjamin Kramer97e59492012-10-09 15:52:25 +0000759void OverloadCandidateSet::destroyCandidates() {
Richard Smith0bf93aa2012-07-18 23:52:59 +0000760 for (iterator i = begin(), e = end(); i != e; ++i) {
Benjamin Kramer02b08432012-01-14 20:16:52 +0000761 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
762 i->Conversions[ii].~ImplicitConversionSequence();
Richard Smith0bf93aa2012-07-18 23:52:59 +0000763 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
764 i->DeductionFailure.Destroy();
765 }
Benjamin Kramer97e59492012-10-09 15:52:25 +0000766}
767
768void OverloadCandidateSet::clear() {
769 destroyCandidates();
Benjamin Kramer0b9c5092012-01-14 19:31:39 +0000770 NumInlineSequences = 0;
Benjamin Kramerfb761ff2012-01-14 16:31:55 +0000771 Candidates.clear();
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000772 Functions.clear();
773}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000774
John McCall4124c492011-10-17 18:40:02 +0000775namespace {
776 class UnbridgedCastsSet {
777 struct Entry {
778 Expr **Addr;
779 Expr *Saved;
780 };
781 SmallVector<Entry, 2> Entries;
782
783 public:
784 void save(Sema &S, Expr *&E) {
785 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
786 Entry entry = { &E, E };
787 Entries.push_back(entry);
788 E = S.stripARCUnbridgedCast(E);
789 }
790
791 void restore() {
792 for (SmallVectorImpl<Entry>::iterator
793 i = Entries.begin(), e = Entries.end(); i != e; ++i)
794 *i->Addr = i->Saved;
795 }
796 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000797}
John McCall4124c492011-10-17 18:40:02 +0000798
799/// checkPlaceholderForOverload - Do any interesting placeholder-like
800/// preprocessing on the given expression.
801///
802/// \param unbridgedCasts a collection to which to add unbridged casts;
803/// without this, they will be immediately diagnosed as errors
804///
805/// Return true on unrecoverable error.
Craig Topperc3ec1492014-05-26 06:22:03 +0000806static bool
807checkPlaceholderForOverload(Sema &S, Expr *&E,
808 UnbridgedCastsSet *unbridgedCasts = nullptr) {
John McCall4124c492011-10-17 18:40:02 +0000809 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
810 // We can't handle overloaded expressions here because overload
811 // resolution might reasonably tweak them.
812 if (placeholder->getKind() == BuiltinType::Overload) return false;
813
814 // If the context potentially accepts unbridged ARC casts, strip
815 // the unbridged cast and add it to the collection for later restoration.
816 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
817 unbridgedCasts) {
818 unbridgedCasts->save(S, E);
819 return false;
820 }
821
822 // Go ahead and check everything else.
823 ExprResult result = S.CheckPlaceholderExpr(E);
824 if (result.isInvalid())
825 return true;
826
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000827 E = result.get();
John McCall4124c492011-10-17 18:40:02 +0000828 return false;
829 }
830
831 // Nothing to do.
832 return false;
833}
834
835/// checkArgPlaceholdersForOverload - Check a set of call operands for
836/// placeholders.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000837static bool checkArgPlaceholdersForOverload(Sema &S,
838 MultiExprArg Args,
John McCall4124c492011-10-17 18:40:02 +0000839 UnbridgedCastsSet &unbridged) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000840 for (unsigned i = 0, e = Args.size(); i != e; ++i)
841 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
John McCall4124c492011-10-17 18:40:02 +0000842 return true;
843
844 return false;
845}
846
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000847// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000848// overload of the declarations in Old. This routine returns false if
849// New and Old cannot be overloaded, e.g., if New has the same
850// signature as some function in Old (C++ 1.3.10) or if the Old
851// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000852// it does return false, MatchedDecl will point to the decl that New
853// cannot be overloaded with. This decl may be a UsingShadowDecl on
854// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000855//
856// Example: Given the following input:
857//
858// void f(int, float); // #1
859// void f(int, int); // #2
860// int f(int, int); // #3
861//
862// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000863// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000864//
John McCall3d988d92009-12-02 08:47:38 +0000865// When we process #2, Old contains only the FunctionDecl for #1. By
866// comparing the parameter types, we see that #1 and #2 are overloaded
867// (since they have different signatures), so this routine returns
868// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000869//
John McCall3d988d92009-12-02 08:47:38 +0000870// When we process #3, Old is an overload set containing #1 and #2. We
871// compare the signatures of #3 to #1 (they're overloaded, so we do
872// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
873// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000874// signature), IsOverload returns false and MatchedDecl will be set to
875// point to the FunctionDecl for #2.
John McCalle9cccd82010-06-16 08:42:20 +0000876//
877// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
878// into a class by a using declaration. The rules for whether to hide
879// shadow declarations ignore some properties which otherwise figure
880// into a function template's signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000881Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000882Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
883 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000884 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000885 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000886 NamedDecl *OldD = *I;
887
888 bool OldIsUsingDecl = false;
889 if (isa<UsingShadowDecl>(OldD)) {
890 OldIsUsingDecl = true;
891
892 // We can always introduce two using declarations into the same
893 // context, even if they have identical signatures.
894 if (NewIsUsingDecl) continue;
895
896 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
897 }
898
Richard Smithf091e122015-09-15 01:28:55 +0000899 // A using-declaration does not conflict with another declaration
900 // if one of them is hidden.
901 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
902 continue;
903
John McCalle9cccd82010-06-16 08:42:20 +0000904 // If either declaration was introduced by a using declaration,
905 // we'll need to use slightly different rules for matching.
906 // Essentially, these rules are the normal rules, except that
907 // function templates hide function templates with different
908 // return types or template parameter lists.
909 bool UseMemberUsingDeclRules =
John McCallc70fca62013-04-03 21:19:47 +0000910 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
911 !New->getFriendObjectKind();
John McCalle9cccd82010-06-16 08:42:20 +0000912
Alp Tokera2794f92014-01-22 07:29:52 +0000913 if (FunctionDecl *OldF = OldD->getAsFunction()) {
John McCalle9cccd82010-06-16 08:42:20 +0000914 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
915 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
916 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
917 continue;
918 }
919
Alp Tokera2794f92014-01-22 07:29:52 +0000920 if (!isa<FunctionTemplateDecl>(OldD) &&
921 !shouldLinkPossiblyHiddenDecl(*I, New))
Rafael Espindola5bddd6a2013-04-15 12:49:13 +0000922 continue;
923
John McCalldaa3d6b2009-12-09 03:35:25 +0000924 Match = *I;
925 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000926 }
John McCalla8987a2942010-11-10 03:01:53 +0000927 } else if (isa<UsingDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +0000928 // We can overload with these, which can show up when doing
929 // redeclaration checks for UsingDecls.
930 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalla8987a2942010-11-10 03:01:53 +0000931 } else if (isa<TagDecl>(OldD)) {
932 // We can always overload with tags by hiding them.
John McCall84d87672009-12-10 09:41:52 +0000933 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
934 // Optimistically assume that an unresolved using decl will
935 // overload; if it doesn't, we'll have to diagnose during
936 // template instantiation.
937 } else {
John McCall1f82f242009-11-18 22:49:29 +0000938 // (C++ 13p1):
939 // Only function declarations can be overloaded; object and type
940 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000941 Match = *I;
942 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000943 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000944 }
John McCall1f82f242009-11-18 22:49:29 +0000945
John McCalldaa3d6b2009-12-09 03:35:25 +0000946 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000947}
948
Richard Smithac974a32013-06-30 09:48:50 +0000949bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
950 bool UseUsingDeclRules) {
951 // C++ [basic.start.main]p2: This function shall not be overloaded.
952 if (New->isMain())
Rafael Espindola576127d2012-12-28 14:21:58 +0000953 return false;
Rafael Espindola7cf35ef2013-01-12 01:47:40 +0000954
David Majnemerc729b0b2013-09-16 22:44:20 +0000955 // MSVCRT user defined entry points cannot be overloaded.
956 if (New->isMSVCRTEntryPoint())
957 return false;
958
John McCall1f82f242009-11-18 22:49:29 +0000959 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
960 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
961
962 // C++ [temp.fct]p2:
963 // A function template can be overloaded with other function templates
964 // and with normal (non-template) functions.
Craig Topperc3ec1492014-05-26 06:22:03 +0000965 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
John McCall1f82f242009-11-18 22:49:29 +0000966 return true;
967
968 // Is the function New an overload of the function Old?
Richard Smithac974a32013-06-30 09:48:50 +0000969 QualType OldQType = Context.getCanonicalType(Old->getType());
970 QualType NewQType = Context.getCanonicalType(New->getType());
John McCall1f82f242009-11-18 22:49:29 +0000971
972 // Compare the signatures (C++ 1.3.10) of the two functions to
973 // determine whether they are overloads. If we find any mismatch
974 // in the signature, they are overloads.
975
976 // If either of these functions is a K&R-style function (no
977 // prototype), then we consider them to have matching signatures.
978 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
979 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
980 return false;
981
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000982 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
983 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
John McCall1f82f242009-11-18 22:49:29 +0000984
985 // The signature of a function includes the types of its
986 // parameters (C++ 1.3.10), which includes the presence or absence
987 // of the ellipsis; see C++ DR 357).
988 if (OldQType != NewQType &&
Alp Toker9cacbab2014-01-20 20:26:09 +0000989 (OldType->getNumParams() != NewType->getNumParams() ||
John McCall1f82f242009-11-18 22:49:29 +0000990 OldType->isVariadic() != NewType->isVariadic() ||
Alp Toker9cacbab2014-01-20 20:26:09 +0000991 !FunctionParamTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +0000992 return true;
993
994 // C++ [temp.over.link]p4:
995 // The signature of a function template consists of its function
996 // signature, its return type and its template parameter list. The names
997 // of the template parameters are significant only for establishing the
998 // relationship between the template parameters and the rest of the
999 // signature.
1000 //
1001 // We check the return type and template parameter lists for function
1002 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +00001003 //
1004 // However, we don't consider either of these when deciding whether
1005 // a member introduced by a shadow declaration is hidden.
1006 if (!UseUsingDeclRules && NewTemplate &&
Richard Smithac974a32013-06-30 09:48:50 +00001007 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1008 OldTemplate->getTemplateParameters(),
1009 false, TPL_TemplateMatch) ||
Alp Toker314cc812014-01-25 16:55:45 +00001010 OldType->getReturnType() != NewType->getReturnType()))
John McCall1f82f242009-11-18 22:49:29 +00001011 return true;
1012
1013 // If the function is a class member, its signature includes the
Douglas Gregorb2f8aa92011-01-26 17:47:49 +00001014 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall1f82f242009-11-18 22:49:29 +00001015 //
1016 // As part of this, also check whether one of the member functions
1017 // is static, in which case they are not overloads (C++
1018 // 13.1p2). While not part of the definition of the signature,
1019 // this check is important to determine whether these functions
1020 // can be overloaded.
Richard Smith574f4f62013-01-14 05:37:29 +00001021 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1022 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
John McCall1f82f242009-11-18 22:49:29 +00001023 if (OldMethod && NewMethod &&
Richard Smith574f4f62013-01-14 05:37:29 +00001024 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1025 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1026 if (!UseUsingDeclRules &&
1027 (OldMethod->getRefQualifier() == RQ_None ||
1028 NewMethod->getRefQualifier() == RQ_None)) {
1029 // C++0x [over.load]p2:
1030 // - Member function declarations with the same name and the same
1031 // parameter-type-list as well as member function template
1032 // declarations with the same name, the same parameter-type-list, and
1033 // the same template parameter lists cannot be overloaded if any of
1034 // them, but not all, have a ref-qualifier (8.3.5).
Richard Smithac974a32013-06-30 09:48:50 +00001035 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
Richard Smith574f4f62013-01-14 05:37:29 +00001036 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
Richard Smithac974a32013-06-30 09:48:50 +00001037 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
Richard Smith574f4f62013-01-14 05:37:29 +00001038 }
1039 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001040 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001041
Richard Smith574f4f62013-01-14 05:37:29 +00001042 // We may not have applied the implicit const for a constexpr member
1043 // function yet (because we haven't yet resolved whether this is a static
1044 // or non-static member function). Add it now, on the assumption that this
1045 // is a redeclaration of OldMethod.
David Majnemer42350df2013-11-03 23:51:28 +00001046 unsigned OldQuals = OldMethod->getTypeQualifiers();
Richard Smith574f4f62013-01-14 05:37:29 +00001047 unsigned NewQuals = NewMethod->getTypeQualifiers();
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001048 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
Richard Smithe83b1d32013-06-25 18:46:26 +00001049 !isa<CXXConstructorDecl>(NewMethod))
Richard Smith574f4f62013-01-14 05:37:29 +00001050 NewQuals |= Qualifiers::Const;
David Majnemer42350df2013-11-03 23:51:28 +00001051
1052 // We do not allow overloading based off of '__restrict'.
1053 OldQuals &= ~Qualifiers::Restrict;
1054 NewQuals &= ~Qualifiers::Restrict;
1055 if (OldQuals != NewQuals)
Richard Smith574f4f62013-01-14 05:37:29 +00001056 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001057 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001058
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001059 // enable_if attributes are an order-sensitive part of the signature.
1060 for (specific_attr_iterator<EnableIfAttr>
1061 NewI = New->specific_attr_begin<EnableIfAttr>(),
1062 NewE = New->specific_attr_end<EnableIfAttr>(),
1063 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1064 OldE = Old->specific_attr_end<EnableIfAttr>();
1065 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1066 if (NewI == NewE || OldI == OldE)
1067 return true;
1068 llvm::FoldingSetNodeID NewID, OldID;
1069 NewI->getCond()->Profile(NewID, Context, true);
1070 OldI->getCond()->Profile(OldID, Context, true);
Nick Lewyckyd950ae72014-01-21 01:30:30 +00001071 if (NewID != OldID)
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001072 return true;
1073 }
1074
Artem Belevich94a55e82015-09-22 17:22:59 +00001075 if (getLangOpts().CUDA && getLangOpts().CUDATargetOverloads) {
1076 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1077 OldTarget = IdentifyCUDATarget(Old);
1078 if (NewTarget == CFT_InvalidTarget || NewTarget == CFT_Global)
1079 return false;
1080
1081 assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target.");
1082
1083 // Don't allow mixing of HD with other kinds. This guarantees that
1084 // we have only one viable function with this signature on any
1085 // side of CUDA compilation .
1086 if ((NewTarget == CFT_HostDevice) || (OldTarget == CFT_HostDevice))
1087 return false;
1088
1089 // Allow overloading of functions with same signature, but
1090 // different CUDA target attributes.
1091 return NewTarget != OldTarget;
1092 }
1093
John McCall1f82f242009-11-18 22:49:29 +00001094 // The signatures match; this is not an overload.
1095 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001096}
1097
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00001098/// \brief Checks availability of the function depending on the current
1099/// function context. Inside an unavailable function, unavailability is ignored.
1100///
1101/// \returns true if \arg FD is unavailable and current context is inside
1102/// an available function, false otherwise.
1103bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1104 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
1105}
1106
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001107/// \brief Tries a user-defined conversion from From to ToType.
1108///
1109/// Produces an implicit conversion sequence for when a standard conversion
1110/// is not an option. See TryImplicitConversion for more information.
1111static ImplicitConversionSequence
1112TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1113 bool SuppressUserConversions,
1114 bool AllowExplicit,
1115 bool InOverloadResolution,
1116 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001117 bool AllowObjCWritebackConversion,
1118 bool AllowObjCConversionOnExplicit) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001119 ImplicitConversionSequence ICS;
1120
1121 if (SuppressUserConversions) {
1122 // We're not in the case above, so there is no conversion that
1123 // we can perform.
1124 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1125 return ICS;
1126 }
1127
1128 // Attempt user-defined conversion.
Richard Smith100b24a2014-04-17 01:52:14 +00001129 OverloadCandidateSet Conversions(From->getExprLoc(),
1130 OverloadCandidateSet::CSK_Normal);
Richard Smith48372b62015-01-27 03:30:40 +00001131 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1132 Conversions, AllowExplicit,
1133 AllowObjCConversionOnExplicit)) {
1134 case OR_Success:
1135 case OR_Deleted:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001136 ICS.setUserDefined();
Ismail Pazarbasidf1a2802014-01-24 13:16:17 +00001137 ICS.UserDefined.Before.setAsIdentityConversion();
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001138 // C++ [over.ics.user]p4:
1139 // A conversion of an expression of class type to the same class
1140 // type is given Exact Match rank, and a conversion of an
1141 // expression of class type to a base class of that type is
1142 // given Conversion rank, in spite of the fact that a copy
1143 // constructor (i.e., a user-defined conversion function) is
1144 // called for those cases.
1145 if (CXXConstructorDecl *Constructor
1146 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1147 QualType FromCanon
1148 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1149 QualType ToCanon
1150 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1151 if (Constructor->isCopyConstructor() &&
1152 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1153 // Turn this into a "standard" conversion sequence, so that it
1154 // gets ranked with standard conversion sequences.
1155 ICS.setStandard();
1156 ICS.Standard.setAsIdentityConversion();
1157 ICS.Standard.setFromType(From->getType());
1158 ICS.Standard.setAllToTypes(ToType);
1159 ICS.Standard.CopyConstructor = Constructor;
1160 if (ToCanon != FromCanon)
1161 ICS.Standard.Second = ICK_Derived_To_Base;
1162 }
1163 }
Richard Smith48372b62015-01-27 03:30:40 +00001164 break;
1165
1166 case OR_Ambiguous:
Richard Smith1bbaba82015-01-27 23:23:39 +00001167 ICS.setAmbiguous();
1168 ICS.Ambiguous.setFromType(From->getType());
1169 ICS.Ambiguous.setToType(ToType);
1170 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1171 Cand != Conversions.end(); ++Cand)
1172 if (Cand->Viable)
1173 ICS.Ambiguous.addConversion(Cand->Function);
1174 break;
Richard Smith48372b62015-01-27 03:30:40 +00001175
1176 // Fall through.
1177 case OR_No_Viable_Function:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001178 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Richard Smith48372b62015-01-27 03:30:40 +00001179 break;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001180 }
1181
1182 return ICS;
1183}
1184
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001185/// TryImplicitConversion - Attempt to perform an implicit conversion
1186/// from the given expression (Expr) to the given type (ToType). This
1187/// function returns an implicit conversion sequence that can be used
1188/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001189///
1190/// void f(float f);
1191/// void g(int i) { f(i); }
1192///
1193/// this routine would produce an implicit conversion sequence to
1194/// describe the initialization of f from i, which will be a standard
1195/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1196/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1197//
1198/// Note that this routine only determines how the conversion can be
1199/// performed; it does not actually perform the conversion. As such,
1200/// it will not produce any diagnostics if no conversion is available,
1201/// but will instead return an implicit conversion sequence of kind
1202/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +00001203///
1204/// If @p SuppressUserConversions, then user-defined conversions are
1205/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +00001206/// If @p AllowExplicit, then explicit user-defined conversions are
1207/// permitted.
John McCall31168b02011-06-15 23:02:42 +00001208///
1209/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1210/// writeback conversion, which allows __autoreleasing id* parameters to
1211/// be initialized with __strong id* or __weak id* arguments.
John McCall5c32be02010-08-24 20:38:10 +00001212static ImplicitConversionSequence
1213TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1214 bool SuppressUserConversions,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001215 bool AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001216 bool InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001217 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001218 bool AllowObjCWritebackConversion,
1219 bool AllowObjCConversionOnExplicit) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001220 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +00001221 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001222 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall0d1da222010-01-12 00:44:57 +00001223 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +00001224 return ICS;
1225 }
1226
David Blaikiebbafb8a2012-03-11 07:00:24 +00001227 if (!S.getLangOpts().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +00001228 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +00001229 return ICS;
1230 }
1231
Douglas Gregor836a7e82010-08-11 02:15:33 +00001232 // C++ [over.ics.user]p4:
1233 // A conversion of an expression of class type to the same class
1234 // type is given Exact Match rank, and a conversion of an
1235 // expression of class type to a base class of that type is
1236 // given Conversion rank, in spite of the fact that a copy/move
1237 // constructor (i.e., a user-defined conversion function) is
1238 // called for those cases.
1239 QualType FromType = From->getType();
1240 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00001241 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1242 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001243 ICS.setStandard();
1244 ICS.Standard.setAsIdentityConversion();
1245 ICS.Standard.setFromType(FromType);
1246 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001247
Douglas Gregor5ab11652010-04-17 22:01:05 +00001248 // We don't actually check at this point whether there is a valid
1249 // copy/move constructor, since overloading just assumes that it
1250 // exists. When we actually perform initialization, we'll find the
1251 // appropriate constructor to copy the returned object, if needed.
Craig Topperc3ec1492014-05-26 06:22:03 +00001252 ICS.Standard.CopyConstructor = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001253
Douglas Gregor5ab11652010-04-17 22:01:05 +00001254 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +00001255 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +00001256 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001257
Douglas Gregor836a7e82010-08-11 02:15:33 +00001258 return ICS;
1259 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001260
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001261 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1262 AllowExplicit, InOverloadResolution, CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001263 AllowObjCWritebackConversion,
1264 AllowObjCConversionOnExplicit);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001265}
1266
John McCall31168b02011-06-15 23:02:42 +00001267ImplicitConversionSequence
1268Sema::TryImplicitConversion(Expr *From, QualType ToType,
1269 bool SuppressUserConversions,
1270 bool AllowExplicit,
1271 bool InOverloadResolution,
1272 bool CStyle,
1273 bool AllowObjCWritebackConversion) {
Richard Smith17c00b42014-11-12 01:24:00 +00001274 return ::TryImplicitConversion(*this, From, ToType,
1275 SuppressUserConversions, AllowExplicit,
1276 InOverloadResolution, CStyle,
1277 AllowObjCWritebackConversion,
1278 /*AllowObjCConversionOnExplicit=*/false);
John McCall5c32be02010-08-24 20:38:10 +00001279}
1280
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001281/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley01296292011-04-08 18:41:53 +00001282/// expression From to the type ToType. Returns the
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001283/// converted expression. Flavor is the kind of conversion we're
1284/// performing, used in the error message. If @p AllowExplicit,
1285/// explicit user-defined conversions are permitted.
John Wiegley01296292011-04-08 18:41:53 +00001286ExprResult
1287Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redlcc152642011-10-16 18:19:06 +00001288 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001289 ImplicitConversionSequence ICS;
Sebastian Redlcc152642011-10-16 18:19:06 +00001290 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001291}
1292
John Wiegley01296292011-04-08 18:41:53 +00001293ExprResult
1294Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001295 AssignmentAction Action, bool AllowExplicit,
Sebastian Redlcc152642011-10-16 18:19:06 +00001296 ImplicitConversionSequence& ICS) {
John McCall526ab472011-10-25 17:37:35 +00001297 if (checkPlaceholderForOverload(*this, From))
1298 return ExprError();
1299
John McCall31168b02011-06-15 23:02:42 +00001300 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1301 bool AllowObjCWritebackConversion
David Blaikiebbafb8a2012-03-11 07:00:24 +00001302 = getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001303 (Action == AA_Passing || Action == AA_Sending);
Fariborz Jahanian381edf52013-12-16 22:54:37 +00001304 if (getLangOpts().ObjC1)
1305 CheckObjCBridgeRelatedConversions(From->getLocStart(),
1306 ToType, From->getType(), From);
Richard Smith17c00b42014-11-12 01:24:00 +00001307 ICS = ::TryImplicitConversion(*this, From, ToType,
1308 /*SuppressUserConversions=*/false,
1309 AllowExplicit,
1310 /*InOverloadResolution=*/false,
1311 /*CStyle=*/false,
1312 AllowObjCWritebackConversion,
1313 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001314 return PerformImplicitConversion(From, ToType, ICS, Action);
1315}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001316
1317/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001318/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth53e61b02011-06-18 01:19:03 +00001319bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1320 QualType &ResultTy) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001321 if (Context.hasSameUnqualifiedType(FromType, ToType))
1322 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001323
John McCall991eb4b2010-12-21 00:44:39 +00001324 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1325 // where F adds one of the following at most once:
1326 // - a pointer
1327 // - a member pointer
1328 // - a block pointer
1329 CanQualType CanTo = Context.getCanonicalType(ToType);
1330 CanQualType CanFrom = Context.getCanonicalType(FromType);
1331 Type::TypeClass TyClass = CanTo->getTypeClass();
1332 if (TyClass != CanFrom->getTypeClass()) return false;
1333 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1334 if (TyClass == Type::Pointer) {
1335 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1336 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1337 } else if (TyClass == Type::BlockPointer) {
1338 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1339 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1340 } else if (TyClass == Type::MemberPointer) {
1341 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1342 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1343 } else {
1344 return false;
1345 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001346
John McCall991eb4b2010-12-21 00:44:39 +00001347 TyClass = CanTo->getTypeClass();
1348 if (TyClass != CanFrom->getTypeClass()) return false;
1349 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1350 return false;
1351 }
1352
1353 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1354 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1355 if (!EInfo.getNoReturn()) return false;
1356
1357 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1358 assert(QualType(FromFn, 0).isCanonical());
1359 if (QualType(FromFn, 0) != CanTo) return false;
1360
1361 ResultTy = ToType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001362 return true;
1363}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001364
Douglas Gregor46188682010-05-18 22:42:18 +00001365/// \brief Determine whether the conversion from FromType to ToType is a valid
1366/// vector conversion.
1367///
1368/// \param ICK Will be set to the vector conversion kind, if this is a vector
1369/// conversion.
John McCall9b595db2014-02-04 23:58:19 +00001370static bool IsVectorConversion(Sema &S, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001371 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregor46188682010-05-18 22:42:18 +00001372 // We need at least one of these types to be a vector type to have a vector
1373 // conversion.
1374 if (!ToType->isVectorType() && !FromType->isVectorType())
1375 return false;
1376
1377 // Identical types require no conversions.
John McCall9b595db2014-02-04 23:58:19 +00001378 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor46188682010-05-18 22:42:18 +00001379 return false;
1380
1381 // There are no conversions between extended vector types, only identity.
1382 if (ToType->isExtVectorType()) {
1383 // There are no conversions between extended vector types other than the
1384 // identity conversion.
1385 if (FromType->isExtVectorType())
1386 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001387
Douglas Gregor46188682010-05-18 22:42:18 +00001388 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +00001389 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +00001390 ICK = ICK_Vector_Splat;
1391 return true;
1392 }
1393 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001394
1395 // We can perform the conversion between vector types in the following cases:
1396 // 1)vector types are equivalent AltiVec and GCC vector types
1397 // 2)lax vector conversions are permitted and the vector types are of the
1398 // same size
1399 if (ToType->isVectorType() && FromType->isVectorType()) {
John McCall9b595db2014-02-04 23:58:19 +00001400 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1401 S.isLaxVectorConversion(FromType, ToType)) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001402 ICK = ICK_Vector_Conversion;
1403 return true;
1404 }
Douglas Gregor46188682010-05-18 22:42:18 +00001405 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001406
Douglas Gregor46188682010-05-18 22:42:18 +00001407 return false;
1408}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001409
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001410static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1411 bool InOverloadResolution,
1412 StandardConversionSequence &SCS,
1413 bool CStyle);
Douglas Gregorc79862f2012-04-12 17:51:55 +00001414
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001415/// IsStandardConversion - Determines whether there is a standard
1416/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1417/// expression From to the type ToType. Standard conversion sequences
1418/// only consider non-class types; for conversions that involve class
1419/// types, use TryImplicitConversion. If a conversion exists, SCS will
1420/// contain the standard conversion sequence required to perform this
1421/// conversion and this routine will return true. Otherwise, this
1422/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +00001423static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1424 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +00001425 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +00001426 bool CStyle,
1427 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001428 QualType FromType = From->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001429
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001430 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +00001431 SCS.setAsIdentityConversion();
Douglas Gregor47d3f272008-12-19 17:40:08 +00001432 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +00001433 SCS.setFromType(FromType);
Craig Topperc3ec1492014-05-26 06:22:03 +00001434 SCS.CopyConstructor = nullptr;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001435
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001436 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +00001437 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001438 if (FromType->isRecordType() || ToType->isRecordType()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001439 if (S.getLangOpts().CPlusPlus)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001440 return false;
1441
Mike Stump11289f42009-09-09 15:08:12 +00001442 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001443 }
1444
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001445 // The first conversion can be an lvalue-to-rvalue conversion,
1446 // array-to-pointer conversion, or function-to-pointer conversion
1447 // (C++ 4p1).
1448
John McCall5c32be02010-08-24 20:38:10 +00001449 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001450 DeclAccessPair AccessPair;
1451 if (FunctionDecl *Fn
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001452 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall5c32be02010-08-24 20:38:10 +00001453 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001454 // We were able to resolve the address of the overloaded function,
1455 // so we can convert to the type of that function.
1456 FromType = Fn->getType();
Ehsan Akhgaric3ad3ba2014-07-22 20:20:14 +00001457 SCS.setFromType(FromType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00001458
1459 // we can sometimes resolve &foo<int> regardless of ToType, so check
1460 // if the type matches (identity) or we are converting to bool
1461 if (!S.Context.hasSameUnqualifiedType(
1462 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1463 QualType resultTy;
1464 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth53e61b02011-06-18 01:19:03 +00001465 if (!S.IsNoReturnConversion(FromType,
Douglas Gregorb491ed32011-02-19 21:32:49 +00001466 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1467 // otherwise, only a boolean conversion is standard
1468 if (!ToType->isBooleanType())
1469 return false;
Douglas Gregor980fb162010-04-29 18:24:40 +00001470 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001471
Chandler Carruthffce2452011-03-29 08:08:18 +00001472 // Check if the "from" expression is taking the address of an overloaded
1473 // function and recompute the FromType accordingly. Take advantage of the
1474 // fact that non-static member functions *must* have such an address-of
1475 // expression.
1476 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1477 if (Method && !Method->isStatic()) {
1478 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1479 "Non-unary operator on non-static member address");
1480 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1481 == UO_AddrOf &&
1482 "Non-address-of operator on non-static member address");
1483 const Type *ClassType
1484 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1485 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruth7750f762011-03-29 18:38:10 +00001486 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1487 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1488 UO_AddrOf &&
Chandler Carruthffce2452011-03-29 08:08:18 +00001489 "Non-address-of operator for overloaded function expression");
1490 FromType = S.Context.getPointerType(FromType);
1491 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001492
Douglas Gregor980fb162010-04-29 18:24:40 +00001493 // Check that we've computed the proper type after overload resolution.
Chandler Carruthffce2452011-03-29 08:08:18 +00001494 assert(S.Context.hasSameType(
1495 FromType,
1496 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001497 } else {
1498 return false;
1499 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001500 }
John McCall154a2fd2011-08-30 00:57:29 +00001501 // Lvalue-to-rvalue conversion (C++11 4.1):
1502 // A glvalue (3.10) of a non-function, non-array type T can
1503 // be converted to a prvalue.
1504 bool argIsLValue = From->isGLValue();
John McCall086a4642010-11-24 05:12:34 +00001505 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001506 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001507 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001508 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001509
Douglas Gregorc79862f2012-04-12 17:51:55 +00001510 // C11 6.3.2.1p2:
1511 // ... if the lvalue has atomic type, the value has the non-atomic version
1512 // of the type of the lvalue ...
1513 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1514 FromType = Atomic->getValueType();
1515
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001516 // If T is a non-class type, the type of the rvalue is the
1517 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001518 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1519 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001520 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001521 } else if (FromType->isArrayType()) {
1522 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001523 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001524
1525 // An lvalue or rvalue of type "array of N T" or "array of unknown
1526 // bound of T" can be converted to an rvalue of type "pointer to
1527 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001528 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001529
John McCall5c32be02010-08-24 20:38:10 +00001530 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00001531 // This conversion is deprecated in C++03 (D.4)
Douglas Gregore489a7d2010-02-28 18:30:25 +00001532 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001533
1534 // For the purpose of ranking in overload resolution
1535 // (13.3.3.1.1), this conversion is considered an
1536 // array-to-pointer conversion followed by a qualification
1537 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001538 SCS.Second = ICK_Identity;
1539 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001540 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001541 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001542 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001543 }
John McCall086a4642010-11-24 05:12:34 +00001544 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001545 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001546 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001547
1548 // An lvalue of function type T can be converted to an rvalue of
1549 // type "pointer to T." The result is a pointer to the
1550 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001551 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001552 } else {
1553 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001554 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001555 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001556 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001557
1558 // The second conversion can be an integral promotion, floating
1559 // point promotion, integral conversion, floating point conversion,
1560 // floating-integral conversion, pointer conversion,
1561 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001562 // For overloading in C, this can also be a "compatible-type"
1563 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001564 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001565 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001566 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001567 // The unqualified versions of the types are the same: there's no
1568 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001569 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001570 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001571 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001572 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001573 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001574 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001575 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001576 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001577 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001578 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001579 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001580 SCS.Second = ICK_Complex_Promotion;
1581 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001582 } else if (ToType->isBooleanType() &&
1583 (FromType->isArithmeticType() ||
1584 FromType->isAnyPointerType() ||
1585 FromType->isBlockPointerType() ||
1586 FromType->isMemberPointerType() ||
1587 FromType->isNullPtrType())) {
1588 // Boolean conversions (C++ 4.12).
1589 SCS.Second = ICK_Boolean_Conversion;
1590 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001591 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001592 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001593 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001594 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001595 FromType = ToType.getUnqualifiedType();
Richard Smithb8a98242013-05-10 20:29:50 +00001596 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001597 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001598 SCS.Second = ICK_Complex_Conversion;
1599 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001600 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1601 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001602 // Complex-real conversions (C99 6.3.1.7)
1603 SCS.Second = ICK_Complex_Real;
1604 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001605 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001606 // Floating point conversions (C++ 4.8).
1607 SCS.Second = ICK_Floating_Conversion;
1608 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001609 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001610 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001611 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001612 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001613 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001614 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001615 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001616 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCall31168b02011-06-15 23:02:42 +00001617 SCS.Second = ICK_Block_Pointer_Conversion;
1618 } else if (AllowObjCWritebackConversion &&
1619 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1620 SCS.Second = ICK_Writeback_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001621 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1622 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001623 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001624 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001625 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregoraec25842011-04-26 23:16:46 +00001626 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001627 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall5c32be02010-08-24 20:38:10 +00001628 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001629 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001630 SCS.Second = ICK_Pointer_Member;
John McCall9b595db2014-02-04 23:58:19 +00001631 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001632 SCS.Second = SecondICK;
1633 FromType = ToType.getUnqualifiedType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001634 } else if (!S.getLangOpts().CPlusPlus &&
John McCall5c32be02010-08-24 20:38:10 +00001635 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001636 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001637 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001638 FromType = ToType.getUnqualifiedType();
Chandler Carruth53e61b02011-06-18 01:19:03 +00001639 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001640 // Treat a conversion that strips "noreturn" as an identity conversion.
1641 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001642 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1643 InOverloadResolution,
1644 SCS, CStyle)) {
1645 SCS.Second = ICK_TransparentUnionConversion;
1646 FromType = ToType;
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001647 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1648 CStyle)) {
1649 // tryAtomicConversion has updated the standard conversion sequence
Douglas Gregorc79862f2012-04-12 17:51:55 +00001650 // appropriately.
1651 return true;
Guy Benyei259f9f42013-02-07 16:05:33 +00001652 } else if (ToType->isEventT() &&
1653 From->isIntegerConstantExpr(S.getASTContext()) &&
1654 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1655 SCS.Second = ICK_Zero_Event_Conversion;
1656 FromType = ToType;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001657 } else {
1658 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001659 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001660 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001661 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001662
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001663 QualType CanonFrom;
1664 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001665 // The third conversion can be a qualification conversion (C++ 4p1).
John McCall31168b02011-06-15 23:02:42 +00001666 bool ObjCLifetimeConversion;
1667 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1668 ObjCLifetimeConversion)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001669 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001670 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001671 FromType = ToType;
John McCall5c32be02010-08-24 20:38:10 +00001672 CanonFrom = S.Context.getCanonicalType(FromType);
1673 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001674 } else {
1675 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001676 SCS.Third = ICK_Identity;
1677
Mike Stump11289f42009-09-09 15:08:12 +00001678 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001679 // [...] Any difference in top-level cv-qualification is
1680 // subsumed by the initialization itself and does not constitute
1681 // a conversion. [...]
John McCall5c32be02010-08-24 20:38:10 +00001682 CanonFrom = S.Context.getCanonicalType(FromType);
1683 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001684 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001685 == CanonTo.getLocalUnqualifiedType() &&
Matt Arsenault7d36c012013-02-26 21:15:54 +00001686 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001687 FromType = ToType;
1688 CanonFrom = CanonTo;
1689 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001690 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001691 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001692
1693 // If we have not converted the argument type to the parameter type,
1694 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001695 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001696 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001697
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001698 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001699}
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001700
1701static bool
1702IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1703 QualType &ToType,
1704 bool InOverloadResolution,
1705 StandardConversionSequence &SCS,
1706 bool CStyle) {
1707
1708 const RecordType *UT = ToType->getAsUnionType();
1709 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1710 return false;
1711 // The field to initialize within the transparent union.
1712 RecordDecl *UD = UT->getDecl();
1713 // It's compatible if the expression matches any of the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001714 for (const auto *it : UD->fields()) {
John McCall31168b02011-06-15 23:02:42 +00001715 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1716 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001717 ToType = it->getType();
1718 return true;
1719 }
1720 }
1721 return false;
1722}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001723
1724/// IsIntegralPromotion - Determines whether the conversion from the
1725/// expression From (whose potentially-adjusted type is FromType) to
1726/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1727/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001728bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001729 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001730 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001731 if (!To) {
1732 return false;
1733 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001734
1735 // An rvalue of type char, signed char, unsigned char, short int, or
1736 // unsigned short int can be converted to an rvalue of type int if
1737 // int can represent all the values of the source type; otherwise,
1738 // the source rvalue can be converted to an rvalue of type unsigned
1739 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001740 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1741 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001742 if (// We can promote any signed, promotable integer type to an int
1743 (FromType->isSignedIntegerType() ||
1744 // We can promote any unsigned integer type whose size is
1745 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001746 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001747 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001748 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001749 }
1750
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001751 return To->getKind() == BuiltinType::UInt;
1752 }
1753
Richard Smithb9c5a602012-09-13 21:18:54 +00001754 // C++11 [conv.prom]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001755 // A prvalue of an unscoped enumeration type whose underlying type is not
1756 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1757 // following types that can represent all the values of the enumeration
1758 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1759 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001760 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001761 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001762 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001763 // with lowest integer conversion rank (4.13) greater than the rank of long
1764 // long in which all the values of the enumeration can be represented. If
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001765 // there are two such extended types, the signed one is chosen.
Richard Smithb9c5a602012-09-13 21:18:54 +00001766 // C++11 [conv.prom]p4:
1767 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1768 // can be converted to a prvalue of its underlying type. Moreover, if
1769 // integral promotion can be applied to its underlying type, a prvalue of an
1770 // unscoped enumeration type whose underlying type is fixed can also be
1771 // converted to a prvalue of the promoted underlying type.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001772 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1773 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1774 // provided for a scoped enumeration.
1775 if (FromEnumType->getDecl()->isScoped())
1776 return false;
1777
Richard Smithb9c5a602012-09-13 21:18:54 +00001778 // We can perform an integral promotion to the underlying type of the enum,
Richard Smithac8c1752015-03-28 00:31:40 +00001779 // even if that's not the promoted type. Note that the check for promoting
1780 // the underlying type is based on the type alone, and does not consider
1781 // the bitfield-ness of the actual source expression.
Richard Smithb9c5a602012-09-13 21:18:54 +00001782 if (FromEnumType->getDecl()->isFixed()) {
1783 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1784 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
Richard Smithac8c1752015-03-28 00:31:40 +00001785 IsIntegralPromotion(nullptr, Underlying, ToType);
Richard Smithb9c5a602012-09-13 21:18:54 +00001786 }
1787
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001788 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001789 if (ToType->isIntegerType() &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001790 !RequireCompleteType(From->getLocStart(), FromType, 0))
Richard Smith88f4bba2015-03-26 00:16:07 +00001791 return Context.hasSameUnqualifiedType(
1792 ToType, FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001793 }
John McCall56774992009-12-09 09:09:27 +00001794
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001795 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001796 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1797 // to an rvalue a prvalue of the first of the following types that can
1798 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001799 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001800 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001801 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001802 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001803 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001804 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001805 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001806 // Determine whether the type we're converting from is signed or
1807 // unsigned.
David Majnemerfa01a582011-07-22 21:09:04 +00001808 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001809 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001810
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001811 // The types we'll try to promote to, in the appropriate
1812 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001813 QualType PromoteTypes[6] = {
1814 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001815 Context.LongTy, Context.UnsignedLongTy ,
1816 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001817 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001818 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001819 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1820 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001821 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001822 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1823 // We found the type that we can promote to. If this is the
1824 // type we wanted, we have a promotion. Otherwise, no
1825 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001826 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001827 }
1828 }
1829 }
1830
1831 // An rvalue for an integral bit-field (9.6) can be converted to an
1832 // rvalue of type int if int can represent all the values of the
1833 // bit-field; otherwise, it can be converted to unsigned int if
1834 // unsigned int can represent all the values of the bit-field. If
1835 // the bit-field is larger yet, no integral promotion applies to
1836 // it. If the bit-field has an enumerated type, it is treated as any
1837 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001838 // FIXME: We should delay checking of bit-fields until we actually perform the
1839 // conversion.
Richard Smith88f4bba2015-03-26 00:16:07 +00001840 if (From) {
John McCalld25db7e2013-05-06 21:39:12 +00001841 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
Richard Smith88f4bba2015-03-26 00:16:07 +00001842 llvm::APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001843 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001844 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
Richard Smith88f4bba2015-03-26 00:16:07 +00001845 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
Douglas Gregor71235ec2009-05-02 02:18:30 +00001846 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001847
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001848 // Are we promoting to an int from a bitfield that fits in an int?
1849 if (BitWidth < ToSize ||
1850 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1851 return To->getKind() == BuiltinType::Int;
1852 }
Mike Stump11289f42009-09-09 15:08:12 +00001853
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001854 // Are we promoting to an unsigned int from an unsigned bitfield
1855 // that fits into an unsigned int?
1856 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1857 return To->getKind() == BuiltinType::UInt;
1858 }
Mike Stump11289f42009-09-09 15:08:12 +00001859
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001860 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001861 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001862 }
Richard Smith88f4bba2015-03-26 00:16:07 +00001863 }
Mike Stump11289f42009-09-09 15:08:12 +00001864
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001865 // An rvalue of type bool can be converted to an rvalue of type int,
1866 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001867 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001868 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001869 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001870
1871 return false;
1872}
1873
1874/// IsFloatingPointPromotion - Determines whether the conversion from
1875/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1876/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001877bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001878 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1879 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001880 /// An rvalue of type float can be converted to an rvalue of type
1881 /// double. (C++ 4.6p1).
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001882 if (FromBuiltin->getKind() == BuiltinType::Float &&
1883 ToBuiltin->getKind() == BuiltinType::Double)
1884 return true;
1885
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001886 // C99 6.3.1.5p1:
1887 // When a float is promoted to double or long double, or a
1888 // double is promoted to long double [...].
David Blaikiebbafb8a2012-03-11 07:00:24 +00001889 if (!getLangOpts().CPlusPlus &&
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001890 (FromBuiltin->getKind() == BuiltinType::Float ||
1891 FromBuiltin->getKind() == BuiltinType::Double) &&
1892 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1893 return true;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001894
1895 // Half can be promoted to float.
Joey Goulydd7f4562013-01-23 11:56:20 +00001896 if (!getLangOpts().NativeHalfType &&
1897 FromBuiltin->getKind() == BuiltinType::Half &&
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001898 ToBuiltin->getKind() == BuiltinType::Float)
1899 return true;
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001900 }
1901
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001902 return false;
1903}
1904
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001905/// \brief Determine if a conversion is a complex promotion.
1906///
1907/// A complex promotion is defined as a complex -> complex conversion
1908/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001909/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001910bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001911 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001912 if (!FromComplex)
1913 return false;
1914
John McCall9dd450b2009-09-21 23:43:11 +00001915 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001916 if (!ToComplex)
1917 return false;
1918
1919 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001920 ToComplex->getElementType()) ||
Craig Topperc3ec1492014-05-26 06:22:03 +00001921 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001922 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001923}
1924
Douglas Gregor237f96c2008-11-26 23:31:11 +00001925/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1926/// the pointer type FromPtr to a pointer to type ToPointee, with the
1927/// same type qualifiers as FromPtr has on its pointee type. ToType,
1928/// if non-empty, will be a pointer to ToType that may or may not have
1929/// the right set of qualifiers on its pointee.
John McCall31168b02011-06-15 23:02:42 +00001930///
Mike Stump11289f42009-09-09 15:08:12 +00001931static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001932BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001933 QualType ToPointee, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00001934 ASTContext &Context,
1935 bool StripObjCLifetime = false) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001936 assert((FromPtr->getTypeClass() == Type::Pointer ||
1937 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1938 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001939
John McCall31168b02011-06-15 23:02:42 +00001940 /// Conversions to 'id' subsume cv-qualifier conversions.
1941 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00001942 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001943
1944 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001945 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00001946 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001947 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001948
John McCall31168b02011-06-15 23:02:42 +00001949 if (StripObjCLifetime)
1950 Quals.removeObjCLifetime();
1951
Mike Stump11289f42009-09-09 15:08:12 +00001952 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001953 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001954 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001955 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001956 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001957
1958 // Build a pointer to ToPointee. It has the right qualifiers
1959 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001960 if (isa<ObjCObjectPointerType>(ToType))
1961 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00001962 return Context.getPointerType(ToPointee);
1963 }
1964
1965 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001966 QualType QualifiedCanonToPointee
1967 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001968
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001969 if (isa<ObjCObjectPointerType>(ToType))
1970 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1971 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001972}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001973
Mike Stump11289f42009-09-09 15:08:12 +00001974static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001975 bool InOverloadResolution,
1976 ASTContext &Context) {
1977 // Handle value-dependent integral null pointer constants correctly.
1978 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1979 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001980 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00001981 return !InOverloadResolution;
1982
Douglas Gregor56751b52009-09-25 04:25:58 +00001983 return Expr->isNullPointerConstant(Context,
1984 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1985 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001986}
Mike Stump11289f42009-09-09 15:08:12 +00001987
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001988/// IsPointerConversion - Determines whether the conversion of the
1989/// expression From, which has the (possibly adjusted) type FromType,
1990/// can be converted to the type ToType via a pointer conversion (C++
1991/// 4.10). If so, returns true and places the converted type (that
1992/// might differ from ToType in its cv-qualifiers at some level) into
1993/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001994///
Douglas Gregora29dc052008-11-27 01:19:21 +00001995/// This routine also supports conversions to and from block pointers
1996/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1997/// pointers to interfaces. FIXME: Once we've determined the
1998/// appropriate overloading rules for Objective-C, we may want to
1999/// split the Objective-C checks into a different routine; however,
2000/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00002001/// conversions, so for now they live here. IncompatibleObjC will be
2002/// set if the conversion is an allowed Objective-C conversion that
2003/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002004bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00002005 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00002006 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00002007 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00002008 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00002009 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2010 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00002011 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00002012
Mike Stump11289f42009-09-09 15:08:12 +00002013 // Conversion from a null pointer constant to any Objective-C pointer type.
2014 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002015 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00002016 ConvertedType = ToType;
2017 return true;
2018 }
2019
Douglas Gregor231d1c62008-11-27 00:15:41 +00002020 // Blocks: Block pointers can be converted to void*.
2021 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002022 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00002023 ConvertedType = ToType;
2024 return true;
2025 }
2026 // Blocks: A null pointer constant can be converted to a block
2027 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00002028 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002029 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00002030 ConvertedType = ToType;
2031 return true;
2032 }
2033
Sebastian Redl576fd422009-05-10 18:38:11 +00002034 // If the left-hand-side is nullptr_t, the right side can be a null
2035 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00002036 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002037 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00002038 ConvertedType = ToType;
2039 return true;
2040 }
2041
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002042 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002043 if (!ToTypePtr)
2044 return false;
2045
2046 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00002047 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002048 ConvertedType = ToType;
2049 return true;
2050 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002051
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002052 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002053 // , including objective-c pointers.
2054 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00002055 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002056 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002057 ConvertedType = BuildSimilarlyQualifiedPointerType(
2058 FromType->getAs<ObjCObjectPointerType>(),
2059 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002060 ToType, Context);
2061 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002062 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002063 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002064 if (!FromTypePtr)
2065 return false;
2066
2067 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002068
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002069 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-08-18 21:25:30 +00002070 // pointer conversion, so don't do all of the work below.
2071 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2072 return false;
2073
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002074 // An rvalue of type "pointer to cv T," where T is an object type,
2075 // can be converted to an rvalue of type "pointer to cv void" (C++
2076 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00002077 if (FromPointeeType->isIncompleteOrObjectType() &&
2078 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002079 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002080 ToPointeeType,
John McCall31168b02011-06-15 23:02:42 +00002081 ToType, Context,
2082 /*StripObjCLifetime=*/true);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002083 return true;
2084 }
2085
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002086 // MSVC allows implicit function to void* type conversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002087 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002088 ToPointeeType->isVoidType()) {
2089 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2090 ToPointeeType,
2091 ToType, Context);
2092 return true;
2093 }
2094
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002095 // When we're overloading in C, we allow a special kind of pointer
2096 // conversion for compatible-but-not-identical pointee types.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002097 if (!getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002098 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002099 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002100 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00002101 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002102 return true;
2103 }
2104
Douglas Gregor5c407d92008-10-23 00:40:37 +00002105 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002106 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00002107 // An rvalue of type "pointer to cv D," where D is a class type,
2108 // can be converted to an rvalue of type "pointer to cv B," where
2109 // B is a base class (clause 10) of D. If B is an inaccessible
2110 // (clause 11) or ambiguous (10.2) base class of D, a program that
2111 // necessitates this conversion is ill-formed. The result of the
2112 // conversion is a pointer to the base class sub-object of the
2113 // derived class object. The null pointer value is converted to
2114 // the null pointer value of the destination type.
2115 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00002116 // Note that we do not check for ambiguity or inaccessibility
2117 // here. That is handled by CheckPointerConversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002118 if (getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002119 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00002120 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002121 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00002122 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002123 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002124 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002125 ToType, Context);
2126 return true;
2127 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002128
Fariborz Jahanianbc2ee932011-04-14 20:33:36 +00002129 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2130 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2131 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2132 ToPointeeType,
2133 ToType, Context);
2134 return true;
2135 }
2136
Douglas Gregora119f102008-12-19 19:13:09 +00002137 return false;
2138}
Douglas Gregoraec25842011-04-26 23:16:46 +00002139
2140/// \brief Adopt the given qualifiers for the given type.
2141static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2142 Qualifiers TQs = T.getQualifiers();
2143
2144 // Check whether qualifiers already match.
2145 if (TQs == Qs)
2146 return T;
2147
2148 if (Qs.compatiblyIncludes(TQs))
2149 return Context.getQualifiedType(T, Qs);
2150
2151 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2152}
Douglas Gregora119f102008-12-19 19:13:09 +00002153
2154/// isObjCPointerConversion - Determines whether this is an
2155/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2156/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00002157bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00002158 QualType& ConvertedType,
2159 bool &IncompatibleObjC) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002160 if (!getLangOpts().ObjC1)
Douglas Gregora119f102008-12-19 19:13:09 +00002161 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002162
Douglas Gregoraec25842011-04-26 23:16:46 +00002163 // The set of qualifiers on the type we're converting from.
2164 Qualifiers FromQualifiers = FromType.getQualifiers();
2165
Steve Naroff7cae42b2009-07-10 23:34:53 +00002166 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00002167 const ObjCObjectPointerType* ToObjCPtr =
2168 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00002169 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00002170 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002171
Steve Naroff7cae42b2009-07-10 23:34:53 +00002172 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002173 // If the pointee types are the same (ignoring qualifications),
2174 // then this is not a pointer conversion.
2175 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2176 FromObjCPtr->getPointeeType()))
2177 return false;
2178
Douglas Gregorab209d82015-07-07 03:58:42 +00002179 // Conversion between Objective-C pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00002180 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002181 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2182 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002183 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002184 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2185 FromObjCPtr->getPointeeType()))
2186 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002187 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002188 ToObjCPtr->getPointeeType(),
2189 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002190 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002191 return true;
2192 }
2193
2194 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2195 // Okay: this is some kind of implicit downcast of Objective-C
2196 // interfaces, which is permitted. However, we're going to
2197 // complain about it.
2198 IncompatibleObjC = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002199 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002200 ToObjCPtr->getPointeeType(),
2201 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002202 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002203 return true;
2204 }
Mike Stump11289f42009-09-09 15:08:12 +00002205 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00002206 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00002207 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002208 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002209 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002210 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002211 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002212 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002213 // to a block pointer type.
2214 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002215 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002216 return true;
2217 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002218 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002219 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002220 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002221 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002222 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002223 // pointer to any object.
Douglas Gregoraec25842011-04-26 23:16:46 +00002224 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002225 return true;
2226 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002227 else
Douglas Gregora119f102008-12-19 19:13:09 +00002228 return false;
2229
Douglas Gregor033f56d2008-12-23 00:53:59 +00002230 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002231 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002232 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00002233 else if (const BlockPointerType *FromBlockPtr =
2234 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00002235 FromPointeeType = FromBlockPtr->getPointeeType();
2236 else
Douglas Gregora119f102008-12-19 19:13:09 +00002237 return false;
2238
Douglas Gregora119f102008-12-19 19:13:09 +00002239 // If we have pointers to pointers, recursively check whether this
2240 // is an Objective-C conversion.
2241 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2242 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2243 IncompatibleObjC)) {
2244 // We always complain about this conversion.
2245 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002246 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002247 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002248 return true;
2249 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002250 // Allow conversion of pointee being objective-c pointer to another one;
2251 // as in I* to id.
2252 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2253 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2254 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2255 IncompatibleObjC)) {
John McCall31168b02011-06-15 23:02:42 +00002256
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002257 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002258 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002259 return true;
2260 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002261
Douglas Gregor033f56d2008-12-23 00:53:59 +00002262 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00002263 // differences in the argument and result types are in Objective-C
2264 // pointer conversions. If so, we permit the conversion (but
2265 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00002266 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002267 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002268 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002269 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002270 if (FromFunctionType && ToFunctionType) {
2271 // If the function types are exactly the same, this isn't an
2272 // Objective-C pointer conversion.
2273 if (Context.getCanonicalType(FromPointeeType)
2274 == Context.getCanonicalType(ToPointeeType))
2275 return false;
2276
2277 // Perform the quick checks that will tell us whether these
2278 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002279 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Douglas Gregora119f102008-12-19 19:13:09 +00002280 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2281 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2282 return false;
2283
2284 bool HasObjCConversion = false;
Alp Toker314cc812014-01-25 16:55:45 +00002285 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2286 Context.getCanonicalType(ToFunctionType->getReturnType())) {
Douglas Gregora119f102008-12-19 19:13:09 +00002287 // Okay, the types match exactly. Nothing to do.
Alp Toker314cc812014-01-25 16:55:45 +00002288 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2289 ToFunctionType->getReturnType(),
Douglas Gregora119f102008-12-19 19:13:09 +00002290 ConvertedType, IncompatibleObjC)) {
2291 // Okay, we have an Objective-C pointer conversion.
2292 HasObjCConversion = true;
2293 } else {
2294 // Function types are too different. Abort.
2295 return false;
2296 }
Mike Stump11289f42009-09-09 15:08:12 +00002297
Douglas Gregora119f102008-12-19 19:13:09 +00002298 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002299 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Douglas Gregora119f102008-12-19 19:13:09 +00002300 ArgIdx != NumArgs; ++ArgIdx) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002301 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2302 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Douglas Gregora119f102008-12-19 19:13:09 +00002303 if (Context.getCanonicalType(FromArgType)
2304 == Context.getCanonicalType(ToArgType)) {
2305 // Okay, the types match exactly. Nothing to do.
2306 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2307 ConvertedType, IncompatibleObjC)) {
2308 // Okay, we have an Objective-C pointer conversion.
2309 HasObjCConversion = true;
2310 } else {
2311 // Argument types are too different. Abort.
2312 return false;
2313 }
2314 }
2315
2316 if (HasObjCConversion) {
2317 // We had an Objective-C conversion. Allow this pointer
2318 // conversion, but complain about it.
Douglas Gregoraec25842011-04-26 23:16:46 +00002319 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002320 IncompatibleObjC = true;
2321 return true;
2322 }
2323 }
2324
Sebastian Redl72b597d2009-01-25 19:43:20 +00002325 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002326}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002327
John McCall31168b02011-06-15 23:02:42 +00002328/// \brief Determine whether this is an Objective-C writeback conversion,
2329/// used for parameter passing when performing automatic reference counting.
2330///
2331/// \param FromType The type we're converting form.
2332///
2333/// \param ToType The type we're converting to.
2334///
2335/// \param ConvertedType The type that will be produced after applying
2336/// this conversion.
2337bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2338 QualType &ConvertedType) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002339 if (!getLangOpts().ObjCAutoRefCount ||
John McCall31168b02011-06-15 23:02:42 +00002340 Context.hasSameUnqualifiedType(FromType, ToType))
2341 return false;
2342
2343 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2344 QualType ToPointee;
2345 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2346 ToPointee = ToPointer->getPointeeType();
2347 else
2348 return false;
2349
2350 Qualifiers ToQuals = ToPointee.getQualifiers();
2351 if (!ToPointee->isObjCLifetimeType() ||
2352 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall18ce25e2012-02-08 00:46:36 +00002353 !ToQuals.withoutObjCLifetime().empty())
John McCall31168b02011-06-15 23:02:42 +00002354 return false;
2355
2356 // Argument must be a pointer to __strong to __weak.
2357 QualType FromPointee;
2358 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2359 FromPointee = FromPointer->getPointeeType();
2360 else
2361 return false;
2362
2363 Qualifiers FromQuals = FromPointee.getQualifiers();
2364 if (!FromPointee->isObjCLifetimeType() ||
2365 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2366 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2367 return false;
2368
2369 // Make sure that we have compatible qualifiers.
2370 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2371 if (!ToQuals.compatiblyIncludes(FromQuals))
2372 return false;
2373
2374 // Remove qualifiers from the pointee type we're converting from; they
2375 // aren't used in the compatibility check belong, and we'll be adding back
2376 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2377 FromPointee = FromPointee.getUnqualifiedType();
2378
2379 // The unqualified form of the pointee types must be compatible.
2380 ToPointee = ToPointee.getUnqualifiedType();
2381 bool IncompatibleObjC;
2382 if (Context.typesAreCompatible(FromPointee, ToPointee))
2383 FromPointee = ToPointee;
2384 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2385 IncompatibleObjC))
2386 return false;
2387
2388 /// \brief Construct the type we're converting to, which is a pointer to
2389 /// __autoreleasing pointee.
2390 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2391 ConvertedType = Context.getPointerType(FromPointee);
2392 return true;
2393}
2394
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002395bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2396 QualType& ConvertedType) {
2397 QualType ToPointeeType;
2398 if (const BlockPointerType *ToBlockPtr =
2399 ToType->getAs<BlockPointerType>())
2400 ToPointeeType = ToBlockPtr->getPointeeType();
2401 else
2402 return false;
2403
2404 QualType FromPointeeType;
2405 if (const BlockPointerType *FromBlockPtr =
2406 FromType->getAs<BlockPointerType>())
2407 FromPointeeType = FromBlockPtr->getPointeeType();
2408 else
2409 return false;
2410 // We have pointer to blocks, check whether the only
2411 // differences in the argument and result types are in Objective-C
2412 // pointer conversions. If so, we permit the conversion.
2413
2414 const FunctionProtoType *FromFunctionType
2415 = FromPointeeType->getAs<FunctionProtoType>();
2416 const FunctionProtoType *ToFunctionType
2417 = ToPointeeType->getAs<FunctionProtoType>();
2418
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002419 if (!FromFunctionType || !ToFunctionType)
2420 return false;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002421
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002422 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002423 return true;
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002424
2425 // Perform the quick checks that will tell us whether these
2426 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002427 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002428 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2429 return false;
2430
2431 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2432 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2433 if (FromEInfo != ToEInfo)
2434 return false;
2435
2436 bool IncompatibleObjC = false;
Alp Toker314cc812014-01-25 16:55:45 +00002437 if (Context.hasSameType(FromFunctionType->getReturnType(),
2438 ToFunctionType->getReturnType())) {
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002439 // Okay, the types match exactly. Nothing to do.
2440 } else {
Alp Toker314cc812014-01-25 16:55:45 +00002441 QualType RHS = FromFunctionType->getReturnType();
2442 QualType LHS = ToFunctionType->getReturnType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002443 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002444 !RHS.hasQualifiers() && LHS.hasQualifiers())
2445 LHS = LHS.getUnqualifiedType();
2446
2447 if (Context.hasSameType(RHS,LHS)) {
2448 // OK exact match.
2449 } else if (isObjCPointerConversion(RHS, LHS,
2450 ConvertedType, IncompatibleObjC)) {
2451 if (IncompatibleObjC)
2452 return false;
2453 // Okay, we have an Objective-C pointer conversion.
2454 }
2455 else
2456 return false;
2457 }
2458
2459 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002460 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002461 ArgIdx != NumArgs; ++ArgIdx) {
2462 IncompatibleObjC = false;
Alp Toker9cacbab2014-01-20 20:26:09 +00002463 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2464 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002465 if (Context.hasSameType(FromArgType, ToArgType)) {
2466 // Okay, the types match exactly. Nothing to do.
2467 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2468 ConvertedType, IncompatibleObjC)) {
2469 if (IncompatibleObjC)
2470 return false;
2471 // Okay, we have an Objective-C pointer conversion.
2472 } else
2473 // Argument types are too different. Abort.
2474 return false;
2475 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00002476 if (LangOpts.ObjCAutoRefCount &&
2477 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2478 ToFunctionType))
2479 return false;
Fariborz Jahanian600ba202011-09-28 20:22:05 +00002480
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002481 ConvertedType = ToType;
2482 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002483}
2484
Richard Trieucaff2472011-11-23 22:32:32 +00002485enum {
2486 ft_default,
2487 ft_different_class,
2488 ft_parameter_arity,
2489 ft_parameter_mismatch,
2490 ft_return_type,
2491 ft_qualifer_mismatch
2492};
2493
2494/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2495/// function types. Catches different number of parameter, mismatch in
2496/// parameter types, and different return types.
2497void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2498 QualType FromType, QualType ToType) {
Richard Trieu96ed5b62011-12-13 23:19:45 +00002499 // If either type is not valid, include no extra info.
2500 if (FromType.isNull() || ToType.isNull()) {
2501 PDiag << ft_default;
2502 return;
2503 }
2504
Richard Trieucaff2472011-11-23 22:32:32 +00002505 // Get the function type from the pointers.
2506 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2507 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2508 *ToMember = ToType->getAs<MemberPointerType>();
Richard Trieu9098c9f2014-05-22 01:39:16 +00002509 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
Richard Trieucaff2472011-11-23 22:32:32 +00002510 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2511 << QualType(FromMember->getClass(), 0);
2512 return;
2513 }
2514 FromType = FromMember->getPointeeType();
2515 ToType = ToMember->getPointeeType();
Richard Trieucaff2472011-11-23 22:32:32 +00002516 }
2517
Richard Trieu96ed5b62011-12-13 23:19:45 +00002518 if (FromType->isPointerType())
2519 FromType = FromType->getPointeeType();
2520 if (ToType->isPointerType())
2521 ToType = ToType->getPointeeType();
2522
2523 // Remove references.
Richard Trieucaff2472011-11-23 22:32:32 +00002524 FromType = FromType.getNonReferenceType();
2525 ToType = ToType.getNonReferenceType();
2526
Richard Trieucaff2472011-11-23 22:32:32 +00002527 // Don't print extra info for non-specialized template functions.
2528 if (FromType->isInstantiationDependentType() &&
2529 !FromType->getAs<TemplateSpecializationType>()) {
2530 PDiag << ft_default;
2531 return;
2532 }
2533
Richard Trieu96ed5b62011-12-13 23:19:45 +00002534 // No extra info for same types.
2535 if (Context.hasSameType(FromType, ToType)) {
2536 PDiag << ft_default;
2537 return;
2538 }
2539
Richard Trieucaff2472011-11-23 22:32:32 +00002540 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2541 *ToFunction = ToType->getAs<FunctionProtoType>();
2542
2543 // Both types need to be function types.
2544 if (!FromFunction || !ToFunction) {
2545 PDiag << ft_default;
2546 return;
2547 }
2548
Alp Toker9cacbab2014-01-20 20:26:09 +00002549 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2550 PDiag << ft_parameter_arity << ToFunction->getNumParams()
2551 << FromFunction->getNumParams();
Richard Trieucaff2472011-11-23 22:32:32 +00002552 return;
2553 }
2554
2555 // Handle different parameter types.
2556 unsigned ArgPos;
Alp Toker9cacbab2014-01-20 20:26:09 +00002557 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
Richard Trieucaff2472011-11-23 22:32:32 +00002558 PDiag << ft_parameter_mismatch << ArgPos + 1
Alp Toker9cacbab2014-01-20 20:26:09 +00002559 << ToFunction->getParamType(ArgPos)
2560 << FromFunction->getParamType(ArgPos);
Richard Trieucaff2472011-11-23 22:32:32 +00002561 return;
2562 }
2563
2564 // Handle different return type.
Alp Toker314cc812014-01-25 16:55:45 +00002565 if (!Context.hasSameType(FromFunction->getReturnType(),
2566 ToFunction->getReturnType())) {
2567 PDiag << ft_return_type << ToFunction->getReturnType()
2568 << FromFunction->getReturnType();
Richard Trieucaff2472011-11-23 22:32:32 +00002569 return;
2570 }
2571
2572 unsigned FromQuals = FromFunction->getTypeQuals(),
2573 ToQuals = ToFunction->getTypeQuals();
2574 if (FromQuals != ToQuals) {
2575 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2576 return;
2577 }
2578
2579 // Unable to find a difference, so add no extra info.
2580 PDiag << ft_default;
2581}
2582
Alp Toker9cacbab2014-01-20 20:26:09 +00002583/// FunctionParamTypesAreEqual - This routine checks two function proto types
Douglas Gregor2039ca02011-12-15 17:15:07 +00002584/// for equality of their argument types. Caller has already checked that
Eli Friedman5f508952013-06-18 22:41:37 +00002585/// they have same number of arguments. If the parameters are different,
2586/// ArgPos will have the parameter index of the first different parameter.
Alp Toker9cacbab2014-01-20 20:26:09 +00002587bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2588 const FunctionProtoType *NewType,
2589 unsigned *ArgPos) {
2590 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2591 N = NewType->param_type_begin(),
2592 E = OldType->param_type_end();
2593 O && (O != E); ++O, ++N) {
Richard Trieu4b03d982013-08-09 21:42:32 +00002594 if (!Context.hasSameType(O->getUnqualifiedType(),
2595 N->getUnqualifiedType())) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002596 if (ArgPos)
2597 *ArgPos = O - OldType->param_type_begin();
Larisse Voufo4154f462013-08-06 03:57:41 +00002598 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002599 }
2600 }
2601 return true;
2602}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002603
Douglas Gregor39c16d42008-10-24 04:54:22 +00002604/// CheckPointerConversion - Check the pointer conversion from the
2605/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00002606/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00002607/// conversions for which IsPointerConversion has already returned
2608/// true. It returns true and produces a diagnostic if there was an
2609/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002610bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002611 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002612 CXXCastPath& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002613 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002614 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00002615 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002616
John McCall8cb679e2010-11-15 09:13:47 +00002617 Kind = CK_BitCast;
2618
David Blaikie1c7c8f72012-08-08 17:33:31 +00002619 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
Argyrios Kyrtzidis3e3305d2014-02-02 05:26:43 +00002620 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
David Blaikie1c7c8f72012-08-08 17:33:31 +00002621 Expr::NPCK_ZeroExpression) {
2622 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2623 DiagRuntimeBehavior(From->getExprLoc(), From,
2624 PDiag(diag::warn_impcast_bool_to_null_pointer)
2625 << ToType << From->getSourceRange());
2626 else if (!isUnevaluatedContext())
2627 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2628 << ToType << From->getSourceRange();
2629 }
John McCall9320b872011-09-09 05:25:32 +00002630 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2631 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002632 QualType FromPointeeType = FromPtrType->getPointeeType(),
2633 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00002634
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002635 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2636 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002637 // We must have a derived-to-base conversion. Check an
2638 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002639 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2640 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00002641 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002642 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002643 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002644
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002645 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00002646 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002647 }
2648 }
John McCall9320b872011-09-09 05:25:32 +00002649 } else if (const ObjCObjectPointerType *ToPtrType =
2650 ToType->getAs<ObjCObjectPointerType>()) {
2651 if (const ObjCObjectPointerType *FromPtrType =
2652 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002653 // Objective-C++ conversions are always okay.
2654 // FIXME: We should have a different class of conversions for the
2655 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00002656 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002657 return false;
John McCall9320b872011-09-09 05:25:32 +00002658 } else if (FromType->isBlockPointerType()) {
2659 Kind = CK_BlockPointerToObjCPointerCast;
2660 } else {
2661 Kind = CK_CPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00002662 }
John McCall9320b872011-09-09 05:25:32 +00002663 } else if (ToType->isBlockPointerType()) {
2664 if (!FromType->isBlockPointerType())
2665 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002666 }
John McCall8cb679e2010-11-15 09:13:47 +00002667
2668 // We shouldn't fall into this case unless it's valid for other
2669 // reasons.
2670 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2671 Kind = CK_NullToPointer;
2672
Douglas Gregor39c16d42008-10-24 04:54:22 +00002673 return false;
2674}
2675
Sebastian Redl72b597d2009-01-25 19:43:20 +00002676/// IsMemberPointerConversion - Determines whether the conversion of the
2677/// expression From, which has the (possibly adjusted) type FromType, can be
2678/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2679/// If so, returns true and places the converted type (that might differ from
2680/// ToType in its cv-qualifiers at some level) into ConvertedType.
2681bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002682 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00002683 bool InOverloadResolution,
2684 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002685 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002686 if (!ToTypePtr)
2687 return false;
2688
2689 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00002690 if (From->isNullPointerConstant(Context,
2691 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2692 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002693 ConvertedType = ToType;
2694 return true;
2695 }
2696
2697 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002698 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002699 if (!FromTypePtr)
2700 return false;
2701
2702 // A pointer to member of B can be converted to a pointer to member of D,
2703 // where D is derived from B (C++ 4.11p2).
2704 QualType FromClass(FromTypePtr->getClass(), 0);
2705 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002706
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002707 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002708 !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002709 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002710 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2711 ToClass.getTypePtr());
2712 return true;
2713 }
2714
2715 return false;
2716}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002717
Sebastian Redl72b597d2009-01-25 19:43:20 +00002718/// CheckMemberPointerConversion - Check the member pointer conversion from the
2719/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002720/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002721/// for which IsMemberPointerConversion has already returned true. It returns
2722/// true and produces a diagnostic if there was an error, or returns false
2723/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002724bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002725 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002726 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002727 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002728 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002729 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00002730 if (!FromPtrType) {
2731 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002732 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00002733 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00002734 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00002735 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00002736 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00002737 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00002738
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002739 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00002740 assert(ToPtrType && "No member pointer cast has a target type "
2741 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002742
Sebastian Redled8f2002009-01-28 18:33:18 +00002743 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2744 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002745
Sebastian Redled8f2002009-01-28 18:33:18 +00002746 // FIXME: What about dependent types?
2747 assert(FromClass->isRecordType() && "Pointer into non-class.");
2748 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002749
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002750 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002751 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00002752 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2753 assert(DerivationOkay &&
2754 "Should not have been called if derivation isn't OK.");
2755 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002756
Sebastian Redled8f2002009-01-28 18:33:18 +00002757 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2758 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002759 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2760 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2761 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2762 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002763 }
Sebastian Redled8f2002009-01-28 18:33:18 +00002764
Douglas Gregor89ee6822009-02-28 01:32:25 +00002765 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002766 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2767 << FromClass << ToClass << QualType(VBase, 0)
2768 << From->getSourceRange();
2769 return true;
2770 }
2771
John McCall5b0829a2010-02-10 09:31:12 +00002772 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00002773 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2774 Paths.front(),
2775 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00002776
Anders Carlssond7923c62009-08-22 23:33:40 +00002777 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002778 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00002779 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002780 return false;
2781}
2782
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002783/// Determine whether the lifetime conversion between the two given
2784/// qualifiers sets is nontrivial.
2785static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
2786 Qualifiers ToQuals) {
2787 // Converting anything to const __unsafe_unretained is trivial.
2788 if (ToQuals.hasConst() &&
2789 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
2790 return false;
2791
2792 return true;
2793}
2794
Douglas Gregor9a657932008-10-21 23:43:52 +00002795/// IsQualificationConversion - Determines whether the conversion from
2796/// an rvalue of type FromType to ToType is a qualification conversion
2797/// (C++ 4.4).
John McCall31168b02011-06-15 23:02:42 +00002798///
2799/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2800/// when the qualification conversion involves a change in the Objective-C
2801/// object lifetime.
Mike Stump11289f42009-09-09 15:08:12 +00002802bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002803Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002804 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002805 FromType = Context.getCanonicalType(FromType);
2806 ToType = Context.getCanonicalType(ToType);
John McCall31168b02011-06-15 23:02:42 +00002807 ObjCLifetimeConversion = false;
2808
Douglas Gregor9a657932008-10-21 23:43:52 +00002809 // If FromType and ToType are the same type, this is not a
2810 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00002811 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00002812 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00002813
Douglas Gregor9a657932008-10-21 23:43:52 +00002814 // (C++ 4.4p4):
2815 // A conversion can add cv-qualifiers at levels other than the first
2816 // in multi-level pointers, subject to the following rules: [...]
2817 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002818 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002819 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002820 // Within each iteration of the loop, we check the qualifiers to
2821 // determine if this still looks like a qualification
2822 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002823 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00002824 // until there are no more pointers or pointers-to-members left to
2825 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002826 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002827
Douglas Gregor90609aa2011-04-25 18:40:17 +00002828 Qualifiers FromQuals = FromType.getQualifiers();
2829 Qualifiers ToQuals = ToType.getQualifiers();
2830
John McCall31168b02011-06-15 23:02:42 +00002831 // Objective-C ARC:
2832 // Check Objective-C lifetime conversions.
2833 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2834 UnwrappedAnyPointer) {
2835 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002836 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
2837 ObjCLifetimeConversion = true;
John McCall31168b02011-06-15 23:02:42 +00002838 FromQuals.removeObjCLifetime();
2839 ToQuals.removeObjCLifetime();
2840 } else {
2841 // Qualification conversions cannot cast between different
2842 // Objective-C lifetime qualifiers.
2843 return false;
2844 }
2845 }
2846
Douglas Gregorf30053d2011-05-08 06:09:53 +00002847 // Allow addition/removal of GC attributes but not changing GC attributes.
2848 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2849 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2850 FromQuals.removeObjCGCAttr();
2851 ToQuals.removeObjCGCAttr();
2852 }
2853
Douglas Gregor9a657932008-10-21 23:43:52 +00002854 // -- for every j > 0, if const is in cv 1,j then const is in cv
2855 // 2,j, and similarly for volatile.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002856 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor9a657932008-10-21 23:43:52 +00002857 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002858
Douglas Gregor9a657932008-10-21 23:43:52 +00002859 // -- if the cv 1,j and cv 2,j are different, then const is in
2860 // every cv for 0 < k < j.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002861 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002862 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00002863 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002864
Douglas Gregor9a657932008-10-21 23:43:52 +00002865 // Keep track of whether all prior cv-qualifiers in the "to" type
2866 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00002867 PreviousToQualsIncludeConst
Douglas Gregor90609aa2011-04-25 18:40:17 +00002868 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002869 }
Douglas Gregor9a657932008-10-21 23:43:52 +00002870
2871 // We are left with FromType and ToType being the pointee types
2872 // after unwrapping the original FromType and ToType the same number
2873 // of types. If we unwrapped any pointers, and if FromType and
2874 // ToType have the same unqualified type (since we checked
2875 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002876 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00002877}
2878
Douglas Gregorc79862f2012-04-12 17:51:55 +00002879/// \brief - Determine whether this is a conversion from a scalar type to an
2880/// atomic type.
2881///
2882/// If successful, updates \c SCS's second and third steps in the conversion
2883/// sequence to finish the conversion.
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00002884static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2885 bool InOverloadResolution,
2886 StandardConversionSequence &SCS,
2887 bool CStyle) {
Douglas Gregorc79862f2012-04-12 17:51:55 +00002888 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2889 if (!ToAtomic)
2890 return false;
2891
2892 StandardConversionSequence InnerSCS;
2893 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2894 InOverloadResolution, InnerSCS,
2895 CStyle, /*AllowObjCWritebackConversion=*/false))
2896 return false;
2897
2898 SCS.Second = InnerSCS.Second;
2899 SCS.setToType(1, InnerSCS.getToType(1));
2900 SCS.Third = InnerSCS.Third;
2901 SCS.QualificationIncludesObjCLifetime
2902 = InnerSCS.QualificationIncludesObjCLifetime;
2903 SCS.setToType(2, InnerSCS.getToType(2));
2904 return true;
2905}
2906
Sebastian Redle5417162012-03-27 18:33:03 +00002907static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2908 CXXConstructorDecl *Constructor,
2909 QualType Type) {
2910 const FunctionProtoType *CtorType =
2911 Constructor->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00002912 if (CtorType->getNumParams() > 0) {
2913 QualType FirstArg = CtorType->getParamType(0);
Sebastian Redle5417162012-03-27 18:33:03 +00002914 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2915 return true;
2916 }
2917 return false;
2918}
2919
Sebastian Redl82ace982012-02-11 23:51:08 +00002920static OverloadingResult
2921IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2922 CXXRecordDecl *To,
2923 UserDefinedConversionSequence &User,
2924 OverloadCandidateSet &CandidateSet,
2925 bool AllowExplicit) {
David Blaikieff7d47a2012-12-19 00:45:41 +00002926 DeclContext::lookup_result R = S.LookupConstructors(To);
2927 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Sebastian Redl82ace982012-02-11 23:51:08 +00002928 Con != ConEnd; ++Con) {
2929 NamedDecl *D = *Con;
2930 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2931
2932 // Find the constructor (which may be a template).
Craig Topperc3ec1492014-05-26 06:22:03 +00002933 CXXConstructorDecl *Constructor = nullptr;
Sebastian Redl82ace982012-02-11 23:51:08 +00002934 FunctionTemplateDecl *ConstructorTmpl
2935 = dyn_cast<FunctionTemplateDecl>(D);
2936 if (ConstructorTmpl)
2937 Constructor
2938 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2939 else
2940 Constructor = cast<CXXConstructorDecl>(D);
2941
2942 bool Usable = !Constructor->isInvalidDecl() &&
2943 S.isInitListConstructor(Constructor) &&
2944 (AllowExplicit || !Constructor->isExplicit());
2945 if (Usable) {
Sebastian Redle5417162012-03-27 18:33:03 +00002946 // If the first argument is (a reference to) the target type,
2947 // suppress conversions.
2948 bool SuppressUserConversions =
2949 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
Sebastian Redl82ace982012-02-11 23:51:08 +00002950 if (ConstructorTmpl)
2951 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00002952 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002953 From, CandidateSet,
Sebastian Redle5417162012-03-27 18:33:03 +00002954 SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00002955 else
2956 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002957 From, CandidateSet,
Sebastian Redle5417162012-03-27 18:33:03 +00002958 SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00002959 }
2960 }
2961
2962 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2963
2964 OverloadCandidateSet::iterator Best;
Fariborz Jahaniandcf06f42015-04-14 17:21:58 +00002965 switch (auto Result =
2966 CandidateSet.BestViableFunction(S, From->getLocStart(),
2967 Best, true)) {
2968 case OR_Deleted:
Sebastian Redl82ace982012-02-11 23:51:08 +00002969 case OR_Success: {
2970 // Record the standard conversion we used and the conversion function.
2971 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Sebastian Redl82ace982012-02-11 23:51:08 +00002972 QualType ThisType = Constructor->getThisType(S.Context);
2973 // Initializer lists don't have conversions as such.
2974 User.Before.setAsIdentityConversion();
2975 User.HadMultipleCandidates = HadMultipleCandidates;
2976 User.ConversionFunction = Constructor;
2977 User.FoundConversionFunction = Best->FoundDecl;
2978 User.After.setAsIdentityConversion();
2979 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2980 User.After.setAllToTypes(ToType);
Fariborz Jahaniandcf06f42015-04-14 17:21:58 +00002981 return Result;
Sebastian Redl82ace982012-02-11 23:51:08 +00002982 }
2983
2984 case OR_No_Viable_Function:
2985 return OR_No_Viable_Function;
Sebastian Redl82ace982012-02-11 23:51:08 +00002986 case OR_Ambiguous:
2987 return OR_Ambiguous;
2988 }
2989
2990 llvm_unreachable("Invalid OverloadResult!");
2991}
2992
Douglas Gregor576e98c2009-01-30 23:27:23 +00002993/// Determines whether there is a user-defined conversion sequence
2994/// (C++ [over.ics.user]) that converts expression From to the type
2995/// ToType. If such a conversion exists, User will contain the
2996/// user-defined conversion sequence that performs such a conversion
2997/// and this routine will return true. Otherwise, this routine returns
2998/// false and User is unspecified.
2999///
Douglas Gregor576e98c2009-01-30 23:27:23 +00003000/// \param AllowExplicit true if the conversion should consider C++0x
3001/// "explicit" conversion functions as well as non-explicit conversion
3002/// functions (C++0x [class.conv.fct]p2).
Douglas Gregor4b60a152013-11-07 22:34:54 +00003003///
3004/// \param AllowObjCConversionOnExplicit true if the conversion should
3005/// allow an extra Objective-C pointer conversion on uses of explicit
3006/// constructors. Requires \c AllowExplicit to also be set.
John McCall5c32be02010-08-24 20:38:10 +00003007static OverloadingResult
3008IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl82ace982012-02-11 23:51:08 +00003009 UserDefinedConversionSequence &User,
3010 OverloadCandidateSet &CandidateSet,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003011 bool AllowExplicit,
3012 bool AllowObjCConversionOnExplicit) {
Douglas Gregor2ee1d992013-11-08 01:20:25 +00003013 assert(AllowExplicit || !AllowObjCConversionOnExplicit);
Douglas Gregor4b60a152013-11-07 22:34:54 +00003014
Douglas Gregor5ab11652010-04-17 22:01:05 +00003015 // Whether we will only visit constructors.
3016 bool ConstructorsOnly = false;
3017
3018 // If the type we are conversion to is a class type, enumerate its
3019 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003020 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00003021 // C++ [over.match.ctor]p1:
3022 // When objects of class type are direct-initialized (8.5), or
3023 // copy-initialized from an expression of the same or a
3024 // derived class type (8.5), overload resolution selects the
3025 // constructor. [...] For copy-initialization, the candidate
3026 // functions are all the converting constructors (12.3.1) of
3027 // that class. The argument list is the expression-list within
3028 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00003029 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00003030 (From->getType()->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00003031 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00003032 ConstructorsOnly = true;
3033
Benjamin Kramer90633e32012-11-23 17:04:52 +00003034 S.RequireCompleteType(From->getExprLoc(), ToType, 0);
Argyrios Kyrtzidis7a6f2a32011-04-22 17:45:37 +00003035 // RequireCompleteType may have returned true due to some invalid decl
3036 // during template instantiation, but ToType may be complete enough now
3037 // to try to recover.
3038 if (ToType->isIncompleteType()) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003039 // We're not going to find any constructors.
3040 } else if (CXXRecordDecl *ToRecordDecl
3041 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003042
3043 Expr **Args = &From;
3044 unsigned NumArgs = 1;
3045 bool ListInitializing = false;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003046 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003047 // But first, see if there is an init-list-constructor that will work.
Sebastian Redl82ace982012-02-11 23:51:08 +00003048 OverloadingResult Result = IsInitializerListConstructorConversion(
3049 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3050 if (Result != OR_No_Viable_Function)
3051 return Result;
3052 // Never mind.
3053 CandidateSet.clear();
3054
3055 // If we're list-initializing, we pass the individual elements as
3056 // arguments, not the entire list.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003057 Args = InitList->getInits();
3058 NumArgs = InitList->getNumInits();
3059 ListInitializing = true;
3060 }
3061
David Blaikieff7d47a2012-12-19 00:45:41 +00003062 DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl);
3063 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Douglas Gregor89ee6822009-02-28 01:32:25 +00003064 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00003065 NamedDecl *D = *Con;
3066 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3067
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003068 // Find the constructor (which may be a template).
Craig Topperc3ec1492014-05-26 06:22:03 +00003069 CXXConstructorDecl *Constructor = nullptr;
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003070 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00003071 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003072 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00003073 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003074 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3075 else
John McCalla0296f72010-03-19 07:35:19 +00003076 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003077
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003078 bool Usable = !Constructor->isInvalidDecl();
3079 if (ListInitializing)
3080 Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3081 else
3082 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3083 if (Usable) {
Sebastian Redld9170b02012-03-20 21:24:14 +00003084 bool SuppressUserConversions = !ConstructorsOnly;
3085 if (SuppressUserConversions && ListInitializing) {
3086 SuppressUserConversions = false;
3087 if (NumArgs == 1) {
3088 // If the first argument is (a reference to) the target type,
3089 // suppress conversions.
Sebastian Redle5417162012-03-27 18:33:03 +00003090 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3091 S.Context, Constructor, ToType);
Sebastian Redld9170b02012-03-20 21:24:14 +00003092 }
3093 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003094 if (ConstructorTmpl)
John McCall5c32be02010-08-24 20:38:10 +00003095 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00003096 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003097 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003098 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003099 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00003100 // Allow one user-defined conversion when user specifies a
3101 // From->ToType conversion via an static cast (c-style, etc).
John McCall5c32be02010-08-24 20:38:10 +00003102 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003103 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003104 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003105 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00003106 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003107 }
3108 }
3109
Douglas Gregor5ab11652010-04-17 22:01:05 +00003110 // Enumerate conversion functions, if we're allowed to.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003111 if (ConstructorsOnly || isa<InitListExpr>(From)) {
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003112 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003113 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00003114 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00003115 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00003116 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003117 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3118 // Add all of the conversion functions as candidates.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00003119 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3120 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00003121 DeclAccessPair FoundDecl = I.getPair();
3122 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003123 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3124 if (isa<UsingShadowDecl>(D))
3125 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3126
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003127 CXXConversionDecl *Conv;
3128 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00003129 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3130 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003131 else
John McCallda4458e2010-03-31 01:36:47 +00003132 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003133
3134 if (AllowExplicit || !Conv->isExplicit()) {
3135 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00003136 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3137 ActingContext, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003138 CandidateSet,
3139 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003140 else
John McCall5c32be02010-08-24 20:38:10 +00003141 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003142 From, ToType, CandidateSet,
3143 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003144 }
3145 }
3146 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00003147 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003148
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003149 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3150
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003151 OverloadCandidateSet::iterator Best;
Richard Smith48372b62015-01-27 03:30:40 +00003152 switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(),
3153 Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00003154 case OR_Success:
Richard Smith48372b62015-01-27 03:30:40 +00003155 case OR_Deleted:
John McCall5c32be02010-08-24 20:38:10 +00003156 // Record the standard conversion we used and the conversion function.
3157 if (CXXConstructorDecl *Constructor
3158 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3159 // C++ [over.ics.user]p1:
3160 // If the user-defined conversion is specified by a
3161 // constructor (12.3.1), the initial standard conversion
3162 // sequence converts the source type to the type required by
3163 // the argument of the constructor.
3164 //
3165 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003166 if (isa<InitListExpr>(From)) {
3167 // Initializer lists don't have conversions as such.
3168 User.Before.setAsIdentityConversion();
3169 } else {
3170 if (Best->Conversions[0].isEllipsis())
3171 User.EllipsisConversion = true;
3172 else {
3173 User.Before = Best->Conversions[0].Standard;
3174 User.EllipsisConversion = false;
3175 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003176 }
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003177 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003178 User.ConversionFunction = Constructor;
John McCall30909032011-09-21 08:36:56 +00003179 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003180 User.After.setAsIdentityConversion();
3181 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3182 User.After.setAllToTypes(ToType);
Richard Smith48372b62015-01-27 03:30:40 +00003183 return Result;
David Blaikie8a40f702012-01-17 06:56:22 +00003184 }
3185 if (CXXConversionDecl *Conversion
John McCall5c32be02010-08-24 20:38:10 +00003186 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3187 // C++ [over.ics.user]p1:
3188 //
3189 // [...] If the user-defined conversion is specified by a
3190 // conversion function (12.3.2), the initial standard
3191 // conversion sequence converts the source type to the
3192 // implicit object parameter of the conversion function.
3193 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003194 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003195 User.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00003196 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003197 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00003198
John McCall5c32be02010-08-24 20:38:10 +00003199 // C++ [over.ics.user]p2:
3200 // The second standard conversion sequence converts the
3201 // result of the user-defined conversion to the target type
3202 // for the sequence. Since an implicit conversion sequence
3203 // is an initialization, the special rules for
3204 // initialization by user-defined conversion apply when
3205 // selecting the best user-defined conversion for a
3206 // user-defined conversion sequence (see 13.3.3 and
3207 // 13.3.3.1).
3208 User.After = Best->FinalConversion;
Richard Smith48372b62015-01-27 03:30:40 +00003209 return Result;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003210 }
David Blaikie8a40f702012-01-17 06:56:22 +00003211 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003212
John McCall5c32be02010-08-24 20:38:10 +00003213 case OR_No_Viable_Function:
3214 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003215
John McCall5c32be02010-08-24 20:38:10 +00003216 case OR_Ambiguous:
3217 return OR_Ambiguous;
3218 }
3219
David Blaikie8a40f702012-01-17 06:56:22 +00003220 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003221}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003222
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003223bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00003224Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003225 ImplicitConversionSequence ICS;
Richard Smith100b24a2014-04-17 01:52:14 +00003226 OverloadCandidateSet CandidateSet(From->getExprLoc(),
3227 OverloadCandidateSet::CSK_Normal);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003228 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00003229 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003230 CandidateSet, false, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00003231 if (OvResult == OR_Ambiguous)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003232 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3233 << From->getType() << ToType << From->getSourceRange();
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003234 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
Larisse Voufo70bb43a2013-06-27 03:36:30 +00003235 if (!RequireCompleteType(From->getLocStart(), ToType,
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003236 diag::err_typecheck_nonviable_condition_incomplete,
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003237 From->getType(), From->getSourceRange()))
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003238 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
Nick Lewycky08426e22015-08-25 22:18:46 +00003239 << false << From->getType() << From->getSourceRange() << ToType;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003240 } else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003241 return false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003242 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003243 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003244}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003245
Douglas Gregor2837aa22012-02-22 17:32:19 +00003246/// \brief Compare the user-defined conversion functions or constructors
3247/// of two user-defined conversion sequences to determine whether any ordering
3248/// is possible.
3249static ImplicitConversionSequence::CompareKind
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003250compareConversionFunctions(Sema &S, FunctionDecl *Function1,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003251 FunctionDecl *Function2) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003252 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
Douglas Gregor2837aa22012-02-22 17:32:19 +00003253 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003254
Douglas Gregor2837aa22012-02-22 17:32:19 +00003255 // Objective-C++:
3256 // If both conversion functions are implicitly-declared conversions from
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003257 // a lambda closure type to a function pointer and a block pointer,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003258 // respectively, always prefer the conversion to a function pointer,
3259 // because the function pointer is more lightweight and is more likely
3260 // to keep code working.
Ted Kremenek8d265c22014-04-01 07:23:18 +00003261 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003262 if (!Conv1)
3263 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003264
Douglas Gregor2837aa22012-02-22 17:32:19 +00003265 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3266 if (!Conv2)
3267 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003268
Douglas Gregor2837aa22012-02-22 17:32:19 +00003269 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3270 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3271 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3272 if (Block1 != Block2)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003273 return Block1 ? ImplicitConversionSequence::Worse
3274 : ImplicitConversionSequence::Better;
Douglas Gregor2837aa22012-02-22 17:32:19 +00003275 }
3276
3277 return ImplicitConversionSequence::Indistinguishable;
3278}
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003279
3280static bool hasDeprecatedStringLiteralToCharPtrConversion(
3281 const ImplicitConversionSequence &ICS) {
3282 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3283 (ICS.isUserDefined() &&
3284 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3285}
3286
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003287/// CompareImplicitConversionSequences - Compare two implicit
3288/// conversion sequences to determine whether one is better than the
3289/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00003290static ImplicitConversionSequence::CompareKind
3291CompareImplicitConversionSequences(Sema &S,
3292 const ImplicitConversionSequence& ICS1,
3293 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003294{
3295 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3296 // conversion sequences (as defined in 13.3.3.1)
3297 // -- a standard conversion sequence (13.3.3.1.1) is a better
3298 // conversion sequence than a user-defined conversion sequence or
3299 // an ellipsis conversion sequence, and
3300 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3301 // conversion sequence than an ellipsis conversion sequence
3302 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00003303 //
John McCall0d1da222010-01-12 00:44:57 +00003304 // C++0x [over.best.ics]p10:
3305 // For the purpose of ranking implicit conversion sequences as
3306 // described in 13.3.3.2, the ambiguous conversion sequence is
3307 // treated as a user-defined sequence that is indistinguishable
3308 // from any other user-defined conversion sequence.
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003309
3310 // String literal to 'char *' conversion has been deprecated in C++03. It has
3311 // been removed from C++11. We still accept this conversion, if it happens at
3312 // the best viable function. Otherwise, this conversion is considered worse
3313 // than ellipsis conversion. Consider this as an extension; this is not in the
3314 // standard. For example:
3315 //
3316 // int &f(...); // #1
3317 // void f(char*); // #2
3318 // void g() { int &r = f("foo"); }
3319 //
3320 // In C++03, we pick #2 as the best viable function.
3321 // In C++11, we pick #1 as the best viable function, because ellipsis
3322 // conversion is better than string-literal to char* conversion (since there
3323 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3324 // convert arguments, #2 would be the best viable function in C++11.
3325 // If the best viable function has this conversion, a warning will be issued
3326 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3327
3328 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3329 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3330 hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3331 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3332 ? ImplicitConversionSequence::Worse
3333 : ImplicitConversionSequence::Better;
3334
Douglas Gregor5ab11652010-04-17 22:01:05 +00003335 if (ICS1.getKindRank() < ICS2.getKindRank())
3336 return ImplicitConversionSequence::Better;
David Blaikie8a40f702012-01-17 06:56:22 +00003337 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor5ab11652010-04-17 22:01:05 +00003338 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003339
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00003340 // The following checks require both conversion sequences to be of
3341 // the same kind.
3342 if (ICS1.getKind() != ICS2.getKind())
3343 return ImplicitConversionSequence::Indistinguishable;
3344
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003345 ImplicitConversionSequence::CompareKind Result =
3346 ImplicitConversionSequence::Indistinguishable;
3347
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003348 // Two implicit conversion sequences of the same form are
3349 // indistinguishable conversion sequences unless one of the
3350 // following rules apply: (C++ 13.3.3.2p3):
Larisse Voufo19d08672015-01-27 18:47:05 +00003351
3352 // List-initialization sequence L1 is a better conversion sequence than
3353 // list-initialization sequence L2 if:
3354 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3355 // if not that,
NAKAMURA Takumib01d86b2015-02-25 11:02:00 +00003356 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
Larisse Voufo19d08672015-01-27 18:47:05 +00003357 // and N1 is smaller than N2.,
3358 // even if one of the other rules in this paragraph would otherwise apply.
3359 if (!ICS1.isBad()) {
3360 if (ICS1.isStdInitializerListElement() &&
3361 !ICS2.isStdInitializerListElement())
3362 return ImplicitConversionSequence::Better;
3363 if (!ICS1.isStdInitializerListElement() &&
3364 ICS2.isStdInitializerListElement())
3365 return ImplicitConversionSequence::Worse;
3366 }
3367
John McCall0d1da222010-01-12 00:44:57 +00003368 if (ICS1.isStandard())
Larisse Voufo19d08672015-01-27 18:47:05 +00003369 // Standard conversion sequence S1 is a better conversion sequence than
3370 // standard conversion sequence S2 if [...]
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003371 Result = CompareStandardConversionSequences(S,
3372 ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00003373 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003374 // User-defined conversion sequence U1 is a better conversion
3375 // sequence than another user-defined conversion sequence U2 if
3376 // they contain the same user-defined conversion function or
3377 // constructor and if the second standard conversion sequence of
3378 // U1 is better than the second standard conversion sequence of
3379 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00003380 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003381 ICS2.UserDefined.ConversionFunction)
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003382 Result = CompareStandardConversionSequences(S,
3383 ICS1.UserDefined.After,
3384 ICS2.UserDefined.After);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003385 else
3386 Result = compareConversionFunctions(S,
3387 ICS1.UserDefined.ConversionFunction,
3388 ICS2.UserDefined.ConversionFunction);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003389 }
3390
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003391 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003392}
3393
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003394static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3395 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3396 Qualifiers Quals;
3397 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003398 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003399 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003400
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003401 return Context.hasSameUnqualifiedType(T1, T2);
3402}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003403
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003404// Per 13.3.3.2p3, compare the given standard conversion sequences to
3405// determine if one is a proper subset of the other.
3406static ImplicitConversionSequence::CompareKind
3407compareStandardConversionSubsets(ASTContext &Context,
3408 const StandardConversionSequence& SCS1,
3409 const StandardConversionSequence& SCS2) {
3410 ImplicitConversionSequence::CompareKind Result
3411 = ImplicitConversionSequence::Indistinguishable;
3412
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003413 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00003414 // any non-identity conversion sequence
Douglas Gregor377c1092011-06-05 06:15:20 +00003415 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3416 return ImplicitConversionSequence::Better;
3417 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3418 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003419
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003420 if (SCS1.Second != SCS2.Second) {
3421 if (SCS1.Second == ICK_Identity)
3422 Result = ImplicitConversionSequence::Better;
3423 else if (SCS2.Second == ICK_Identity)
3424 Result = ImplicitConversionSequence::Worse;
3425 else
3426 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003427 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003428 return ImplicitConversionSequence::Indistinguishable;
3429
3430 if (SCS1.Third == SCS2.Third) {
3431 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3432 : ImplicitConversionSequence::Indistinguishable;
3433 }
3434
3435 if (SCS1.Third == ICK_Identity)
3436 return Result == ImplicitConversionSequence::Worse
3437 ? ImplicitConversionSequence::Indistinguishable
3438 : ImplicitConversionSequence::Better;
3439
3440 if (SCS2.Third == ICK_Identity)
3441 return Result == ImplicitConversionSequence::Better
3442 ? ImplicitConversionSequence::Indistinguishable
3443 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003444
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003445 return ImplicitConversionSequence::Indistinguishable;
3446}
3447
Douglas Gregore696ebb2011-01-26 14:52:12 +00003448/// \brief Determine whether one of the given reference bindings is better
3449/// than the other based on what kind of bindings they are.
Richard Smith19172c42014-07-14 02:28:44 +00003450static bool
3451isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3452 const StandardConversionSequence &SCS2) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003453 // C++0x [over.ics.rank]p3b4:
3454 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3455 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003456 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00003457 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003458 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00003459 // reference*.
3460 //
3461 // FIXME: Rvalue references. We're going rogue with the above edits,
3462 // because the semantics in the current C++0x working paper (N3225 at the
3463 // time of this writing) break the standard definition of std::forward
3464 // and std::reference_wrapper when dealing with references to functions.
3465 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00003466 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3467 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3468 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003469
Douglas Gregore696ebb2011-01-26 14:52:12 +00003470 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3471 SCS2.IsLvalueReference) ||
3472 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
Richard Smith19172c42014-07-14 02:28:44 +00003473 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
Douglas Gregore696ebb2011-01-26 14:52:12 +00003474}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003475
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003476/// CompareStandardConversionSequences - Compare two standard
3477/// conversion sequences to determine whether one is better than the
3478/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00003479static ImplicitConversionSequence::CompareKind
3480CompareStandardConversionSequences(Sema &S,
3481 const StandardConversionSequence& SCS1,
3482 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003483{
3484 // Standard conversion sequence S1 is a better conversion sequence
3485 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3486
3487 // -- S1 is a proper subsequence of S2 (comparing the conversion
3488 // sequences in the canonical form defined by 13.3.3.1.1,
3489 // excluding any Lvalue Transformation; the identity conversion
3490 // sequence is considered to be a subsequence of any
3491 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003492 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00003493 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003494 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003495
3496 // -- the rank of S1 is better than the rank of S2 (by the rules
3497 // defined below), or, if not that,
3498 ImplicitConversionRank Rank1 = SCS1.getRank();
3499 ImplicitConversionRank Rank2 = SCS2.getRank();
3500 if (Rank1 < Rank2)
3501 return ImplicitConversionSequence::Better;
3502 else if (Rank2 < Rank1)
3503 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003504
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003505 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3506 // are indistinguishable unless one of the following rules
3507 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00003508
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003509 // A conversion that is not a conversion of a pointer, or
3510 // pointer to member, to bool is better than another conversion
3511 // that is such a conversion.
3512 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3513 return SCS2.isPointerConversionToBool()
3514 ? ImplicitConversionSequence::Better
3515 : ImplicitConversionSequence::Worse;
3516
Douglas Gregor5c407d92008-10-23 00:40:37 +00003517 // C++ [over.ics.rank]p4b2:
3518 //
3519 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003520 // conversion of B* to A* is better than conversion of B* to
3521 // void*, and conversion of A* to void* is better than conversion
3522 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00003523 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003524 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00003525 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003526 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003527 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3528 // Exactly one of the conversion sequences is a conversion to
3529 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003530 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3531 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003532 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3533 // Neither conversion sequence converts to a void pointer; compare
3534 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003535 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall5c32be02010-08-24 20:38:10 +00003536 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003537 return DerivedCK;
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003538 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3539 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003540 // Both conversion sequences are conversions to void
3541 // pointers. Compare the source types to determine if there's an
3542 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00003543 QualType FromType1 = SCS1.getFromType();
3544 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003545
3546 // Adjust the types we're converting from via the array-to-pointer
3547 // conversion, if we need to.
3548 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003549 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003550 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003551 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003552
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003553 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3554 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003555
John McCall5c32be02010-08-24 20:38:10 +00003556 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003557 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003558 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003559 return ImplicitConversionSequence::Worse;
3560
3561 // Objective-C++: If one interface is more specific than the
3562 // other, it is the better one.
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003563 const ObjCObjectPointerType* FromObjCPtr1
3564 = FromType1->getAs<ObjCObjectPointerType>();
3565 const ObjCObjectPointerType* FromObjCPtr2
3566 = FromType2->getAs<ObjCObjectPointerType>();
3567 if (FromObjCPtr1 && FromObjCPtr2) {
3568 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3569 FromObjCPtr2);
3570 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3571 FromObjCPtr1);
3572 if (AssignLeft != AssignRight) {
3573 return AssignLeft? ImplicitConversionSequence::Better
3574 : ImplicitConversionSequence::Worse;
3575 }
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003576 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003577 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003578
3579 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3580 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00003581 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00003582 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003583 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003584
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003585 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003586 // Check for a better reference binding based on the kind of bindings.
3587 if (isBetterReferenceBindingKind(SCS1, SCS2))
3588 return ImplicitConversionSequence::Better;
3589 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3590 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003591
Sebastian Redlb28b4072009-03-22 23:49:27 +00003592 // C++ [over.ics.rank]p3b4:
3593 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3594 // which the references refer are the same type except for
3595 // top-level cv-qualifiers, and the type to which the reference
3596 // initialized by S2 refers is more cv-qualified than the type
3597 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003598 QualType T1 = SCS1.getToType(2);
3599 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003600 T1 = S.Context.getCanonicalType(T1);
3601 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003602 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003603 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3604 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003605 if (UnqualT1 == UnqualT2) {
John McCall31168b02011-06-15 23:02:42 +00003606 // Objective-C++ ARC: If the references refer to objects with different
3607 // lifetimes, prefer bindings that don't change lifetime.
3608 if (SCS1.ObjCLifetimeConversionBinding !=
3609 SCS2.ObjCLifetimeConversionBinding) {
3610 return SCS1.ObjCLifetimeConversionBinding
3611 ? ImplicitConversionSequence::Worse
3612 : ImplicitConversionSequence::Better;
3613 }
3614
Chandler Carruth8e543b32010-12-12 08:17:55 +00003615 // If the type is an array type, promote the element qualifiers to the
3616 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003617 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003618 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003619 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003620 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003621 if (T2.isMoreQualifiedThan(T1))
3622 return ImplicitConversionSequence::Better;
3623 else if (T1.isMoreQualifiedThan(T2))
John McCall31168b02011-06-15 23:02:42 +00003624 return ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003625 }
3626 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003627
Francois Pichet08d2fa02011-09-18 21:37:37 +00003628 // In Microsoft mode, prefer an integral conversion to a
3629 // floating-to-integral conversion if the integral conversion
3630 // is between types of the same size.
3631 // For example:
3632 // void f(float);
3633 // void f(int);
3634 // int main {
3635 // long a;
3636 // f(a);
3637 // }
3638 // Here, MSVC will call f(int) instead of generating a compile error
3639 // as clang will do in standard mode.
Alp Tokerbfa39342014-01-14 12:51:41 +00003640 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3641 SCS2.Second == ICK_Floating_Integral &&
Francois Pichet08d2fa02011-09-18 21:37:37 +00003642 S.Context.getTypeSize(SCS1.getFromType()) ==
Alp Tokerbfa39342014-01-14 12:51:41 +00003643 S.Context.getTypeSize(SCS1.getToType(2)))
Francois Pichet08d2fa02011-09-18 21:37:37 +00003644 return ImplicitConversionSequence::Better;
3645
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003646 return ImplicitConversionSequence::Indistinguishable;
3647}
3648
3649/// CompareQualificationConversions - Compares two standard conversion
3650/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00003651/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
Richard Smith17c00b42014-11-12 01:24:00 +00003652static ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003653CompareQualificationConversions(Sema &S,
3654 const StandardConversionSequence& SCS1,
3655 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00003656 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003657 // -- S1 and S2 differ only in their qualification conversion and
3658 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3659 // cv-qualification signature of type T1 is a proper subset of
3660 // the cv-qualification signature of type T2, and S1 is not the
3661 // deprecated string literal array-to-pointer conversion (4.2).
3662 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3663 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3664 return ImplicitConversionSequence::Indistinguishable;
3665
3666 // FIXME: the example in the standard doesn't use a qualification
3667 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003668 QualType T1 = SCS1.getToType(2);
3669 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003670 T1 = S.Context.getCanonicalType(T1);
3671 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003672 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003673 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3674 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003675
3676 // If the types are the same, we won't learn anything by unwrapped
3677 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003678 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003679 return ImplicitConversionSequence::Indistinguishable;
3680
Chandler Carruth607f38e2009-12-29 07:16:59 +00003681 // If the type is an array type, promote the element qualifiers to the type
3682 // for comparison.
3683 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003684 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003685 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003686 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003687
Mike Stump11289f42009-09-09 15:08:12 +00003688 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003689 = ImplicitConversionSequence::Indistinguishable;
John McCall31168b02011-06-15 23:02:42 +00003690
3691 // Objective-C++ ARC:
3692 // Prefer qualification conversions not involving a change in lifetime
3693 // to qualification conversions that do not change lifetime.
3694 if (SCS1.QualificationIncludesObjCLifetime !=
3695 SCS2.QualificationIncludesObjCLifetime) {
3696 Result = SCS1.QualificationIncludesObjCLifetime
3697 ? ImplicitConversionSequence::Worse
3698 : ImplicitConversionSequence::Better;
3699 }
3700
John McCall5c32be02010-08-24 20:38:10 +00003701 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003702 // Within each iteration of the loop, we check the qualifiers to
3703 // determine if this still looks like a qualification
3704 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003705 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003706 // until there are no more pointers or pointers-to-members left
3707 // to unwrap. This essentially mimics what
3708 // IsQualificationConversion does, but here we're checking for a
3709 // strict subset of qualifiers.
3710 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3711 // The qualifiers are the same, so this doesn't tell us anything
3712 // about how the sequences rank.
3713 ;
3714 else if (T2.isMoreQualifiedThan(T1)) {
3715 // T1 has fewer qualifiers, so it could be the better sequence.
3716 if (Result == ImplicitConversionSequence::Worse)
3717 // Neither has qualifiers that are a subset of the other's
3718 // qualifiers.
3719 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003720
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003721 Result = ImplicitConversionSequence::Better;
3722 } else if (T1.isMoreQualifiedThan(T2)) {
3723 // T2 has fewer qualifiers, so it could be the better sequence.
3724 if (Result == ImplicitConversionSequence::Better)
3725 // Neither has qualifiers that are a subset of the other's
3726 // qualifiers.
3727 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003728
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003729 Result = ImplicitConversionSequence::Worse;
3730 } else {
3731 // Qualifiers are disjoint.
3732 return ImplicitConversionSequence::Indistinguishable;
3733 }
3734
3735 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00003736 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003737 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003738 }
3739
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003740 // Check that the winning standard conversion sequence isn't using
3741 // the deprecated string literal array to pointer conversion.
3742 switch (Result) {
3743 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003744 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003745 Result = ImplicitConversionSequence::Indistinguishable;
3746 break;
3747
3748 case ImplicitConversionSequence::Indistinguishable:
3749 break;
3750
3751 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003752 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003753 Result = ImplicitConversionSequence::Indistinguishable;
3754 break;
3755 }
3756
3757 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003758}
3759
Douglas Gregor5c407d92008-10-23 00:40:37 +00003760/// CompareDerivedToBaseConversions - Compares two standard conversion
3761/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00003762/// various kinds of derived-to-base conversions (C++
3763/// [over.ics.rank]p4b3). As part of these checks, we also look at
3764/// conversions between Objective-C interface types.
Richard Smith17c00b42014-11-12 01:24:00 +00003765static ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003766CompareDerivedToBaseConversions(Sema &S,
3767 const StandardConversionSequence& SCS1,
3768 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00003769 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003770 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00003771 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003772 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003773
3774 // Adjust the types we're converting from via the array-to-pointer
3775 // conversion, if we need to.
3776 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003777 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003778 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003779 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003780
3781 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00003782 FromType1 = S.Context.getCanonicalType(FromType1);
3783 ToType1 = S.Context.getCanonicalType(ToType1);
3784 FromType2 = S.Context.getCanonicalType(FromType2);
3785 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003786
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003787 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00003788 //
3789 // If class B is derived directly or indirectly from class A and
3790 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00003791 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003792 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00003793 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00003794 SCS2.Second == ICK_Pointer_Conversion &&
3795 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3796 FromType1->isPointerType() && FromType2->isPointerType() &&
3797 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003798 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003799 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00003800 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003801 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003802 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003803 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003804 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003805 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00003806
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003807 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00003808 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003809 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003810 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003811 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003812 return ImplicitConversionSequence::Worse;
3813 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003814
3815 // -- conversion of B* to A* is better than conversion of C* to A*,
3816 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003817 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003818 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003819 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003820 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00003821 }
3822 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3823 SCS2.Second == ICK_Pointer_Conversion) {
3824 const ObjCObjectPointerType *FromPtr1
3825 = FromType1->getAs<ObjCObjectPointerType>();
3826 const ObjCObjectPointerType *FromPtr2
3827 = FromType2->getAs<ObjCObjectPointerType>();
3828 const ObjCObjectPointerType *ToPtr1
3829 = ToType1->getAs<ObjCObjectPointerType>();
3830 const ObjCObjectPointerType *ToPtr2
3831 = ToType2->getAs<ObjCObjectPointerType>();
3832
3833 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3834 // Apply the same conversion ranking rules for Objective-C pointer types
3835 // that we do for C++ pointers to class types. However, we employ the
3836 // Objective-C pseudo-subtyping relationship used for assignment of
3837 // Objective-C pointer types.
3838 bool FromAssignLeft
3839 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3840 bool FromAssignRight
3841 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3842 bool ToAssignLeft
3843 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3844 bool ToAssignRight
3845 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3846
3847 // A conversion to an a non-id object pointer type or qualified 'id'
3848 // type is better than a conversion to 'id'.
3849 if (ToPtr1->isObjCIdType() &&
3850 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3851 return ImplicitConversionSequence::Worse;
3852 if (ToPtr2->isObjCIdType() &&
3853 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3854 return ImplicitConversionSequence::Better;
3855
3856 // A conversion to a non-id object pointer type is better than a
3857 // conversion to a qualified 'id' type
3858 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3859 return ImplicitConversionSequence::Worse;
3860 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3861 return ImplicitConversionSequence::Better;
3862
3863 // A conversion to an a non-Class object pointer type or qualified 'Class'
3864 // type is better than a conversion to 'Class'.
3865 if (ToPtr1->isObjCClassType() &&
3866 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3867 return ImplicitConversionSequence::Worse;
3868 if (ToPtr2->isObjCClassType() &&
3869 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3870 return ImplicitConversionSequence::Better;
3871
3872 // A conversion to a non-Class object pointer type is better than a
3873 // conversion to a qualified 'Class' type.
3874 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3875 return ImplicitConversionSequence::Worse;
3876 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3877 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00003878
Douglas Gregor058d3de2011-01-31 18:51:41 +00003879 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3880 if (S.Context.hasSameType(FromType1, FromType2) &&
3881 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3882 (ToAssignLeft != ToAssignRight))
3883 return ToAssignLeft? ImplicitConversionSequence::Worse
3884 : ImplicitConversionSequence::Better;
3885
3886 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3887 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3888 (FromAssignLeft != FromAssignRight))
3889 return FromAssignLeft? ImplicitConversionSequence::Better
3890 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003891 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00003892 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00003893
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003894 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003895 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3896 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3897 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003898 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003899 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003900 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003901 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003902 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003903 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003904 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003905 ToType2->getAs<MemberPointerType>();
3906 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3907 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3908 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3909 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3910 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3911 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3912 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3913 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003914 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003915 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003916 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003917 return ImplicitConversionSequence::Worse;
John McCall5c32be02010-08-24 20:38:10 +00003918 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003919 return ImplicitConversionSequence::Better;
3920 }
3921 // conversion of B::* to C::* is better than conversion of A::* to C::*
3922 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003923 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003924 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003925 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003926 return ImplicitConversionSequence::Worse;
3927 }
3928 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003929
Douglas Gregor5ab11652010-04-17 22:01:05 +00003930 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00003931 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00003932 // -- binding of an expression of type C to a reference of type
3933 // B& is better than binding an expression of type C to a
3934 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003935 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3936 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3937 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003938 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003939 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003940 return ImplicitConversionSequence::Worse;
3941 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003942
Douglas Gregor2fe98832008-11-03 19:09:14 +00003943 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00003944 // -- binding of an expression of type B to a reference of type
3945 // A& is better than binding an expression of type C to a
3946 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003947 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3948 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3949 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003950 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003951 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003952 return ImplicitConversionSequence::Worse;
3953 }
3954 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003955
Douglas Gregor5c407d92008-10-23 00:40:37 +00003956 return ImplicitConversionSequence::Indistinguishable;
3957}
3958
Douglas Gregor45bb4832013-03-26 23:36:30 +00003959/// \brief Determine whether the given type is valid, e.g., it is not an invalid
3960/// C++ class.
3961static bool isTypeValid(QualType T) {
3962 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3963 return !Record->isInvalidDecl();
3964
3965 return true;
3966}
3967
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003968/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3969/// determine whether they are reference-related,
3970/// reference-compatible, reference-compatible with added
3971/// qualification, or incompatible, for use in C++ initialization by
3972/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3973/// type, and the first type (T1) is the pointee type of the reference
3974/// type being initialized.
3975Sema::ReferenceCompareResult
3976Sema::CompareReferenceRelationship(SourceLocation Loc,
3977 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003978 bool &DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003979 bool &ObjCConversion,
3980 bool &ObjCLifetimeConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003981 assert(!OrigT1->isReferenceType() &&
3982 "T1 must be the pointee type of the reference type");
3983 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3984
3985 QualType T1 = Context.getCanonicalType(OrigT1);
3986 QualType T2 = Context.getCanonicalType(OrigT2);
3987 Qualifiers T1Quals, T2Quals;
3988 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3989 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3990
3991 // C++ [dcl.init.ref]p4:
3992 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3993 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3994 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003995 DerivedToBase = false;
3996 ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003997 ObjCLifetimeConversion = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003998 if (UnqualT1 == UnqualT2) {
3999 // Nothing to do.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004000 } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
Douglas Gregor45bb4832013-03-26 23:36:30 +00004001 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4002 IsDerivedFrom(UnqualT2, UnqualT1))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004003 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004004 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4005 UnqualT2->isObjCObjectOrInterfaceType() &&
4006 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4007 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004008 else
4009 return Ref_Incompatible;
4010
4011 // At this point, we know that T1 and T2 are reference-related (at
4012 // least).
4013
4014 // If the type is an array type, promote the element qualifiers to the type
4015 // for comparison.
4016 if (isa<ArrayType>(T1) && T1Quals)
4017 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4018 if (isa<ArrayType>(T2) && T2Quals)
4019 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4020
4021 // C++ [dcl.init.ref]p4:
4022 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4023 // reference-related to T2 and cv1 is the same cv-qualification
4024 // as, or greater cv-qualification than, cv2. For purposes of
4025 // overload resolution, cases for which cv1 is greater
4026 // cv-qualification than cv2 are identified as
4027 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregord517d552011-04-28 17:56:11 +00004028 //
4029 // Note that we also require equivalence of Objective-C GC and address-space
4030 // qualifiers when performing these computations, so that e.g., an int in
4031 // address space 1 is not reference-compatible with an int in address
4032 // space 2.
John McCall31168b02011-06-15 23:02:42 +00004033 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4034 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00004035 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4036 ObjCLifetimeConversion = true;
4037
John McCall31168b02011-06-15 23:02:42 +00004038 T1Quals.removeObjCLifetime();
4039 T2Quals.removeObjCLifetime();
John McCall31168b02011-06-15 23:02:42 +00004040 }
4041
Douglas Gregord517d552011-04-28 17:56:11 +00004042 if (T1Quals == T2Quals)
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004043 return Ref_Compatible;
John McCall31168b02011-06-15 23:02:42 +00004044 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004045 return Ref_Compatible_With_Added_Qualification;
4046 else
4047 return Ref_Related;
4048}
4049
Douglas Gregor836a7e82010-08-11 02:15:33 +00004050/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00004051/// with DeclType. Return true if something definite is found.
4052static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00004053FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4054 QualType DeclType, SourceLocation DeclLoc,
4055 Expr *Init, QualType T2, bool AllowRvalues,
4056 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004057 assert(T2->isRecordType() && "Can only find conversions of record types.");
4058 CXXRecordDecl *T2RecordDecl
4059 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4060
Richard Smith100b24a2014-04-17 01:52:14 +00004061 OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal);
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004062 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4063 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004064 NamedDecl *D = *I;
4065 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4066 if (isa<UsingShadowDecl>(D))
4067 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4068
4069 FunctionTemplateDecl *ConvTemplate
4070 = dyn_cast<FunctionTemplateDecl>(D);
4071 CXXConversionDecl *Conv;
4072 if (ConvTemplate)
4073 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4074 else
4075 Conv = cast<CXXConversionDecl>(D);
4076
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004077 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00004078 // explicit conversions, skip it.
4079 if (!AllowExplicit && Conv->isExplicit())
4080 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004081
Douglas Gregor836a7e82010-08-11 02:15:33 +00004082 if (AllowRvalues) {
4083 bool DerivedToBase = false;
4084 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004085 bool ObjCLifetimeConversion = false;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004086
4087 // If we are initializing an rvalue reference, don't permit conversion
4088 // functions that return lvalues.
4089 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4090 const ReferenceType *RefType
4091 = Conv->getConversionType()->getAs<LValueReferenceType>();
4092 if (RefType && !RefType->getPointeeType()->isFunctionType())
4093 continue;
4094 }
4095
Douglas Gregor836a7e82010-08-11 02:15:33 +00004096 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00004097 S.CompareReferenceRelationship(
4098 DeclLoc,
4099 Conv->getConversionType().getNonReferenceType()
4100 .getUnqualifiedType(),
4101 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCall31168b02011-06-15 23:02:42 +00004102 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth8e543b32010-12-12 08:17:55 +00004103 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00004104 continue;
4105 } else {
4106 // If the conversion function doesn't return a reference type,
4107 // it can't be considered for this conversion. An rvalue reference
4108 // is only acceptable if its referencee is a function type.
4109
4110 const ReferenceType *RefType =
4111 Conv->getConversionType()->getAs<ReferenceType>();
4112 if (!RefType ||
4113 (!RefType->isLValueReferenceType() &&
4114 !RefType->getPointeeType()->isFunctionType()))
4115 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00004116 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004117
Douglas Gregor836a7e82010-08-11 02:15:33 +00004118 if (ConvTemplate)
4119 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004120 Init, DeclType, CandidateSet,
4121 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor836a7e82010-08-11 02:15:33 +00004122 else
4123 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004124 DeclType, CandidateSet,
4125 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redld92badf2010-06-30 18:13:39 +00004126 }
4127
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004128 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4129
Sebastian Redld92badf2010-06-30 18:13:39 +00004130 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00004131 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004132 case OR_Success:
4133 // C++ [over.ics.ref]p1:
4134 //
4135 // [...] If the parameter binds directly to the result of
4136 // applying a conversion function to the argument
4137 // expression, the implicit conversion sequence is a
4138 // user-defined conversion sequence (13.3.3.1.2), with the
4139 // second standard conversion sequence either an identity
4140 // conversion or, if the conversion function returns an
4141 // entity of a type that is a derived class of the parameter
4142 // type, a derived-to-base Conversion.
4143 if (!Best->FinalConversion.DirectBinding)
4144 return false;
4145
4146 ICS.setUserDefined();
4147 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4148 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004149 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redld92badf2010-06-30 18:13:39 +00004150 ICS.UserDefined.ConversionFunction = Best->Function;
John McCall30909032011-09-21 08:36:56 +00004151 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redld92badf2010-06-30 18:13:39 +00004152 ICS.UserDefined.EllipsisConversion = false;
4153 assert(ICS.UserDefined.After.ReferenceBinding &&
4154 ICS.UserDefined.After.DirectBinding &&
4155 "Expected a direct reference binding!");
4156 return true;
4157
4158 case OR_Ambiguous:
4159 ICS.setAmbiguous();
4160 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4161 Cand != CandidateSet.end(); ++Cand)
4162 if (Cand->Viable)
4163 ICS.Ambiguous.addConversion(Cand->Function);
4164 return true;
4165
4166 case OR_No_Viable_Function:
4167 case OR_Deleted:
4168 // There was no suitable conversion, or we found a deleted
4169 // conversion; continue with other checks.
4170 return false;
4171 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004172
David Blaikie8a40f702012-01-17 06:56:22 +00004173 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redld92badf2010-06-30 18:13:39 +00004174}
4175
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004176/// \brief Compute an implicit conversion sequence for reference
4177/// initialization.
4178static ImplicitConversionSequence
Sebastian Redldf888642011-12-03 14:54:30 +00004179TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004180 SourceLocation DeclLoc,
4181 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00004182 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004183 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4184
4185 // Most paths end in a failed conversion.
4186 ImplicitConversionSequence ICS;
4187 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4188
4189 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4190 QualType T2 = Init->getType();
4191
4192 // If the initializer is the address of an overloaded function, try
4193 // to resolve the overloaded function. If all goes well, T2 is the
4194 // type of the resulting function.
4195 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4196 DeclAccessPair Found;
4197 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4198 false, Found))
4199 T2 = Fn->getType();
4200 }
4201
4202 // Compute some basic properties of the types and the initializer.
4203 bool isRValRef = DeclType->isRValueReferenceType();
4204 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004205 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004206 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00004207 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004208 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004209 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004210 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004211
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004212
Sebastian Redld92badf2010-06-30 18:13:39 +00004213 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00004214 // A reference to type "cv1 T1" is initialized by an expression
4215 // of type "cv2 T2" as follows:
4216
Sebastian Redld92badf2010-06-30 18:13:39 +00004217 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00004218 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004219 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4220 // reference-compatible with "cv2 T2," or
4221 //
4222 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4223 if (InitCategory.isLValue() &&
4224 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004225 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00004226 // When a parameter of reference type binds directly (8.5.3)
4227 // to an argument expression, the implicit conversion sequence
4228 // is the identity conversion, unless the argument expression
4229 // has a type that is a derived class of the parameter type,
4230 // in which case the implicit conversion sequence is a
4231 // derived-to-base Conversion (13.3.3.1).
4232 ICS.setStandard();
4233 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004234 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4235 : ObjCConversion? ICK_Compatible_Conversion
4236 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00004237 ICS.Standard.Third = ICK_Identity;
4238 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4239 ICS.Standard.setToType(0, T2);
4240 ICS.Standard.setToType(1, T1);
4241 ICS.Standard.setToType(2, T1);
4242 ICS.Standard.ReferenceBinding = true;
4243 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004244 ICS.Standard.IsLvalueReference = !isRValRef;
4245 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4246 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004247 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004248 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Craig Topperc3ec1492014-05-26 06:22:03 +00004249 ICS.Standard.CopyConstructor = nullptr;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004250 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004251
Sebastian Redld92badf2010-06-30 18:13:39 +00004252 // Nothing more to do: the inaccessibility/ambiguity check for
4253 // derived-to-base conversions is suppressed when we're
4254 // computing the implicit conversion sequence (C++
4255 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004256 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00004257 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004258
Sebastian Redld92badf2010-06-30 18:13:39 +00004259 // -- has a class type (i.e., T2 is a class type), where T1 is
4260 // not reference-related to T2, and can be implicitly
4261 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4262 // is reference-compatible with "cv3 T3" 92) (this
4263 // conversion is selected by enumerating the applicable
4264 // conversion functions (13.3.1.6) and choosing the best
4265 // one through overload resolution (13.3)),
4266 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004267 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00004268 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00004269 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4270 Init, T2, /*AllowRvalues=*/false,
4271 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00004272 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004273 }
4274 }
4275
Sebastian Redld92badf2010-06-30 18:13:39 +00004276 // -- Otherwise, the reference shall be an lvalue reference to a
4277 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00004278 // shall be an rvalue reference.
Richard Smithce4f6082012-05-24 04:29:20 +00004279 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004280 return ICS;
4281
Douglas Gregorf143cd52011-01-24 16:14:37 +00004282 // -- If the initializer expression
4283 //
4284 // -- is an xvalue, class prvalue, array prvalue or function
John McCall31168b02011-06-15 23:02:42 +00004285 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregorf143cd52011-01-24 16:14:37 +00004286 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4287 (InitCategory.isXValue() ||
4288 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4289 (InitCategory.isLValue() && T2->isFunctionType()))) {
4290 ICS.setStandard();
4291 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004292 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004293 : ObjCConversion? ICK_Compatible_Conversion
4294 : ICK_Identity;
4295 ICS.Standard.Third = ICK_Identity;
4296 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4297 ICS.Standard.setToType(0, T2);
4298 ICS.Standard.setToType(1, T1);
4299 ICS.Standard.setToType(2, T1);
4300 ICS.Standard.ReferenceBinding = true;
4301 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4302 // binding unless we're binding to a class prvalue.
4303 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4304 // allow the use of rvalue references in C++98/03 for the benefit of
4305 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004306 ICS.Standard.DirectBinding =
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004307 S.getLangOpts().CPlusPlus11 ||
Richard Smithb94afe12014-07-14 19:54:05 +00004308 !(InitCategory.isPRValue() || T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00004309 ICS.Standard.IsLvalueReference = !isRValRef;
4310 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004311 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00004312 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004313 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Craig Topperc3ec1492014-05-26 06:22:03 +00004314 ICS.Standard.CopyConstructor = nullptr;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004315 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004316 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00004317 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004318
Douglas Gregorf143cd52011-01-24 16:14:37 +00004319 // -- has a class type (i.e., T2 is a class type), where T1 is not
4320 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004321 // an xvalue, class prvalue, or function lvalue of type
4322 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00004323 // "cv3 T3",
4324 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004325 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00004326 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004327 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004328 // class subobject).
4329 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004330 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004331 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4332 Init, T2, /*AllowRvalues=*/true,
4333 AllowExplicit)) {
4334 // In the second case, if the reference is an rvalue reference
4335 // and the second standard conversion sequence of the
4336 // user-defined conversion sequence includes an lvalue-to-rvalue
4337 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004338 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004339 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4340 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4341
Douglas Gregor95273c32011-01-21 16:36:05 +00004342 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00004343 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004344
Richard Smith19172c42014-07-14 02:28:44 +00004345 // A temporary of function type cannot be created; don't even try.
4346 if (T1->isFunctionType())
4347 return ICS;
4348
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004349 // -- Otherwise, a temporary of type "cv1 T1" is created and
4350 // initialized from the initializer expression using the
4351 // rules for a non-reference copy initialization (8.5). The
4352 // reference is then bound to the temporary. If T1 is
4353 // reference-related to T2, cv1 must be the same
4354 // cv-qualification as, or greater cv-qualification than,
4355 // cv2; otherwise, the program is ill-formed.
4356 if (RefRelationship == Sema::Ref_Related) {
4357 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4358 // we would be reference-compatible or reference-compatible with
4359 // added qualification. But that wasn't the case, so the reference
4360 // initialization fails.
John McCall31168b02011-06-15 23:02:42 +00004361 //
4362 // Note that we only want to check address spaces and cvr-qualifiers here.
4363 // ObjC GC and lifetime qualifiers aren't important.
4364 Qualifiers T1Quals = T1.getQualifiers();
4365 Qualifiers T2Quals = T2.getQualifiers();
4366 T1Quals.removeObjCGCAttr();
4367 T1Quals.removeObjCLifetime();
4368 T2Quals.removeObjCGCAttr();
4369 T2Quals.removeObjCLifetime();
4370 if (!T1Quals.compatiblyIncludes(T2Quals))
4371 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004372 }
4373
4374 // If at least one of the types is a class type, the types are not
4375 // related, and we aren't allowed any user conversions, the
4376 // reference binding fails. This case is important for breaking
4377 // recursion, since TryImplicitConversion below will attempt to
4378 // create a temporary through the use of a copy constructor.
4379 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4380 (T1->isRecordType() || T2->isRecordType()))
4381 return ICS;
4382
Douglas Gregorcba72b12011-01-21 05:18:22 +00004383 // If T1 is reference-related to T2 and the reference is an rvalue
4384 // reference, the initializer expression shall not be an lvalue.
4385 if (RefRelationship >= Sema::Ref_Related &&
4386 isRValRef && Init->Classify(S.Context).isLValue())
4387 return ICS;
4388
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004389 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004390 // When a parameter of reference type is not bound directly to
4391 // an argument expression, the conversion sequence is the one
4392 // required to convert the argument expression to the
4393 // underlying type of the reference according to
4394 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4395 // to copy-initializing a temporary of the underlying type with
4396 // the argument expression. Any difference in top-level
4397 // cv-qualification is subsumed by the initialization itself
4398 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00004399 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4400 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004401 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004402 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004403 /*AllowObjCWritebackConversion=*/false,
4404 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004405
4406 // Of course, that's still a reference binding.
4407 if (ICS.isStandard()) {
4408 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004409 ICS.Standard.IsLvalueReference = !isRValRef;
Richard Smith19172c42014-07-14 02:28:44 +00004410 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004411 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004412 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004413 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004414 } else if (ICS.isUserDefined()) {
Richard Smith19172c42014-07-14 02:28:44 +00004415 const ReferenceType *LValRefType =
4416 ICS.UserDefined.ConversionFunction->getReturnType()
4417 ->getAs<LValueReferenceType>();
4418
4419 // C++ [over.ics.ref]p3:
4420 // Except for an implicit object parameter, for which see 13.3.1, a
4421 // standard conversion sequence cannot be formed if it requires [...]
4422 // binding an rvalue reference to an lvalue other than a function
4423 // lvalue.
4424 // Note that the function case is not possible here.
4425 if (DeclType->isRValueReferenceType() && LValRefType) {
4426 // FIXME: This is the wrong BadConversionSequence. The problem is binding
4427 // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4428 // reference to an rvalue!
4429 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4430 return ICS;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004431 }
Richard Smith19172c42014-07-14 02:28:44 +00004432
Ismail Pazarbasi99afd962014-01-24 10:54:12 +00004433 ICS.UserDefined.Before.setAsIdentityConversion();
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004434 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004435 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
Richard Smith19172c42014-07-14 02:28:44 +00004436 ICS.UserDefined.After.BindsToFunctionLvalue = false;
4437 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004438 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4439 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004440 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00004441
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004442 return ICS;
4443}
4444
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004445static ImplicitConversionSequence
4446TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4447 bool SuppressUserConversions,
4448 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004449 bool AllowObjCWritebackConversion,
4450 bool AllowExplicit = false);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004451
4452/// TryListConversion - Try to copy-initialize a value of type ToType from the
4453/// initializer list From.
4454static ImplicitConversionSequence
4455TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4456 bool SuppressUserConversions,
4457 bool InOverloadResolution,
4458 bool AllowObjCWritebackConversion) {
4459 // C++11 [over.ics.list]p1:
4460 // When an argument is an initializer list, it is not an expression and
4461 // special rules apply for converting it to a parameter type.
4462
4463 ImplicitConversionSequence Result;
4464 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4465
Sebastian Redl09edce02012-01-23 22:09:39 +00004466 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004467 // initialized from init lists.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004468 if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004469 return Result;
4470
Larisse Voufo19d08672015-01-27 18:47:05 +00004471 // Per DR1467:
4472 // If the parameter type is a class X and the initializer list has a single
4473 // element of type cv U, where U is X or a class derived from X, the
4474 // implicit conversion sequence is the one required to convert the element
4475 // to the parameter type.
4476 //
4477 // Otherwise, if the parameter type is a character array [... ]
4478 // and the initializer list has a single element that is an
4479 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4480 // implicit conversion sequence is the identity conversion.
4481 if (From->getNumInits() == 1) {
4482 if (ToType->isRecordType()) {
4483 QualType InitType = From->getInit(0)->getType();
4484 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
4485 S.IsDerivedFrom(InitType, ToType))
4486 return TryCopyInitialization(S, From->getInit(0), ToType,
4487 SuppressUserConversions,
4488 InOverloadResolution,
4489 AllowObjCWritebackConversion);
4490 }
Richard Smith1bbaba82015-01-27 23:23:39 +00004491 // FIXME: Check the other conditions here: array of character type,
4492 // initializer is a string literal.
4493 if (ToType->isArrayType()) {
Larisse Voufo19d08672015-01-27 18:47:05 +00004494 InitializedEntity Entity =
4495 InitializedEntity::InitializeParameter(S.Context, ToType,
4496 /*Consumed=*/false);
4497 if (S.CanPerformCopyInitialization(Entity, From)) {
4498 Result.setStandard();
4499 Result.Standard.setAsIdentityConversion();
4500 Result.Standard.setFromType(ToType);
4501 Result.Standard.setAllToTypes(ToType);
4502 return Result;
4503 }
4504 }
4505 }
4506
4507 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004508 // C++11 [over.ics.list]p2:
4509 // If the parameter type is std::initializer_list<X> or "array of X" and
4510 // all the elements can be implicitly converted to X, the implicit
4511 // conversion sequence is the worst conversion necessary to convert an
4512 // element of the list to X.
Larisse Voufo19d08672015-01-27 18:47:05 +00004513 //
4514 // C++14 [over.ics.list]p3:
NAKAMURA Takumib01d86b2015-02-25 11:02:00 +00004515 // Otherwise, if the parameter type is "array of N X", if the initializer
Larisse Voufo19d08672015-01-27 18:47:05 +00004516 // list has exactly N elements or if it has fewer than N elements and X is
4517 // default-constructible, and if all the elements of the initializer list
4518 // can be implicitly converted to X, the implicit conversion sequence is
4519 // the worst conversion necessary to convert an element of the list to X.
Richard Smith1bbaba82015-01-27 23:23:39 +00004520 //
4521 // FIXME: We're missing a lot of these checks.
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004522 bool toStdInitializerList = false;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004523 QualType X;
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004524 if (ToType->isArrayType())
Richard Smith0db1ea52012-12-09 06:48:56 +00004525 X = S.Context.getAsArrayType(ToType)->getElementType();
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004526 else
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004527 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004528 if (!X.isNull()) {
4529 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4530 Expr *Init = From->getInit(i);
4531 ImplicitConversionSequence ICS =
4532 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4533 InOverloadResolution,
4534 AllowObjCWritebackConversion);
4535 // If a single element isn't convertible, fail.
4536 if (ICS.isBad()) {
4537 Result = ICS;
4538 break;
4539 }
4540 // Otherwise, look for the worst conversion.
4541 if (Result.isBad() ||
4542 CompareImplicitConversionSequences(S, ICS, Result) ==
4543 ImplicitConversionSequence::Worse)
4544 Result = ICS;
4545 }
Douglas Gregor0f5c1c02012-04-04 23:09:20 +00004546
4547 // For an empty list, we won't have computed any conversion sequence.
4548 // Introduce the identity conversion sequence.
4549 if (From->getNumInits() == 0) {
4550 Result.setStandard();
4551 Result.Standard.setAsIdentityConversion();
4552 Result.Standard.setFromType(ToType);
4553 Result.Standard.setAllToTypes(ToType);
4554 }
4555
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004556 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004557 return Result;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004558 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004559
Larisse Voufo19d08672015-01-27 18:47:05 +00004560 // C++14 [over.ics.list]p4:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004561 // C++11 [over.ics.list]p3:
4562 // Otherwise, if the parameter is a non-aggregate class X and overload
4563 // resolution chooses a single best constructor [...] the implicit
4564 // conversion sequence is a user-defined conversion sequence. If multiple
4565 // constructors are viable but none is better than the others, the
4566 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004567 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4568 // This function can deal with initializer lists.
Richard Smitha93f1022013-09-06 22:30:28 +00004569 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4570 /*AllowExplicit=*/false,
4571 InOverloadResolution, /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004572 AllowObjCWritebackConversion,
4573 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004574 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004575
Larisse Voufo19d08672015-01-27 18:47:05 +00004576 // C++14 [over.ics.list]p5:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004577 // C++11 [over.ics.list]p4:
4578 // Otherwise, if the parameter has an aggregate type which can be
4579 // initialized from the initializer list [...] the implicit conversion
4580 // sequence is a user-defined conversion sequence.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004581 if (ToType->isAggregateType()) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004582 // Type is an aggregate, argument is an init list. At this point it comes
4583 // down to checking whether the initialization works.
4584 // FIXME: Find out whether this parameter is consumed or not.
4585 InitializedEntity Entity =
4586 InitializedEntity::InitializeParameter(S.Context, ToType,
4587 /*Consumed=*/false);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004588 if (S.CanPerformCopyInitialization(Entity, From)) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004589 Result.setUserDefined();
4590 Result.UserDefined.Before.setAsIdentityConversion();
4591 // Initializer lists don't have a type.
4592 Result.UserDefined.Before.setFromType(QualType());
4593 Result.UserDefined.Before.setAllToTypes(QualType());
4594
4595 Result.UserDefined.After.setAsIdentityConversion();
4596 Result.UserDefined.After.setFromType(ToType);
4597 Result.UserDefined.After.setAllToTypes(ToType);
Craig Topperc3ec1492014-05-26 06:22:03 +00004598 Result.UserDefined.ConversionFunction = nullptr;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004599 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004600 return Result;
4601 }
4602
Larisse Voufo19d08672015-01-27 18:47:05 +00004603 // C++14 [over.ics.list]p6:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004604 // C++11 [over.ics.list]p5:
4605 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redldf888642011-12-03 14:54:30 +00004606 if (ToType->isReferenceType()) {
4607 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4608 // mention initializer lists in any way. So we go by what list-
4609 // initialization would do and try to extrapolate from that.
4610
4611 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4612
4613 // If the initializer list has a single element that is reference-related
4614 // to the parameter type, we initialize the reference from that.
4615 if (From->getNumInits() == 1) {
4616 Expr *Init = From->getInit(0);
4617
4618 QualType T2 = Init->getType();
4619
4620 // If the initializer is the address of an overloaded function, try
4621 // to resolve the overloaded function. If all goes well, T2 is the
4622 // type of the resulting function.
4623 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4624 DeclAccessPair Found;
4625 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4626 Init, ToType, false, Found))
4627 T2 = Fn->getType();
4628 }
4629
4630 // Compute some basic properties of the types and the initializer.
4631 bool dummy1 = false;
4632 bool dummy2 = false;
4633 bool dummy3 = false;
4634 Sema::ReferenceCompareResult RefRelationship
4635 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4636 dummy2, dummy3);
4637
Richard Smith4d2bbd72013-09-06 01:22:42 +00004638 if (RefRelationship >= Sema::Ref_Related) {
Richard Smitha93f1022013-09-06 22:30:28 +00004639 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4640 SuppressUserConversions,
4641 /*AllowExplicit=*/false);
Richard Smith4d2bbd72013-09-06 01:22:42 +00004642 }
Sebastian Redldf888642011-12-03 14:54:30 +00004643 }
4644
4645 // Otherwise, we bind the reference to a temporary created from the
4646 // initializer list.
4647 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4648 InOverloadResolution,
4649 AllowObjCWritebackConversion);
4650 if (Result.isFailure())
4651 return Result;
4652 assert(!Result.isEllipsis() &&
4653 "Sub-initialization cannot result in ellipsis conversion.");
4654
4655 // Can we even bind to a temporary?
4656 if (ToType->isRValueReferenceType() ||
4657 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4658 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4659 Result.UserDefined.After;
4660 SCS.ReferenceBinding = true;
4661 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4662 SCS.BindsToRvalue = true;
4663 SCS.BindsToFunctionLvalue = false;
4664 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4665 SCS.ObjCLifetimeConversionBinding = false;
4666 } else
4667 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4668 From, ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004669 return Result;
Sebastian Redldf888642011-12-03 14:54:30 +00004670 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004671
Larisse Voufo19d08672015-01-27 18:47:05 +00004672 // C++14 [over.ics.list]p7:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004673 // C++11 [over.ics.list]p6:
4674 // Otherwise, if the parameter type is not a class:
4675 if (!ToType->isRecordType()) {
Larisse Voufo19d08672015-01-27 18:47:05 +00004676 // - if the initializer list has one element that is not itself an
4677 // initializer list, the implicit conversion sequence is the one
4678 // required to convert the element to the parameter type.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004679 unsigned NumInits = From->getNumInits();
Richard Smith1bbaba82015-01-27 23:23:39 +00004680 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004681 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4682 SuppressUserConversions,
4683 InOverloadResolution,
4684 AllowObjCWritebackConversion);
4685 // - if the initializer list has no elements, the implicit conversion
4686 // sequence is the identity conversion.
4687 else if (NumInits == 0) {
4688 Result.setStandard();
4689 Result.Standard.setAsIdentityConversion();
John McCallb73bc9a2012-04-04 02:40:27 +00004690 Result.Standard.setFromType(ToType);
4691 Result.Standard.setAllToTypes(ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004692 }
4693 return Result;
4694 }
4695
Larisse Voufo19d08672015-01-27 18:47:05 +00004696 // C++14 [over.ics.list]p8:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004697 // C++11 [over.ics.list]p7:
4698 // In all cases other than those enumerated above, no conversion is possible
4699 return Result;
4700}
4701
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004702/// TryCopyInitialization - Try to copy-initialize a value of type
4703/// ToType from the expression From. Return the implicit conversion
4704/// sequence required to pass this argument, which may be a bad
4705/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00004706/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00004707/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004708static ImplicitConversionSequence
4709TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004710 bool SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004711 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004712 bool AllowObjCWritebackConversion,
4713 bool AllowExplicit) {
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004714 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4715 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4716 InOverloadResolution,AllowObjCWritebackConversion);
4717
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004718 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004719 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004720 /*FIXME:*/From->getLocStart(),
4721 SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004722 AllowExplicit);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004723
John McCall5c32be02010-08-24 20:38:10 +00004724 return TryImplicitConversion(S, From, ToType,
4725 SuppressUserConversions,
4726 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004727 InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00004728 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004729 AllowObjCWritebackConversion,
4730 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004731}
4732
Anna Zaks1b068122011-07-28 19:46:48 +00004733static bool TryCopyInitialization(const CanQualType FromQTy,
4734 const CanQualType ToQTy,
4735 Sema &S,
4736 SourceLocation Loc,
4737 ExprValueKind FromVK) {
4738 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4739 ImplicitConversionSequence ICS =
4740 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4741
4742 return !ICS.isBad();
4743}
4744
Douglas Gregor436424c2008-11-18 23:14:02 +00004745/// TryObjectArgumentInitialization - Try to initialize the object
4746/// parameter of the given member function (@c Method) from the
4747/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00004748static ImplicitConversionSequence
Richard Smith03c66d32013-01-26 02:07:32 +00004749TryObjectArgumentInitialization(Sema &S, QualType FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004750 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00004751 CXXMethodDecl *Method,
4752 CXXRecordDecl *ActingContext) {
4753 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00004754 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4755 // const volatile object.
4756 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4757 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00004758 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00004759
4760 // Set up the conversion sequence as a "bad" conversion, to allow us
4761 // to exit early.
4762 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00004763
4764 // We need to have an object of class type.
Douglas Gregor02824322011-01-26 19:30:28 +00004765 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004766 FromType = PT->getPointeeType();
4767
Douglas Gregor02824322011-01-26 19:30:28 +00004768 // When we had a pointer, it's implicitly dereferenced, so we
4769 // better have an lvalue.
4770 assert(FromClassification.isLValue());
4771 }
4772
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004773 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00004774
Douglas Gregor02824322011-01-26 19:30:28 +00004775 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004776 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00004777 // parameter is
4778 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004779 // - "lvalue reference to cv X" for functions declared without a
4780 // ref-qualifier or with the & ref-qualifier
4781 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00004782 // ref-qualifier
4783 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004784 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00004785 // cv-qualification on the member function declaration.
4786 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004787 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor02824322011-01-26 19:30:28 +00004788 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00004789 // (C++ [over.match.funcs]p5). We perform a simplified version of
4790 // reference binding here, that allows class rvalues to bind to
4791 // non-constant references.
4792
Douglas Gregor02824322011-01-26 19:30:28 +00004793 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00004794 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004795 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004796 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00004797 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00004798 ICS.setBad(BadConversionSequence::bad_qualifiers,
Richard Smith03c66d32013-01-26 02:07:32 +00004799 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004800 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004801 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004802
4803 // Check that we have either the same type or a derived type. It
4804 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00004805 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00004806 ImplicitConversionKind SecondKind;
4807 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4808 SecondKind = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00004809 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00004810 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00004811 else {
John McCall65eb8792010-02-25 01:37:24 +00004812 ICS.setBad(BadConversionSequence::unrelated_class,
4813 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004814 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004815 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004816
Douglas Gregor02824322011-01-26 19:30:28 +00004817 // Check the ref-qualifier.
4818 switch (Method->getRefQualifier()) {
4819 case RQ_None:
4820 // Do nothing; we don't care about lvalueness or rvalueness.
4821 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004822
Douglas Gregor02824322011-01-26 19:30:28 +00004823 case RQ_LValue:
4824 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4825 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004826 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004827 ImplicitParamType);
4828 return ICS;
4829 }
4830 break;
4831
4832 case RQ_RValue:
4833 if (!FromClassification.isRValue()) {
4834 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004835 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004836 ImplicitParamType);
4837 return ICS;
4838 }
4839 break;
4840 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004841
Douglas Gregor436424c2008-11-18 23:14:02 +00004842 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00004843 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00004844 ICS.Standard.setAsIdentityConversion();
4845 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00004846 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004847 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004848 ICS.Standard.ReferenceBinding = true;
4849 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004850 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004851 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004852 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4853 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4854 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00004855 return ICS;
4856}
4857
4858/// PerformObjectArgumentInitialization - Perform initialization of
4859/// the implicit object parameter for the given Method with the given
4860/// expression.
John Wiegley01296292011-04-08 18:41:53 +00004861ExprResult
4862Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004863 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00004864 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004865 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004866 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00004867 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004868 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004869
Douglas Gregor02824322011-01-26 19:30:28 +00004870 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004871 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004872 FromRecordType = PT->getPointeeType();
4873 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00004874 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004875 } else {
4876 FromRecordType = From->getType();
4877 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00004878 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004879 }
4880
John McCall6e9f8f62009-12-03 04:06:58 +00004881 // Note that we always use the true parent context when performing
4882 // the actual argument initialization.
Nico Weberb58e51c2014-11-19 05:21:39 +00004883 ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
4884 *this, From->getType(), FromClassification, Method, Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004885 if (ICS.isBad()) {
4886 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4887 Qualifiers FromQs = FromRecordType.getQualifiers();
4888 Qualifiers ToQs = DestType.getQualifiers();
4889 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4890 if (CVR) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004891 Diag(From->getLocStart(),
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004892 diag::err_member_function_call_bad_cvr)
4893 << Method->getDeclName() << FromRecordType << (CVR - 1)
4894 << From->getSourceRange();
4895 Diag(Method->getLocation(), diag::note_previous_decl)
4896 << Method->getDeclName();
John Wiegley01296292011-04-08 18:41:53 +00004897 return ExprError();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004898 }
4899 }
4900
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004901 return Diag(From->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004902 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004903 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004904 }
Mike Stump11289f42009-09-09 15:08:12 +00004905
John Wiegley01296292011-04-08 18:41:53 +00004906 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4907 ExprResult FromRes =
4908 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4909 if (FromRes.isInvalid())
4910 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004911 From = FromRes.get();
John Wiegley01296292011-04-08 18:41:53 +00004912 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004913
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004914 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley01296292011-04-08 18:41:53 +00004915 From = ImpCastExprToType(From, DestType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004916 From->getValueKind()).get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004917 return From;
Douglas Gregor436424c2008-11-18 23:14:02 +00004918}
4919
Douglas Gregor5fb53972009-01-14 15:45:31 +00004920/// TryContextuallyConvertToBool - Attempt to contextually convert the
4921/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00004922static ImplicitConversionSequence
4923TryContextuallyConvertToBool(Sema &S, Expr *From) {
John McCall5c32be02010-08-24 20:38:10 +00004924 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00004925 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00004926 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00004927 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004928 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004929 /*AllowObjCWritebackConversion=*/false,
4930 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004931}
4932
4933/// PerformContextuallyConvertToBool - Perform a contextual conversion
4934/// of the expression From to bool (C++0x [conv]p3).
John Wiegley01296292011-04-08 18:41:53 +00004935ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00004936 if (checkPlaceholderForOverload(*this, From))
4937 return ExprError();
4938
John McCall5c32be02010-08-24 20:38:10 +00004939 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00004940 if (!ICS.isBad())
4941 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004942
Fariborz Jahanian76197412009-11-18 18:26:29 +00004943 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004944 return Diag(From->getLocStart(),
John McCall0009fcc2011-04-26 20:42:42 +00004945 diag::err_typecheck_bool_condition)
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00004946 << From->getType() << From->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004947 return ExprError();
Douglas Gregor5fb53972009-01-14 15:45:31 +00004948}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004949
Richard Smithf8379a02012-01-18 23:55:52 +00004950/// Check that the specified conversion is permitted in a converted constant
4951/// expression, according to C++11 [expr.const]p3. Return true if the conversion
4952/// is acceptable.
4953static bool CheckConvertedConstantConversions(Sema &S,
4954 StandardConversionSequence &SCS) {
4955 // Since we know that the target type is an integral or unscoped enumeration
4956 // type, most conversion kinds are impossible. All possible First and Third
4957 // conversions are fine.
4958 switch (SCS.Second) {
4959 case ICK_Identity:
Richard Smith410cc892014-11-26 03:26:53 +00004960 case ICK_NoReturn_Adjustment:
Richard Smithf8379a02012-01-18 23:55:52 +00004961 case ICK_Integral_Promotion:
Richard Smith410cc892014-11-26 03:26:53 +00004962 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
Richard Smithf8379a02012-01-18 23:55:52 +00004963 return true;
4964
4965 case ICK_Boolean_Conversion:
Richard Smithca24ed42012-09-13 22:00:12 +00004966 // Conversion from an integral or unscoped enumeration type to bool is
Richard Smith410cc892014-11-26 03:26:53 +00004967 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
4968 // conversion, so we allow it in a converted constant expression.
4969 //
4970 // FIXME: Per core issue 1407, we should not allow this, but that breaks
4971 // a lot of popular code. We should at least add a warning for this
4972 // (non-conforming) extension.
Richard Smithca24ed42012-09-13 22:00:12 +00004973 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4974 SCS.getToType(2)->isBooleanType();
4975
Richard Smith410cc892014-11-26 03:26:53 +00004976 case ICK_Pointer_Conversion:
4977 case ICK_Pointer_Member:
4978 // C++1z: null pointer conversions and null member pointer conversions are
4979 // only permitted if the source type is std::nullptr_t.
4980 return SCS.getFromType()->isNullPtrType();
4981
4982 case ICK_Floating_Promotion:
4983 case ICK_Complex_Promotion:
4984 case ICK_Floating_Conversion:
4985 case ICK_Complex_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00004986 case ICK_Floating_Integral:
Richard Smith410cc892014-11-26 03:26:53 +00004987 case ICK_Compatible_Conversion:
4988 case ICK_Derived_To_Base:
4989 case ICK_Vector_Conversion:
4990 case ICK_Vector_Splat:
Richard Smithf8379a02012-01-18 23:55:52 +00004991 case ICK_Complex_Real:
Richard Smith410cc892014-11-26 03:26:53 +00004992 case ICK_Block_Pointer_Conversion:
4993 case ICK_TransparentUnionConversion:
4994 case ICK_Writeback_Conversion:
4995 case ICK_Zero_Event_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00004996 return false;
4997
4998 case ICK_Lvalue_To_Rvalue:
4999 case ICK_Array_To_Pointer:
5000 case ICK_Function_To_Pointer:
Richard Smith410cc892014-11-26 03:26:53 +00005001 llvm_unreachable("found a first conversion kind in Second");
5002
Richard Smithf8379a02012-01-18 23:55:52 +00005003 case ICK_Qualification:
Richard Smith410cc892014-11-26 03:26:53 +00005004 llvm_unreachable("found a third conversion kind in Second");
Richard Smithf8379a02012-01-18 23:55:52 +00005005
5006 case ICK_Num_Conversion_Kinds:
5007 break;
5008 }
5009
5010 llvm_unreachable("unknown conversion kind");
5011}
5012
5013/// CheckConvertedConstantExpression - Check that the expression From is a
5014/// converted constant expression of type T, perform the conversion and produce
5015/// the converted expression, per C++11 [expr.const]p3.
Richard Smith410cc892014-11-26 03:26:53 +00005016static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5017 QualType T, APValue &Value,
5018 Sema::CCEKind CCE,
5019 bool RequireInt) {
5020 assert(S.getLangOpts().CPlusPlus11 &&
5021 "converted constant expression outside C++11");
Richard Smithf8379a02012-01-18 23:55:52 +00005022
Richard Smith410cc892014-11-26 03:26:53 +00005023 if (checkPlaceholderForOverload(S, From))
Richard Smithf8379a02012-01-18 23:55:52 +00005024 return ExprError();
5025
Richard Smith410cc892014-11-26 03:26:53 +00005026 // C++1z [expr.const]p3:
5027 // A converted constant expression of type T is an expression,
5028 // implicitly converted to type T, where the converted
5029 // expression is a constant expression and the implicit conversion
5030 // sequence contains only [... list of conversions ...].
Richard Smithf8379a02012-01-18 23:55:52 +00005031 ImplicitConversionSequence ICS =
Richard Smith410cc892014-11-26 03:26:53 +00005032 TryCopyInitialization(S, From, T,
Richard Smithf8379a02012-01-18 23:55:52 +00005033 /*SuppressUserConversions=*/false,
Richard Smithf8379a02012-01-18 23:55:52 +00005034 /*InOverloadResolution=*/false,
Richard Smith410cc892014-11-26 03:26:53 +00005035 /*AllowObjcWritebackConversion=*/false,
5036 /*AllowExplicit=*/false);
Craig Topperc3ec1492014-05-26 06:22:03 +00005037 StandardConversionSequence *SCS = nullptr;
Richard Smithf8379a02012-01-18 23:55:52 +00005038 switch (ICS.getKind()) {
5039 case ImplicitConversionSequence::StandardConversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005040 SCS = &ICS.Standard;
5041 break;
5042 case ImplicitConversionSequence::UserDefinedConversion:
Richard Smith410cc892014-11-26 03:26:53 +00005043 // We are converting to a non-class type, so the Before sequence
5044 // must be trivial.
Richard Smithf8379a02012-01-18 23:55:52 +00005045 SCS = &ICS.UserDefined.After;
5046 break;
5047 case ImplicitConversionSequence::AmbiguousConversion:
5048 case ImplicitConversionSequence::BadConversion:
Richard Smith410cc892014-11-26 03:26:53 +00005049 if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5050 return S.Diag(From->getLocStart(),
5051 diag::err_typecheck_converted_constant_expression)
5052 << From->getType() << From->getSourceRange() << T;
Richard Smithf8379a02012-01-18 23:55:52 +00005053 return ExprError();
5054
5055 case ImplicitConversionSequence::EllipsisConversion:
5056 llvm_unreachable("ellipsis conversion in converted constant expression");
5057 }
5058
Richard Smith410cc892014-11-26 03:26:53 +00005059 // Check that we would only use permitted conversions.
5060 if (!CheckConvertedConstantConversions(S, *SCS)) {
5061 return S.Diag(From->getLocStart(),
5062 diag::err_typecheck_converted_constant_expression_disallowed)
5063 << From->getType() << From->getSourceRange() << T;
5064 }
5065 // [...] and where the reference binding (if any) binds directly.
5066 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5067 return S.Diag(From->getLocStart(),
5068 diag::err_typecheck_converted_constant_expression_indirect)
5069 << From->getType() << From->getSourceRange() << T;
5070 }
5071
5072 ExprResult Result =
5073 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
Richard Smithf8379a02012-01-18 23:55:52 +00005074 if (Result.isInvalid())
5075 return Result;
5076
5077 // Check for a narrowing implicit conversion.
5078 APValue PreNarrowingValue;
Richard Smith5614ca72012-03-23 23:55:39 +00005079 QualType PreNarrowingType;
Richard Smith410cc892014-11-26 03:26:53 +00005080 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
Richard Smith5614ca72012-03-23 23:55:39 +00005081 PreNarrowingType)) {
Richard Smithf8379a02012-01-18 23:55:52 +00005082 case NK_Variable_Narrowing:
5083 // Implicit conversion to a narrower type, and the value is not a constant
5084 // expression. We'll diagnose this in a moment.
5085 case NK_Not_Narrowing:
5086 break;
5087
5088 case NK_Constant_Narrowing:
Richard Smith410cc892014-11-26 03:26:53 +00005089 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00005090 << CCE << /*Constant*/1
Richard Smith410cc892014-11-26 03:26:53 +00005091 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
Richard Smithf8379a02012-01-18 23:55:52 +00005092 break;
5093
5094 case NK_Type_Narrowing:
Richard Smith410cc892014-11-26 03:26:53 +00005095 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00005096 << CCE << /*Constant*/0 << From->getType() << T;
5097 break;
5098 }
5099
5100 // Check the expression is a constant expression.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005101 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithf8379a02012-01-18 23:55:52 +00005102 Expr::EvalResult Eval;
5103 Eval.Diag = &Notes;
5104
Richard Smith410cc892014-11-26 03:26:53 +00005105 if ((T->isReferenceType()
5106 ? !Result.get()->EvaluateAsLValue(Eval, S.Context)
5107 : !Result.get()->EvaluateAsRValue(Eval, S.Context)) ||
5108 (RequireInt && !Eval.Val.isInt())) {
Richard Smithf8379a02012-01-18 23:55:52 +00005109 // The expression can't be folded, so we can't keep it at this position in
5110 // the AST.
5111 Result = ExprError();
Richard Smith911e1422012-01-30 22:27:01 +00005112 } else {
Richard Smith410cc892014-11-26 03:26:53 +00005113 Value = Eval.Val;
Richard Smith911e1422012-01-30 22:27:01 +00005114
5115 if (Notes.empty()) {
5116 // It's a constant expression.
5117 return Result;
5118 }
Richard Smithf8379a02012-01-18 23:55:52 +00005119 }
5120
5121 // It's not a constant expression. Produce an appropriate diagnostic.
5122 if (Notes.size() == 1 &&
5123 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
Richard Smith410cc892014-11-26 03:26:53 +00005124 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
Richard Smithf8379a02012-01-18 23:55:52 +00005125 else {
Richard Smith410cc892014-11-26 03:26:53 +00005126 S.Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smithf8379a02012-01-18 23:55:52 +00005127 << CCE << From->getSourceRange();
5128 for (unsigned I = 0; I < Notes.size(); ++I)
Richard Smith410cc892014-11-26 03:26:53 +00005129 S.Diag(Notes[I].first, Notes[I].second);
Richard Smithf8379a02012-01-18 23:55:52 +00005130 }
Richard Smith410cc892014-11-26 03:26:53 +00005131 return ExprError();
Richard Smithf8379a02012-01-18 23:55:52 +00005132}
5133
Richard Smith410cc892014-11-26 03:26:53 +00005134ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5135 APValue &Value, CCEKind CCE) {
5136 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5137}
5138
5139ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5140 llvm::APSInt &Value,
5141 CCEKind CCE) {
5142 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5143
5144 APValue V;
5145 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5146 if (!R.isInvalid())
5147 Value = V.getInt();
5148 return R;
5149}
5150
5151
John McCallfec112d2011-09-09 06:11:02 +00005152/// dropPointerConversions - If the given standard conversion sequence
5153/// involves any pointer conversions, remove them. This may change
5154/// the result type of the conversion sequence.
5155static void dropPointerConversion(StandardConversionSequence &SCS) {
5156 if (SCS.Second == ICK_Pointer_Conversion) {
5157 SCS.Second = ICK_Identity;
5158 SCS.Third = ICK_Identity;
5159 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5160 }
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005161}
John McCall5c32be02010-08-24 20:38:10 +00005162
John McCallfec112d2011-09-09 06:11:02 +00005163/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5164/// convert the expression From to an Objective-C pointer type.
5165static ImplicitConversionSequence
5166TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5167 // Do an implicit conversion to 'id'.
5168 QualType Ty = S.Context.getObjCIdType();
5169 ImplicitConversionSequence ICS
5170 = TryImplicitConversion(S, From, Ty,
5171 // FIXME: Are these flags correct?
5172 /*SuppressUserConversions=*/false,
5173 /*AllowExplicit=*/true,
5174 /*InOverloadResolution=*/false,
5175 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005176 /*AllowObjCWritebackConversion=*/false,
5177 /*AllowObjCConversionOnExplicit=*/true);
John McCallfec112d2011-09-09 06:11:02 +00005178
5179 // Strip off any final conversions to 'id'.
5180 switch (ICS.getKind()) {
5181 case ImplicitConversionSequence::BadConversion:
5182 case ImplicitConversionSequence::AmbiguousConversion:
5183 case ImplicitConversionSequence::EllipsisConversion:
5184 break;
5185
5186 case ImplicitConversionSequence::UserDefinedConversion:
5187 dropPointerConversion(ICS.UserDefined.After);
5188 break;
5189
5190 case ImplicitConversionSequence::StandardConversion:
5191 dropPointerConversion(ICS.Standard);
5192 break;
5193 }
5194
5195 return ICS;
5196}
5197
5198/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5199/// conversion of the expression From to an Objective-C pointer type.
5200ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00005201 if (checkPlaceholderForOverload(*this, From))
5202 return ExprError();
5203
John McCall8b07ec22010-05-15 11:32:37 +00005204 QualType Ty = Context.getObjCIdType();
John McCallfec112d2011-09-09 06:11:02 +00005205 ImplicitConversionSequence ICS =
5206 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005207 if (!ICS.isBad())
5208 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00005209 return ExprError();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005210}
Douglas Gregor5fb53972009-01-14 15:45:31 +00005211
Richard Smith8dd34252012-02-04 07:07:42 +00005212/// Determine whether the provided type is an integral type, or an enumeration
5213/// type of a permitted flavor.
Richard Smithccc11812013-05-21 19:05:48 +00005214bool Sema::ICEConvertDiagnoser::match(QualType T) {
5215 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5216 : T->isIntegralOrUnscopedEnumerationType();
Richard Smith8dd34252012-02-04 07:07:42 +00005217}
5218
Larisse Voufo236bec22013-06-10 06:50:24 +00005219static ExprResult
5220diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5221 Sema::ContextualImplicitConverter &Converter,
5222 QualType T, UnresolvedSetImpl &ViableConversions) {
5223
5224 if (Converter.Suppress)
5225 return ExprError();
5226
5227 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5228 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5229 CXXConversionDecl *Conv =
5230 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5231 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5232 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5233 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005234 return From;
Larisse Voufo236bec22013-06-10 06:50:24 +00005235}
5236
5237static bool
5238diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5239 Sema::ContextualImplicitConverter &Converter,
5240 QualType T, bool HadMultipleCandidates,
5241 UnresolvedSetImpl &ExplicitConversions) {
5242 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5243 DeclAccessPair Found = ExplicitConversions[0];
5244 CXXConversionDecl *Conversion =
5245 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5246
5247 // The user probably meant to invoke the given explicit
5248 // conversion; use it.
5249 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5250 std::string TypeStr;
5251 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5252
5253 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5254 << FixItHint::CreateInsertion(From->getLocStart(),
5255 "static_cast<" + TypeStr + ">(")
5256 << FixItHint::CreateInsertion(
Alp Tokerb6cc5922014-05-03 03:45:55 +00005257 SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
Larisse Voufo236bec22013-06-10 06:50:24 +00005258 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5259
5260 // If we aren't in a SFINAE context, build a call to the
5261 // explicit conversion function.
5262 if (SemaRef.isSFINAEContext())
5263 return true;
5264
Craig Topperc3ec1492014-05-26 06:22:03 +00005265 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
Larisse Voufo236bec22013-06-10 06:50:24 +00005266 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5267 HadMultipleCandidates);
5268 if (Result.isInvalid())
5269 return true;
5270 // Record usage of conversion in an implicit cast.
5271 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005272 CK_UserDefinedConversion, Result.get(),
5273 nullptr, Result.get()->getValueKind());
Larisse Voufo236bec22013-06-10 06:50:24 +00005274 }
5275 return false;
5276}
5277
5278static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5279 Sema::ContextualImplicitConverter &Converter,
5280 QualType T, bool HadMultipleCandidates,
5281 DeclAccessPair &Found) {
5282 CXXConversionDecl *Conversion =
5283 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00005284 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
Larisse Voufo236bec22013-06-10 06:50:24 +00005285
5286 QualType ToType = Conversion->getConversionType().getNonReferenceType();
5287 if (!Converter.SuppressConversion) {
5288 if (SemaRef.isSFINAEContext())
5289 return true;
5290
5291 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5292 << From->getSourceRange();
5293 }
5294
5295 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5296 HadMultipleCandidates);
5297 if (Result.isInvalid())
5298 return true;
5299 // Record usage of conversion in an implicit cast.
5300 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005301 CK_UserDefinedConversion, Result.get(),
5302 nullptr, Result.get()->getValueKind());
Larisse Voufo236bec22013-06-10 06:50:24 +00005303 return false;
5304}
5305
5306static ExprResult finishContextualImplicitConversion(
5307 Sema &SemaRef, SourceLocation Loc, Expr *From,
5308 Sema::ContextualImplicitConverter &Converter) {
5309 if (!Converter.match(From->getType()) && !Converter.Suppress)
5310 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5311 << From->getSourceRange();
5312
5313 return SemaRef.DefaultLvalueConversion(From);
5314}
5315
5316static void
5317collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5318 UnresolvedSetImpl &ViableConversions,
5319 OverloadCandidateSet &CandidateSet) {
5320 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5321 DeclAccessPair FoundDecl = ViableConversions[I];
5322 NamedDecl *D = FoundDecl.getDecl();
5323 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5324 if (isa<UsingShadowDecl>(D))
5325 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5326
5327 CXXConversionDecl *Conv;
5328 FunctionTemplateDecl *ConvTemplate;
5329 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5330 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5331 else
5332 Conv = cast<CXXConversionDecl>(D);
5333
5334 if (ConvTemplate)
5335 SemaRef.AddTemplateConversionCandidate(
Douglas Gregor4b60a152013-11-07 22:34:54 +00005336 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5337 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005338 else
5339 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005340 ToType, CandidateSet,
5341 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005342 }
5343}
5344
Richard Smithccc11812013-05-21 19:05:48 +00005345/// \brief Attempt to convert the given expression to a type which is accepted
5346/// by the given converter.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005347///
Richard Smithccc11812013-05-21 19:05:48 +00005348/// This routine will attempt to convert an expression of class type to a
5349/// type accepted by the specified converter. In C++11 and before, the class
5350/// must have a single non-explicit conversion function converting to a matching
5351/// type. In C++1y, there can be multiple such conversion functions, but only
5352/// one target type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005353///
Douglas Gregor4799d032010-06-30 00:20:43 +00005354/// \param Loc The source location of the construct that requires the
5355/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005356///
James Dennett18348b62012-06-22 08:52:37 +00005357/// \param From The expression we're converting from.
Douglas Gregor4799d032010-06-30 00:20:43 +00005358///
Richard Smithccc11812013-05-21 19:05:48 +00005359/// \param Converter Used to control and diagnose the conversion process.
Richard Smith8dd34252012-02-04 07:07:42 +00005360///
Douglas Gregor4799d032010-06-30 00:20:43 +00005361/// \returns The expression, converted to an integral or enumeration type if
5362/// successful.
Richard Smithccc11812013-05-21 19:05:48 +00005363ExprResult Sema::PerformContextualImplicitConversion(
5364 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005365 // We can't perform any more checking for type-dependent expressions.
5366 if (From->isTypeDependent())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005367 return From;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005368
Eli Friedman1da70392012-01-26 00:26:18 +00005369 // Process placeholders immediately.
5370 if (From->hasPlaceholderType()) {
5371 ExprResult result = CheckPlaceholderExpr(From);
Larisse Voufo236bec22013-06-10 06:50:24 +00005372 if (result.isInvalid())
5373 return result;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005374 From = result.get();
Eli Friedman1da70392012-01-26 00:26:18 +00005375 }
5376
Richard Smithccc11812013-05-21 19:05:48 +00005377 // If the expression already has a matching type, we're golden.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005378 QualType T = From->getType();
Richard Smithccc11812013-05-21 19:05:48 +00005379 if (Converter.match(T))
Eli Friedman1da70392012-01-26 00:26:18 +00005380 return DefaultLvalueConversion(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005381
5382 // FIXME: Check for missing '()' if T is a function type?
5383
Richard Smithccc11812013-05-21 19:05:48 +00005384 // We can only perform contextual implicit conversions on objects of class
5385 // type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005386 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikiebbafb8a2012-03-11 07:00:24 +00005387 if (!RecordTy || !getLangOpts().CPlusPlus) {
Richard Smithccc11812013-05-21 19:05:48 +00005388 if (!Converter.Suppress)
5389 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005390 return From;
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005391 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005392
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005393 // We must have a complete class type.
Douglas Gregora6c5abb2012-05-04 16:48:41 +00005394 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
Richard Smithccc11812013-05-21 19:05:48 +00005395 ContextualImplicitConverter &Converter;
Douglas Gregore2b37442012-05-04 22:38:52 +00005396 Expr *From;
Richard Smithccc11812013-05-21 19:05:48 +00005397
5398 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5399 : TypeDiagnoser(Converter.Suppress), Converter(Converter), From(From) {}
5400
Craig Toppere14c0f82014-03-12 04:55:44 +00005401 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00005402 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005403 }
Richard Smithccc11812013-05-21 19:05:48 +00005404 } IncompleteDiagnoser(Converter, From);
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005405
5406 if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005407 return From;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005408
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005409 // Look for a conversion to an integral or enumeration type.
Larisse Voufo236bec22013-06-10 06:50:24 +00005410 UnresolvedSet<4>
5411 ViableConversions; // These are *potentially* viable in C++1y.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005412 UnresolvedSet<4> ExplicitConversions;
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005413 const auto &Conversions =
Larisse Voufo236bec22013-06-10 06:50:24 +00005414 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005415
Larisse Voufo236bec22013-06-10 06:50:24 +00005416 bool HadMultipleCandidates =
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005417 (std::distance(Conversions.begin(), Conversions.end()) > 1);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005418
Larisse Voufo236bec22013-06-10 06:50:24 +00005419 // To check that there is only one target type, in C++1y:
5420 QualType ToType;
5421 bool HasUniqueTargetType = true;
5422
5423 // Collect explicit or viable (potentially in C++1y) conversions.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005424 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005425 NamedDecl *D = (*I)->getUnderlyingDecl();
5426 CXXConversionDecl *Conversion;
5427 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5428 if (ConvTemplate) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005429 if (getLangOpts().CPlusPlus14)
Larisse Voufo236bec22013-06-10 06:50:24 +00005430 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5431 else
5432 continue; // C++11 does not consider conversion operator templates(?).
5433 } else
5434 Conversion = cast<CXXConversionDecl>(D);
5435
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005436 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
Larisse Voufo236bec22013-06-10 06:50:24 +00005437 "Conversion operator templates are considered potentially "
5438 "viable in C++1y");
5439
5440 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5441 if (Converter.match(CurToType) || ConvTemplate) {
5442
5443 if (Conversion->isExplicit()) {
5444 // FIXME: For C++1y, do we need this restriction?
5445 // cf. diagnoseNoViableConversion()
5446 if (!ConvTemplate)
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005447 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
Larisse Voufo236bec22013-06-10 06:50:24 +00005448 } else {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005449 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005450 if (ToType.isNull())
5451 ToType = CurToType.getUnqualifiedType();
5452 else if (HasUniqueTargetType &&
5453 (CurToType.getUnqualifiedType() != ToType))
5454 HasUniqueTargetType = false;
5455 }
5456 ViableConversions.addDecl(I.getDecl(), I.getAccess());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005457 }
Richard Smith8dd34252012-02-04 07:07:42 +00005458 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005459 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005460
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005461 if (getLangOpts().CPlusPlus14) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005462 // C++1y [conv]p6:
5463 // ... An expression e of class type E appearing in such a context
5464 // is said to be contextually implicitly converted to a specified
5465 // type T and is well-formed if and only if e can be implicitly
5466 // converted to a type T that is determined as follows: E is searched
Larisse Voufo67170bd2013-06-10 08:25:58 +00005467 // for conversion functions whose return type is cv T or reference to
5468 // cv T such that T is allowed by the context. There shall be
Larisse Voufo236bec22013-06-10 06:50:24 +00005469 // exactly one such T.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005470
Larisse Voufo236bec22013-06-10 06:50:24 +00005471 // If no unique T is found:
5472 if (ToType.isNull()) {
5473 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5474 HadMultipleCandidates,
5475 ExplicitConversions))
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005476 return ExprError();
Larisse Voufo236bec22013-06-10 06:50:24 +00005477 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005478 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005479
Larisse Voufo236bec22013-06-10 06:50:24 +00005480 // If more than one unique Ts are found:
5481 if (!HasUniqueTargetType)
5482 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5483 ViableConversions);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005484
Larisse Voufo236bec22013-06-10 06:50:24 +00005485 // If one unique T is found:
5486 // First, build a candidate set from the previously recorded
5487 // potentially viable conversions.
Richard Smith100b24a2014-04-17 01:52:14 +00005488 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Larisse Voufo236bec22013-06-10 06:50:24 +00005489 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5490 CandidateSet);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005491
Larisse Voufo236bec22013-06-10 06:50:24 +00005492 // Then, perform overload resolution over the candidate set.
5493 OverloadCandidateSet::iterator Best;
5494 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5495 case OR_Success: {
5496 // Apply this conversion.
5497 DeclAccessPair Found =
5498 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5499 if (recordConversion(*this, Loc, From, Converter, T,
5500 HadMultipleCandidates, Found))
5501 return ExprError();
5502 break;
5503 }
5504 case OR_Ambiguous:
5505 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5506 ViableConversions);
5507 case OR_No_Viable_Function:
5508 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5509 HadMultipleCandidates,
5510 ExplicitConversions))
5511 return ExprError();
5512 // fall through 'OR_Deleted' case.
5513 case OR_Deleted:
5514 // We'll complain below about a non-integral condition type.
5515 break;
5516 }
5517 } else {
5518 switch (ViableConversions.size()) {
5519 case 0: {
5520 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5521 HadMultipleCandidates,
5522 ExplicitConversions))
Douglas Gregor4799d032010-06-30 00:20:43 +00005523 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005524
Larisse Voufo236bec22013-06-10 06:50:24 +00005525 // We'll complain below about a non-integral condition type.
5526 break;
Douglas Gregor4799d032010-06-30 00:20:43 +00005527 }
Larisse Voufo236bec22013-06-10 06:50:24 +00005528 case 1: {
5529 // Apply this conversion.
5530 DeclAccessPair Found = ViableConversions[0];
5531 if (recordConversion(*this, Loc, From, Converter, T,
5532 HadMultipleCandidates, Found))
5533 return ExprError();
5534 break;
5535 }
5536 default:
5537 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5538 ViableConversions);
5539 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005540 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005541
Larisse Voufo236bec22013-06-10 06:50:24 +00005542 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005543}
5544
Richard Smith100b24a2014-04-17 01:52:14 +00005545/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5546/// an acceptable non-member overloaded operator for a call whose
5547/// arguments have types T1 (and, if non-empty, T2). This routine
5548/// implements the check in C++ [over.match.oper]p3b2 concerning
5549/// enumeration types.
5550static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5551 FunctionDecl *Fn,
5552 ArrayRef<Expr *> Args) {
5553 QualType T1 = Args[0]->getType();
5554 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5555
5556 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5557 return true;
5558
5559 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5560 return true;
5561
5562 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5563 if (Proto->getNumParams() < 1)
5564 return false;
5565
5566 if (T1->isEnumeralType()) {
5567 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5568 if (Context.hasSameUnqualifiedType(T1, ArgType))
5569 return true;
5570 }
5571
5572 if (Proto->getNumParams() < 2)
5573 return false;
5574
5575 if (!T2.isNull() && T2->isEnumeralType()) {
5576 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5577 if (Context.hasSameUnqualifiedType(T2, ArgType))
5578 return true;
5579 }
5580
5581 return false;
5582}
5583
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005584/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00005585/// candidate functions, using the given function call arguments. If
5586/// @p SuppressUserConversions, then don't allow user-defined
5587/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00005588///
James Dennett2a4d13c2012-06-15 07:13:21 +00005589/// \param PartialOverloading true if we are performing "partial" overloading
Douglas Gregorcabea402009-09-22 15:41:20 +00005590/// based on an incomplete set of function arguments. This feature is used by
5591/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00005592void
5593Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00005594 DeclAccessPair FoundDecl,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005595 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005596 OverloadCandidateSet &CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00005597 bool SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005598 bool PartialOverloading,
5599 bool AllowExplicit) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005600 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00005601 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005602 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00005603 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005604 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00005605
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005606 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005607 if (!isa<CXXConstructorDecl>(Method)) {
5608 // If we get here, it's because we're calling a member function
5609 // that is named without a member access expression (e.g.,
5610 // "this->f") that was either written explicitly or created
5611 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00005612 // function, e.g., X::f(). We use an empty type for the implied
5613 // object argument (C++ [over.call.func]p3), and the acting context
5614 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00005615 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005616 QualType(), Expr::Classification::makeSimpleLValue(),
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005617 Args, CandidateSet, SuppressUserConversions,
5618 PartialOverloading);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005619 return;
5620 }
5621 // We treat a constructor like a non-member function, since its object
5622 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005623 }
5624
Douglas Gregorff7028a2009-11-13 23:59:09 +00005625 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005626 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00005627
Richard Smith100b24a2014-04-17 01:52:14 +00005628 // C++ [over.match.oper]p3:
5629 // if no operand has a class type, only those non-member functions in the
5630 // lookup set that have a first parameter of type T1 or "reference to
5631 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5632 // is a right operand) a second parameter of type T2 or "reference to
5633 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
5634 // candidate functions.
5635 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5636 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5637 return;
5638
Richard Smith8b86f2d2013-11-04 01:48:18 +00005639 // C++11 [class.copy]p11: [DR1402]
5640 // A defaulted move constructor that is defined as deleted is ignored by
5641 // overload resolution.
5642 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5643 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5644 Constructor->isMoveConstructor())
5645 return;
5646
Douglas Gregor27381f32009-11-23 12:27:39 +00005647 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005648 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005649
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005650 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005651 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCalla0296f72010-03-19 07:35:19 +00005652 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005653 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005654 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005655 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005656 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005657 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005658
John McCall578a1f82014-12-14 01:46:53 +00005659 if (Constructor) {
5660 // C++ [class.copy]p3:
5661 // A member function template is never instantiated to perform the copy
5662 // of a class object to an object of its class type.
5663 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
5664 if (Args.size() == 1 &&
5665 Constructor->isSpecializationCopyingObject() &&
5666 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5667 IsDerivedFrom(Args[0]->getType(), ClassType))) {
5668 Candidate.Viable = false;
5669 Candidate.FailureKind = ovl_fail_illegal_constructor;
5670 return;
5671 }
5672 }
5673
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005674 unsigned NumParams = Proto->getNumParams();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005675
5676 // (C++ 13.3.2p2): A candidate function having fewer than m
5677 // parameters is viable only if it has an ellipsis in its parameter
5678 // list (8.3.5).
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005679 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
Douglas Gregor2a920012009-09-23 14:56:09 +00005680 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005681 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005682 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005683 return;
5684 }
5685
5686 // (C++ 13.3.2p2): A candidate function having more than m parameters
5687 // is viable only if the (m+1)st parameter has a default argument
5688 // (8.3.6). For the purposes of overload resolution, the
5689 // parameter list is truncated on the right, so that there are
5690 // exactly m parameters.
5691 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005692 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005693 // Not enough arguments.
5694 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005695 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005696 return;
5697 }
5698
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005699 // (CUDA B.1): Check for invalid calls between targets.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005700 if (getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005701 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
Eli Bendersky9a220fc2014-09-29 20:38:29 +00005702 // Skip the check for callers that are implicit members, because in this
5703 // case we may not yet know what the member's target is; the target is
5704 // inferred for the member automatically, based on the bases and fields of
5705 // the class.
5706 if (!Caller->isImplicit() && CheckCUDATarget(Caller, Function)) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005707 Candidate.Viable = false;
5708 Candidate.FailureKind = ovl_fail_bad_target;
5709 return;
5710 }
5711
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005712 // Determine the implicit conversion sequences for each of the
5713 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005714 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005715 if (ArgIdx < NumParams) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005716 // (C++ 13.3.2p3): for F to be a viable function, there shall
5717 // exist for each argument an implicit conversion sequence
5718 // (13.3.3.1) that converts that argument to the corresponding
5719 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00005720 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005721 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005722 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005723 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00005724 /*InOverloadResolution=*/true,
5725 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005726 getLangOpts().ObjCAutoRefCount,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005727 AllowExplicit);
John McCall0d1da222010-01-12 00:44:57 +00005728 if (Candidate.Conversions[ArgIdx].isBad()) {
5729 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005730 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005731 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00005732 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005733 } else {
5734 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5735 // argument for which there is no corresponding parameter is
5736 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005737 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005738 }
5739 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005740
5741 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
5742 Candidate.Viable = false;
5743 Candidate.FailureKind = ovl_fail_enable_if;
5744 Candidate.DeductionFailure.Data = FailedAttr;
5745 return;
5746 }
5747}
5748
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005749ObjCMethodDecl *Sema::SelectBestMethod(Selector Sel, MultiExprArg Args,
Fariborz Jahanian0ded4242014-08-13 21:24:14 +00005750 bool IsInstance) {
5751 SmallVector<ObjCMethodDecl*, 4> Methods;
5752 if (!CollectMultipleMethodsInGlobalPool(Sel, Methods, IsInstance))
5753 return nullptr;
5754
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005755 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5756 bool Match = true;
5757 ObjCMethodDecl *Method = Methods[b];
5758 unsigned NumNamedArgs = Sel.getNumArgs();
5759 // Method might have more arguments than selector indicates. This is due
5760 // to addition of c-style arguments in method.
5761 if (Method->param_size() > NumNamedArgs)
5762 NumNamedArgs = Method->param_size();
5763 if (Args.size() < NumNamedArgs)
5764 continue;
5765
5766 for (unsigned i = 0; i < NumNamedArgs; i++) {
5767 // We can't do any type-checking on a type-dependent argument.
5768 if (Args[i]->isTypeDependent()) {
5769 Match = false;
5770 break;
5771 }
5772
5773 ParmVarDecl *param = Method->parameters()[i];
5774 Expr *argExpr = Args[i];
5775 assert(argExpr && "SelectBestMethod(): missing expression");
5776
5777 // Strip the unbridged-cast placeholder expression off unless it's
5778 // a consumed argument.
5779 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
5780 !param->hasAttr<CFConsumedAttr>())
5781 argExpr = stripARCUnbridgedCast(argExpr);
5782
5783 // If the parameter is __unknown_anytype, move on to the next method.
5784 if (param->getType() == Context.UnknownAnyTy) {
5785 Match = false;
5786 break;
5787 }
5788
5789 ImplicitConversionSequence ConversionState
5790 = TryCopyInitialization(*this, argExpr, param->getType(),
5791 /*SuppressUserConversions*/false,
5792 /*InOverloadResolution=*/true,
5793 /*AllowObjCWritebackConversion=*/
5794 getLangOpts().ObjCAutoRefCount,
5795 /*AllowExplicit*/false);
5796 if (ConversionState.isBad()) {
5797 Match = false;
5798 break;
5799 }
5800 }
5801 // Promote additional arguments to variadic methods.
5802 if (Match && Method->isVariadic()) {
5803 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
5804 if (Args[i]->isTypeDependent()) {
5805 Match = false;
5806 break;
5807 }
5808 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
5809 nullptr);
5810 if (Arg.isInvalid()) {
5811 Match = false;
5812 break;
5813 }
5814 }
Fariborz Jahanian180d76b2014-08-27 16:38:47 +00005815 } else {
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005816 // Check for extra arguments to non-variadic methods.
5817 if (Args.size() != NumNamedArgs)
5818 Match = false;
Fariborz Jahanian180d76b2014-08-27 16:38:47 +00005819 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
5820 // Special case when selectors have no argument. In this case, select
5821 // one with the most general result type of 'id'.
5822 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5823 QualType ReturnT = Methods[b]->getReturnType();
5824 if (ReturnT->isObjCIdType())
5825 return Methods[b];
5826 }
5827 }
5828 }
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005829
5830 if (Match)
5831 return Method;
5832 }
5833 return nullptr;
5834}
5835
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005836static bool IsNotEnableIfAttr(Attr *A) { return !isa<EnableIfAttr>(A); }
5837
5838EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
5839 bool MissingImplicitThis) {
5840 // FIXME: specific_attr_iterator<EnableIfAttr> iterates in reverse order, but
5841 // we need to find the first failing one.
5842 if (!Function->hasAttrs())
Craig Topperc3ec1492014-05-26 06:22:03 +00005843 return nullptr;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005844 AttrVec Attrs = Function->getAttrs();
5845 AttrVec::iterator E = std::remove_if(Attrs.begin(), Attrs.end(),
5846 IsNotEnableIfAttr);
5847 if (Attrs.begin() == E)
Craig Topperc3ec1492014-05-26 06:22:03 +00005848 return nullptr;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005849 std::reverse(Attrs.begin(), E);
5850
5851 SFINAETrap Trap(*this);
5852
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005853 SmallVector<Expr *, 16> ConvertedArgs;
5854 bool InitializationFailed = false;
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00005855 bool ContainsValueDependentExpr = false;
Nick Lewyckye283c552015-08-25 22:33:16 +00005856
5857 // Convert the arguments.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005858 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
5859 if (i == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) &&
Nick Lewyckyb8336b72014-02-28 05:26:13 +00005860 !cast<CXXMethodDecl>(Function)->isStatic() &&
5861 !isa<CXXConstructorDecl>(Function)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005862 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
5863 ExprResult R =
Craig Topperc3ec1492014-05-26 06:22:03 +00005864 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005865 Method, Method);
5866 if (R.isInvalid()) {
5867 InitializationFailed = true;
5868 break;
5869 }
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00005870 ContainsValueDependentExpr |= R.get()->isValueDependent();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005871 ConvertedArgs.push_back(R.get());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005872 } else {
5873 ExprResult R =
5874 PerformCopyInitialization(InitializedEntity::InitializeParameter(
5875 Context,
5876 Function->getParamDecl(i)),
5877 SourceLocation(),
5878 Args[i]);
5879 if (R.isInvalid()) {
5880 InitializationFailed = true;
5881 break;
5882 }
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00005883 ContainsValueDependentExpr |= R.get()->isValueDependent();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005884 ConvertedArgs.push_back(R.get());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005885 }
5886 }
5887
5888 if (InitializationFailed || Trap.hasErrorOccurred())
5889 return cast<EnableIfAttr>(Attrs[0]);
5890
Nick Lewyckye283c552015-08-25 22:33:16 +00005891 // Push default arguments if needed.
5892 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
5893 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
5894 ParmVarDecl *P = Function->getParamDecl(i);
5895 ExprResult R = PerformCopyInitialization(
5896 InitializedEntity::InitializeParameter(Context,
5897 Function->getParamDecl(i)),
5898 SourceLocation(),
5899 P->hasUninstantiatedDefaultArg() ? P->getUninstantiatedDefaultArg()
5900 : P->getDefaultArg());
5901 if (R.isInvalid()) {
5902 InitializationFailed = true;
5903 break;
5904 }
5905 ContainsValueDependentExpr |= R.get()->isValueDependent();
5906 ConvertedArgs.push_back(R.get());
5907 }
5908
5909 if (InitializationFailed || Trap.hasErrorOccurred())
5910 return cast<EnableIfAttr>(Attrs[0]);
5911 }
5912
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005913 for (AttrVec::iterator I = Attrs.begin(); I != E; ++I) {
5914 APValue Result;
5915 EnableIfAttr *EIA = cast<EnableIfAttr>(*I);
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00005916 if (EIA->getCond()->isValueDependent()) {
5917 // Don't even try now, we'll examine it after instantiation.
5918 continue;
5919 }
5920
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005921 if (!EIA->getCond()->EvaluateWithSubstitution(
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00005922 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) {
5923 if (!ContainsValueDependentExpr)
5924 return EIA;
5925 } else if (!Result.isInt() || !Result.getInt().getBoolValue()) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005926 return EIA;
5927 }
5928 }
Craig Topperc3ec1492014-05-26 06:22:03 +00005929 return nullptr;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005930}
5931
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005932/// \brief Add all of the function declarations in the given function set to
Nick Lewyckyed4265c2013-09-22 10:06:01 +00005933/// the overload candidate set.
John McCall4c4c1df2010-01-26 03:27:55 +00005934void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005935 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005936 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005937 TemplateArgumentListInfo *ExplicitTemplateArgs,
Richard Smithbcc22fc2012-03-09 08:00:36 +00005938 bool SuppressUserConversions,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005939 bool PartialOverloading) {
John McCall4c4c1df2010-01-26 03:27:55 +00005940 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00005941 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5942 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005943 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00005944 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00005945 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00005946 Args[0]->getType(), Args[0]->Classify(Context),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005947 Args.slice(1), CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005948 SuppressUserConversions, PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005949 else
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005950 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005951 SuppressUserConversions, PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005952 } else {
John McCalla0296f72010-03-19 07:35:19 +00005953 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005954 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5955 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00005956 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00005957 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Richard Smithbcc22fc2012-03-09 08:00:36 +00005958 ExplicitTemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005959 Args[0]->getType(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005960 Args[0]->Classify(Context), Args.slice(1),
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005961 CandidateSet, SuppressUserConversions,
5962 PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005963 else
John McCalla0296f72010-03-19 07:35:19 +00005964 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smithbcc22fc2012-03-09 08:00:36 +00005965 ExplicitTemplateArgs, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005966 CandidateSet, SuppressUserConversions,
5967 PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005968 }
Douglas Gregor15448f82009-06-27 21:05:07 +00005969 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005970}
5971
John McCallf0f1cf02009-11-17 07:50:12 +00005972/// AddMethodCandidate - Adds a named decl (which is some kind of
5973/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00005974void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005975 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005976 Expr::Classification ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00005977 ArrayRef<Expr *> Args,
John McCallf0f1cf02009-11-17 07:50:12 +00005978 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005979 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00005980 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00005981 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00005982
5983 if (isa<UsingShadowDecl>(Decl))
5984 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005985
John McCallf0f1cf02009-11-17 07:50:12 +00005986 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5987 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5988 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00005989 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
Craig Topperc3ec1492014-05-26 06:22:03 +00005990 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005991 ObjectType, ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00005992 Args, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005993 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00005994 } else {
John McCalla0296f72010-03-19 07:35:19 +00005995 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005996 ObjectType, ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00005997 Args,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005998 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00005999 }
6000}
6001
Douglas Gregor436424c2008-11-18 23:14:02 +00006002/// AddMethodCandidate - Adds the given C++ member function to the set
6003/// of candidate functions, using the given function call arguments
6004/// and the object argument (@c Object). For example, in a call
6005/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6006/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6007/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00006008/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00006009void
John McCalla0296f72010-03-19 07:35:19 +00006010Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00006011 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006012 Expr::Classification ObjectClassification,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006013 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006014 OverloadCandidateSet &CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006015 bool SuppressUserConversions,
6016 bool PartialOverloading) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006017 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00006018 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00006019 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00006020 assert(!isa<CXXConstructorDecl>(Method) &&
6021 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00006022
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006023 if (!CandidateSet.isNewCandidate(Method))
6024 return;
6025
Richard Smith8b86f2d2013-11-04 01:48:18 +00006026 // C++11 [class.copy]p23: [DR1402]
6027 // A defaulted move assignment operator that is defined as deleted is
6028 // ignored by overload resolution.
6029 if (Method->isDefaulted() && Method->isDeleted() &&
6030 Method->isMoveAssignmentOperator())
6031 return;
6032
Douglas Gregor27381f32009-11-23 12:27:39 +00006033 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006034 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006035
Douglas Gregor436424c2008-11-18 23:14:02 +00006036 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006037 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00006038 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00006039 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006040 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006041 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006042 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor436424c2008-11-18 23:14:02 +00006043
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006044 unsigned NumParams = Proto->getNumParams();
Douglas Gregor436424c2008-11-18 23:14:02 +00006045
6046 // (C++ 13.3.2p2): A candidate function having fewer than m
6047 // parameters is viable only if it has an ellipsis in its parameter
6048 // list (8.3.5).
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006049 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6050 !Proto->isVariadic()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006051 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006052 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00006053 return;
6054 }
6055
6056 // (C++ 13.3.2p2): A candidate function having more than m parameters
6057 // is viable only if the (m+1)st parameter has a default argument
6058 // (8.3.6). For the purposes of overload resolution, the
6059 // parameter list is truncated on the right, so that there are
6060 // exactly m parameters.
6061 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006062 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006063 // Not enough arguments.
6064 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006065 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00006066 return;
6067 }
6068
6069 Candidate.Viable = true;
Douglas Gregor436424c2008-11-18 23:14:02 +00006070
John McCall6e9f8f62009-12-03 04:06:58 +00006071 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006072 // The implicit object argument is ignored.
6073 Candidate.IgnoreObjectArgument = true;
6074 else {
6075 // Determine the implicit conversion sequence for the object
6076 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00006077 Candidate.Conversions[0]
Douglas Gregor02824322011-01-26 19:30:28 +00006078 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
6079 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00006080 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006081 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006082 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006083 return;
6084 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006085 }
6086
Eli Bendersky291a57e2014-09-25 23:59:08 +00006087 // (CUDA B.1): Check for invalid calls between targets.
6088 if (getLangOpts().CUDA)
6089 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6090 if (CheckCUDATarget(Caller, Method)) {
6091 Candidate.Viable = false;
6092 Candidate.FailureKind = ovl_fail_bad_target;
6093 return;
6094 }
6095
Douglas Gregor436424c2008-11-18 23:14:02 +00006096 // Determine the implicit conversion sequences for each of the
6097 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006098 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006099 if (ArgIdx < NumParams) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006100 // (C++ 13.3.2p3): for F to be a viable function, there shall
6101 // exist for each argument an implicit conversion sequence
6102 // (13.3.3.1) that converts that argument to the corresponding
6103 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00006104 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00006105 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006106 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006107 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00006108 /*InOverloadResolution=*/true,
6109 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006110 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00006111 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006112 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006113 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006114 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00006115 }
6116 } else {
6117 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6118 // argument for which there is no corresponding parameter is
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006119 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006120 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00006121 }
6122 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006123
6124 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6125 Candidate.Viable = false;
6126 Candidate.FailureKind = ovl_fail_enable_if;
6127 Candidate.DeductionFailure.Data = FailedAttr;
6128 return;
6129 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006130}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006131
Douglas Gregor97628d62009-08-21 00:16:32 +00006132/// \brief Add a C++ member function template as a candidate to the candidate
6133/// set, using template argument deduction to produce an appropriate member
6134/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00006135void
Douglas Gregor97628d62009-08-21 00:16:32 +00006136Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00006137 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006138 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006139 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006140 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006141 Expr::Classification ObjectClassification,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006142 ArrayRef<Expr *> Args,
Douglas Gregor97628d62009-08-21 00:16:32 +00006143 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006144 bool SuppressUserConversions,
6145 bool PartialOverloading) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006146 if (!CandidateSet.isNewCandidate(MethodTmpl))
6147 return;
6148
Douglas Gregor97628d62009-08-21 00:16:32 +00006149 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00006150 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00006151 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00006152 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00006153 // candidate functions in the usual way.113) A given name can refer to one
6154 // or more function templates and also to a set of overloaded non-template
6155 // functions. In such a case, the candidate functions generated from each
6156 // function template are combined with the set of non-template candidate
6157 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00006158 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006159 FunctionDecl *Specialization = nullptr;
Douglas Gregor97628d62009-08-21 00:16:32 +00006160 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006161 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006162 Specialization, Info, PartialOverloading)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006163 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006164 Candidate.FoundDecl = FoundDecl;
6165 Candidate.Function = MethodTmpl->getTemplatedDecl();
6166 Candidate.Viable = false;
6167 Candidate.FailureKind = ovl_fail_bad_deduction;
6168 Candidate.IsSurrogate = false;
6169 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006170 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006171 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006172 Info);
6173 return;
6174 }
Mike Stump11289f42009-09-09 15:08:12 +00006175
Douglas Gregor97628d62009-08-21 00:16:32 +00006176 // Add the function template specialization produced by template argument
6177 // deduction as a candidate.
6178 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00006179 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00006180 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00006181 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006182 ActingContext, ObjectType, ObjectClassification, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006183 CandidateSet, SuppressUserConversions, PartialOverloading);
Douglas Gregor97628d62009-08-21 00:16:32 +00006184}
6185
Douglas Gregor05155d82009-08-21 23:19:43 +00006186/// \brief Add a C++ function template specialization as a candidate
6187/// in the candidate set, using template argument deduction to produce
6188/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00006189void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006190Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00006191 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006192 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006193 ArrayRef<Expr *> Args,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006194 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006195 bool SuppressUserConversions,
6196 bool PartialOverloading) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006197 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6198 return;
6199
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006200 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00006201 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006202 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00006203 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006204 // candidate functions in the usual way.113) A given name can refer to one
6205 // or more function templates and also to a set of overloaded non-template
6206 // functions. In such a case, the candidate functions generated from each
6207 // function template are combined with the set of non-template candidate
6208 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00006209 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006210 FunctionDecl *Specialization = nullptr;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006211 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006212 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006213 Specialization, Info, PartialOverloading)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006214 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCalla0296f72010-03-19 07:35:19 +00006215 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00006216 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6217 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006218 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00006219 Candidate.IsSurrogate = false;
6220 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006221 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006222 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006223 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006224 return;
6225 }
Mike Stump11289f42009-09-09 15:08:12 +00006226
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006227 // Add the function template specialization produced by template argument
6228 // deduction as a candidate.
6229 assert(Specialization && "Missing function template specialization?");
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006230 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006231 SuppressUserConversions, PartialOverloading);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006232}
Mike Stump11289f42009-09-09 15:08:12 +00006233
Douglas Gregor4b60a152013-11-07 22:34:54 +00006234/// Determine whether this is an allowable conversion from the result
6235/// of an explicit conversion operator to the expected type, per C++
6236/// [over.match.conv]p1 and [over.match.ref]p1.
6237///
6238/// \param ConvType The return type of the conversion function.
6239///
6240/// \param ToType The type we are converting to.
6241///
6242/// \param AllowObjCPointerConversion Allow a conversion from one
6243/// Objective-C pointer to another.
6244///
6245/// \returns true if the conversion is allowable, false otherwise.
6246static bool isAllowableExplicitConversion(Sema &S,
6247 QualType ConvType, QualType ToType,
6248 bool AllowObjCPointerConversion) {
6249 QualType ToNonRefType = ToType.getNonReferenceType();
6250
6251 // Easy case: the types are the same.
6252 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6253 return true;
6254
6255 // Allow qualification conversions.
6256 bool ObjCLifetimeConversion;
6257 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6258 ObjCLifetimeConversion))
6259 return true;
6260
6261 // If we're not allowed to consider Objective-C pointer conversions,
6262 // we're done.
6263 if (!AllowObjCPointerConversion)
6264 return false;
6265
6266 // Is this an Objective-C pointer conversion?
6267 bool IncompatibleObjC = false;
6268 QualType ConvertedType;
6269 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6270 IncompatibleObjC);
6271}
6272
Douglas Gregora1f013e2008-11-07 22:36:19 +00006273/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00006274/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00006275/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00006276/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00006277/// (which may or may not be the same type as the type that the
6278/// conversion function produces).
6279void
6280Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006281 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006282 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00006283 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006284 OverloadCandidateSet& CandidateSet,
6285 bool AllowObjCConversionOnExplicit) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006286 assert(!Conversion->getDescribedFunctionTemplate() &&
6287 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00006288 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006289 if (!CandidateSet.isNewCandidate(Conversion))
6290 return;
6291
Richard Smith2a7d4812013-05-04 07:00:32 +00006292 // If the conversion function has an undeduced return type, trigger its
6293 // deduction now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006294 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00006295 if (DeduceReturnType(Conversion, From->getExprLoc()))
6296 return;
6297 ConvType = Conversion->getConversionType().getNonReferenceType();
6298 }
6299
Richard Smith089c3162013-09-21 21:55:46 +00006300 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6301 // operator is only a candidate if its return type is the target type or
6302 // can be converted to the target type with a qualification conversion.
Douglas Gregor4b60a152013-11-07 22:34:54 +00006303 if (Conversion->isExplicit() &&
6304 !isAllowableExplicitConversion(*this, ConvType, ToType,
6305 AllowObjCConversionOnExplicit))
Richard Smith089c3162013-09-21 21:55:46 +00006306 return;
6307
Douglas Gregor27381f32009-11-23 12:27:39 +00006308 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006309 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006310
Douglas Gregora1f013e2008-11-07 22:36:19 +00006311 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006312 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCalla0296f72010-03-19 07:35:19 +00006313 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006314 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006315 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006316 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006317 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00006318 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00006319 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00006320 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006321 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006322
Douglas Gregor6affc782010-08-19 15:37:02 +00006323 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006324 // For conversion functions, the function is considered to be a member of
6325 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00006326 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006327 //
6328 // Determine the implicit conversion sequence for the implicit
6329 // object parameter.
6330 QualType ImplicitParamType = From->getType();
6331 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6332 ImplicitParamType = FromPtrType->getPointeeType();
6333 CXXRecordDecl *ConversionContext
6334 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006335
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006336 Candidate.Conversions[0]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006337 = TryObjectArgumentInitialization(*this, From->getType(),
6338 From->Classify(Context),
Douglas Gregor02824322011-01-26 19:30:28 +00006339 Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006340
John McCall0d1da222010-01-12 00:44:57 +00006341 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006342 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006343 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006344 return;
6345 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006346
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006347 // We won't go through a user-defined type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006348 // derived to base as such conversions are given Conversion Rank. They only
6349 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6350 QualType FromCanon
6351 = Context.getCanonicalType(From->getType().getUnqualifiedType());
6352 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
6353 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
6354 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006355 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006356 return;
6357 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006358
Douglas Gregora1f013e2008-11-07 22:36:19 +00006359 // To determine what the conversion from the result of calling the
6360 // conversion function to the type we're eventually trying to
6361 // convert to (ToType), we need to synthesize a call to the
6362 // conversion function and attempt copy initialization from it. This
6363 // makes sure that we get the right semantics with respect to
6364 // lvalues/rvalues and the type. Fortunately, we can allocate this
6365 // call on the stack and we don't need its arguments to be
6366 // well-formed.
John McCall113bee02012-03-10 09:33:50 +00006367 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00006368 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00006369 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6370 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00006371 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00006372 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00006373
Richard Smith48d24642011-07-13 22:53:21 +00006374 QualType ConversionType = Conversion->getConversionType();
6375 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor72ebdab2010-11-13 19:36:57 +00006376 Candidate.Viable = false;
6377 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6378 return;
6379 }
6380
Richard Smith48d24642011-07-13 22:53:21 +00006381 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCall7decc9e2010-11-18 06:31:45 +00006382
Mike Stump11289f42009-09-09 15:08:12 +00006383 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00006384 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6385 // allocator).
Richard Smith48d24642011-07-13 22:53:21 +00006386 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00006387 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00006388 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00006389 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006390 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00006391 /*SuppressUserConversions=*/true,
John McCall31168b02011-06-15 23:02:42 +00006392 /*InOverloadResolution=*/false,
6393 /*AllowObjCWritebackConversion=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00006394
John McCall0d1da222010-01-12 00:44:57 +00006395 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006396 case ImplicitConversionSequence::StandardConversion:
6397 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006398
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006399 // C++ [over.ics.user]p3:
6400 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006401 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006402 // shall have exact match rank.
6403 if (Conversion->getPrimaryTemplate() &&
6404 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6405 Candidate.Viable = false;
6406 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006407 return;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006408 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006409
Douglas Gregorcba72b12011-01-21 05:18:22 +00006410 // C++0x [dcl.init.ref]p5:
6411 // In the second case, if the reference is an rvalue reference and
6412 // the second standard conversion sequence of the user-defined
6413 // conversion sequence includes an lvalue-to-rvalue conversion, the
6414 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006415 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00006416 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6417 Candidate.Viable = false;
6418 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006419 return;
Douglas Gregorcba72b12011-01-21 05:18:22 +00006420 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00006421 break;
6422
6423 case ImplicitConversionSequence::BadConversion:
6424 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006425 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006426 return;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006427
6428 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006429 llvm_unreachable(
Douglas Gregora1f013e2008-11-07 22:36:19 +00006430 "Can only end up with a standard conversion sequence or failure");
6431 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006432
Craig Topper5fc8fc22014-08-27 06:28:36 +00006433 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006434 Candidate.Viable = false;
6435 Candidate.FailureKind = ovl_fail_enable_if;
6436 Candidate.DeductionFailure.Data = FailedAttr;
6437 return;
6438 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00006439}
6440
Douglas Gregor05155d82009-08-21 23:19:43 +00006441/// \brief Adds a conversion function template specialization
6442/// candidate to the overload set, using template argument deduction
6443/// to deduce the template arguments of the conversion function
6444/// template from the type that we are converting to (C++
6445/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00006446void
Douglas Gregor05155d82009-08-21 23:19:43 +00006447Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00006448 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006449 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00006450 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006451 OverloadCandidateSet &CandidateSet,
6452 bool AllowObjCConversionOnExplicit) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006453 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
6454 "Only conversion function templates permitted here");
6455
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006456 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6457 return;
6458
Craig Toppere6706e42012-09-19 02:26:47 +00006459 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006460 CXXConversionDecl *Specialization = nullptr;
Douglas Gregor05155d82009-08-21 23:19:43 +00006461 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00006462 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00006463 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006464 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006465 Candidate.FoundDecl = FoundDecl;
6466 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6467 Candidate.Viable = false;
6468 Candidate.FailureKind = ovl_fail_bad_deduction;
6469 Candidate.IsSurrogate = false;
6470 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006471 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006472 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006473 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00006474 return;
6475 }
Mike Stump11289f42009-09-09 15:08:12 +00006476
Douglas Gregor05155d82009-08-21 23:19:43 +00006477 // Add the conversion function template specialization produced by
6478 // template argument deduction as a candidate.
6479 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00006480 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006481 CandidateSet, AllowObjCConversionOnExplicit);
Douglas Gregor05155d82009-08-21 23:19:43 +00006482}
6483
Douglas Gregorab7897a2008-11-19 22:57:39 +00006484/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
6485/// converts the given @c Object to a function pointer via the
6486/// conversion function @c Conversion, and then attempts to call it
6487/// with the given arguments (C++ [over.call.object]p2-4). Proto is
6488/// the type of function that we'll eventually be calling.
6489void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006490 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006491 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006492 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00006493 Expr *Object,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006494 ArrayRef<Expr *> Args,
Douglas Gregorab7897a2008-11-19 22:57:39 +00006495 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006496 if (!CandidateSet.isNewCandidate(Conversion))
6497 return;
6498
Douglas Gregor27381f32009-11-23 12:27:39 +00006499 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006500 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006501
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006502 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00006503 Candidate.FoundDecl = FoundDecl;
Craig Topperc3ec1492014-05-26 06:22:03 +00006504 Candidate.Function = nullptr;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006505 Candidate.Surrogate = Conversion;
6506 Candidate.Viable = true;
6507 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006508 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006509 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006510
6511 // Determine the implicit conversion sequence for the implicit
6512 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00006513 ImplicitConversionSequence ObjectInit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006514 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00006515 Object->Classify(Context),
6516 Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00006517 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006518 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006519 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00006520 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006521 return;
6522 }
6523
6524 // The first conversion is actually a user-defined conversion whose
6525 // first conversion is ObjectInit's standard conversion (which is
6526 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00006527 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006528 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00006529 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006530 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006531 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00006532 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump11289f42009-09-09 15:08:12 +00006533 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00006534 = Candidate.Conversions[0].UserDefined.Before;
6535 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
6536
Mike Stump11289f42009-09-09 15:08:12 +00006537 // Find the
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006538 unsigned NumParams = Proto->getNumParams();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006539
6540 // (C++ 13.3.2p2): A candidate function having fewer than m
6541 // parameters is viable only if it has an ellipsis in its parameter
6542 // list (8.3.5).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006543 if (Args.size() > NumParams && !Proto->isVariadic()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006544 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006545 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006546 return;
6547 }
6548
6549 // Function types don't have any default arguments, so just check if
6550 // we have enough arguments.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006551 if (Args.size() < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006552 // Not enough arguments.
6553 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006554 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006555 return;
6556 }
6557
6558 // Determine the implicit conversion sequences for each of the
6559 // arguments.
Richard Smithe54c3072013-05-05 15:51:06 +00006560 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006561 if (ArgIdx < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006562 // (C++ 13.3.2p3): for F to be a viable function, there shall
6563 // exist for each argument an implicit conversion sequence
6564 // (13.3.3.1) that converts that argument to the corresponding
6565 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00006566 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00006567 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006568 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00006569 /*SuppressUserConversions=*/false,
John McCall31168b02011-06-15 23:02:42 +00006570 /*InOverloadResolution=*/false,
6571 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006572 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00006573 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006574 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006575 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006576 return;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006577 }
6578 } else {
6579 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6580 // argument for which there is no corresponding parameter is
6581 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006582 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006583 }
6584 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006585
Craig Topper5fc8fc22014-08-27 06:28:36 +00006586 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006587 Candidate.Viable = false;
6588 Candidate.FailureKind = ovl_fail_enable_if;
6589 Candidate.DeductionFailure.Data = FailedAttr;
6590 return;
6591 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00006592}
6593
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006594/// \brief Add overload candidates for overloaded operators that are
6595/// member functions.
6596///
6597/// Add the overloaded operator candidates that are member functions
6598/// for the operator Op that was used in an operator expression such
6599/// as "x Op y". , Args/NumArgs provides the operator arguments, and
6600/// CandidateSet will store the added overload candidates. (C++
6601/// [over.match.oper]).
6602void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
6603 SourceLocation OpLoc,
Richard Smithe54c3072013-05-05 15:51:06 +00006604 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006605 OverloadCandidateSet& CandidateSet,
6606 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006607 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6608
6609 // C++ [over.match.oper]p3:
6610 // For a unary operator @ with an operand of a type whose
6611 // cv-unqualified version is T1, and for a binary operator @ with
6612 // a left operand of a type whose cv-unqualified version is T1 and
6613 // a right operand of a type whose cv-unqualified version is T2,
6614 // three sets of candidate functions, designated member
6615 // candidates, non-member candidates and built-in candidates, are
6616 // constructed as follows:
6617 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00006618
Richard Smith0feaf0c2013-04-20 12:41:22 +00006619 // -- If T1 is a complete class type or a class currently being
6620 // defined, the set of member candidates is the result of the
6621 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
6622 // the set of member candidates is empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006623 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Richard Smith0feaf0c2013-04-20 12:41:22 +00006624 // Complete the type if it can be completed.
6625 RequireCompleteType(OpLoc, T1, 0);
6626 // If the type is neither complete nor being defined, bail out now.
6627 if (!T1Rec->getDecl()->getDefinition())
Douglas Gregor6a1f9652009-08-27 23:35:55 +00006628 return;
Mike Stump11289f42009-09-09 15:08:12 +00006629
John McCall27b18f82009-11-17 02:14:36 +00006630 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6631 LookupQualifiedName(Operators, T1Rec->getDecl());
6632 Operators.suppressDiagnostics();
6633
Mike Stump11289f42009-09-09 15:08:12 +00006634 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00006635 OperEnd = Operators.end();
6636 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00006637 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00006638 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
Rafael Espindola51629df2013-04-29 19:29:25 +00006639 Args[0]->Classify(Context),
Richard Smithe54c3072013-05-05 15:51:06 +00006640 Args.slice(1),
Douglas Gregor02824322011-01-26 19:30:28 +00006641 CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00006642 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00006643 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006644}
6645
Douglas Gregora11693b2008-11-12 17:17:38 +00006646/// AddBuiltinCandidate - Add a candidate for a built-in
6647/// operator. ResultTy and ParamTys are the result and parameter types
6648/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00006649/// arguments being passed to the candidate. IsAssignmentOperator
6650/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00006651/// operator. NumContextualBoolArguments is the number of arguments
6652/// (at the beginning of the argument list) that will be contextually
6653/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00006654void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Richard Smithe54c3072013-05-05 15:51:06 +00006655 ArrayRef<Expr *> Args,
Douglas Gregorc5e61072009-01-13 00:52:54 +00006656 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00006657 bool IsAssignmentOperator,
6658 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00006659 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006660 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006661
Douglas Gregora11693b2008-11-12 17:17:38 +00006662 // Add this candidate
Richard Smithe54c3072013-05-05 15:51:06 +00006663 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
Craig Topperc3ec1492014-05-26 06:22:03 +00006664 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
6665 Candidate.Function = nullptr;
Douglas Gregor1d248c52008-12-12 02:00:36 +00006666 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006667 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00006668 Candidate.BuiltinTypes.ResultTy = ResultTy;
Richard Smithe54c3072013-05-05 15:51:06 +00006669 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Douglas Gregora11693b2008-11-12 17:17:38 +00006670 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6671
6672 // Determine the implicit conversion sequences for each of the
6673 // arguments.
6674 Candidate.Viable = true;
Richard Smithe54c3072013-05-05 15:51:06 +00006675 Candidate.ExplicitCallArguments = Args.size();
6676 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00006677 // C++ [over.match.oper]p4:
6678 // For the built-in assignment operators, conversions of the
6679 // left operand are restricted as follows:
6680 // -- no temporaries are introduced to hold the left operand, and
6681 // -- no user-defined conversions are applied to the left
6682 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00006683 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00006684 //
6685 // We block these conversions by turning off user-defined
6686 // conversions, since that is the only way that initialization of
6687 // a reference to a non-class type can occur from something that
6688 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00006689 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00006690 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00006691 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00006692 Candidate.Conversions[ArgIdx]
6693 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006694 } else {
Mike Stump11289f42009-09-09 15:08:12 +00006695 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006696 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00006697 ArgIdx == 0 && IsAssignmentOperator,
John McCall31168b02011-06-15 23:02:42 +00006698 /*InOverloadResolution=*/false,
6699 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006700 getLangOpts().ObjCAutoRefCount);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006701 }
John McCall0d1da222010-01-12 00:44:57 +00006702 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006703 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006704 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00006705 break;
6706 }
Douglas Gregora11693b2008-11-12 17:17:38 +00006707 }
6708}
6709
Craig Toppercd7b0332013-07-01 06:29:40 +00006710namespace {
6711
Douglas Gregora11693b2008-11-12 17:17:38 +00006712/// BuiltinCandidateTypeSet - A set of types that will be used for the
6713/// candidate operator functions for built-in operators (C++
6714/// [over.built]). The types are separated into pointer types and
6715/// enumeration types.
6716class BuiltinCandidateTypeSet {
6717 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006718 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00006719
6720 /// PointerTypes - The set of pointer types that will be used in the
6721 /// built-in candidates.
6722 TypeSet PointerTypes;
6723
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006724 /// MemberPointerTypes - The set of member pointer types that will be
6725 /// used in the built-in candidates.
6726 TypeSet MemberPointerTypes;
6727
Douglas Gregora11693b2008-11-12 17:17:38 +00006728 /// EnumerationTypes - The set of enumeration types that will be
6729 /// used in the built-in candidates.
6730 TypeSet EnumerationTypes;
6731
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006732 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006733 /// candidates.
6734 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00006735
6736 /// \brief A flag indicating non-record types are viable candidates
6737 bool HasNonRecordTypes;
6738
6739 /// \brief A flag indicating whether either arithmetic or enumeration types
6740 /// were present in the candidate set.
6741 bool HasArithmeticOrEnumeralTypes;
6742
Douglas Gregor80af3132011-05-21 23:15:46 +00006743 /// \brief A flag indicating whether the nullptr type was present in the
6744 /// candidate set.
6745 bool HasNullPtrType;
6746
Douglas Gregor8a2e6012009-08-24 15:23:48 +00006747 /// Sema - The semantic analysis instance where we are building the
6748 /// candidate type set.
6749 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00006750
Douglas Gregora11693b2008-11-12 17:17:38 +00006751 /// Context - The AST context in which we will build the type sets.
6752 ASTContext &Context;
6753
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006754 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6755 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006756 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00006757
6758public:
6759 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006760 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00006761
Mike Stump11289f42009-09-09 15:08:12 +00006762 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00006763 : HasNonRecordTypes(false),
6764 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor80af3132011-05-21 23:15:46 +00006765 HasNullPtrType(false),
Chandler Carruth00a38332010-12-13 01:44:01 +00006766 SemaRef(SemaRef),
6767 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00006768
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006769 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006770 SourceLocation Loc,
6771 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006772 bool AllowExplicitConversions,
6773 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00006774
6775 /// pointer_begin - First pointer type found;
6776 iterator pointer_begin() { return PointerTypes.begin(); }
6777
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006778 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006779 iterator pointer_end() { return PointerTypes.end(); }
6780
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006781 /// member_pointer_begin - First member pointer type found;
6782 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6783
6784 /// member_pointer_end - Past the last member pointer type found;
6785 iterator member_pointer_end() { return MemberPointerTypes.end(); }
6786
Douglas Gregora11693b2008-11-12 17:17:38 +00006787 /// enumeration_begin - First enumeration type found;
6788 iterator enumeration_begin() { return EnumerationTypes.begin(); }
6789
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006790 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006791 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006792
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006793 iterator vector_begin() { return VectorTypes.begin(); }
6794 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00006795
6796 bool hasNonRecordTypes() { return HasNonRecordTypes; }
6797 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor80af3132011-05-21 23:15:46 +00006798 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregora11693b2008-11-12 17:17:38 +00006799};
6800
Craig Toppercd7b0332013-07-01 06:29:40 +00006801} // end anonymous namespace
6802
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006803/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00006804/// the set of pointer types along with any more-qualified variants of
6805/// that type. For example, if @p Ty is "int const *", this routine
6806/// will add "int const *", "int const volatile *", "int const
6807/// restrict *", and "int const volatile restrict *" to the set of
6808/// pointer types. Returns true if the add of @p Ty itself succeeded,
6809/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006810///
6811/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006812bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006813BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6814 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00006815
Douglas Gregora11693b2008-11-12 17:17:38 +00006816 // Insert this type.
David Blaikie82e95a32014-11-19 07:49:47 +00006817 if (!PointerTypes.insert(Ty).second)
Douglas Gregora11693b2008-11-12 17:17:38 +00006818 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006819
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006820 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00006821 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006822 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006823 if (!PointerTy) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00006824 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6825 PointeeTy = PTy->getPointeeType();
6826 buildObjCPtr = true;
6827 } else {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006828 PointeeTy = PointerTy->getPointeeType();
Douglas Gregor5bee2582012-06-04 00:15:09 +00006829 }
6830
Sebastian Redl4990a632009-11-18 20:39:26 +00006831 // Don't add qualified variants of arrays. For one, they're not allowed
6832 // (the qualifier would sink to the element type), and for another, the
6833 // only overload situation where it matters is subscript or pointer +- int,
6834 // and those shouldn't have qualifier variants anyway.
6835 if (PointeeTy->isArrayType())
6836 return true;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006837
John McCall8ccfcb52009-09-24 19:53:00 +00006838 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006839 bool hasVolatile = VisibleQuals.hasVolatile();
6840 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006841
John McCall8ccfcb52009-09-24 19:53:00 +00006842 // Iterate through all strict supersets of BaseCVR.
6843 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6844 if ((CVR | BaseCVR) != CVR) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006845 // Skip over volatile if no volatile found anywhere in the types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006846 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006847
6848 // Skip over restrict if no restrict found anywhere in the types, or if
6849 // the type cannot be restrict-qualified.
6850 if ((CVR & Qualifiers::Restrict) &&
6851 (!hasRestrict ||
6852 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6853 continue;
6854
6855 // Build qualified pointee type.
John McCall8ccfcb52009-09-24 19:53:00 +00006856 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Douglas Gregor5bee2582012-06-04 00:15:09 +00006857
6858 // Build qualified pointer type.
6859 QualType QPointerTy;
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006860 if (!buildObjCPtr)
Douglas Gregor5bee2582012-06-04 00:15:09 +00006861 QPointerTy = Context.getPointerType(QPointeeTy);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006862 else
Douglas Gregor5bee2582012-06-04 00:15:09 +00006863 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6864
6865 // Insert qualified pointer type.
6866 PointerTypes.insert(QPointerTy);
Douglas Gregora11693b2008-11-12 17:17:38 +00006867 }
6868
6869 return true;
6870}
6871
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006872/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6873/// to the set of pointer types along with any more-qualified variants of
6874/// that type. For example, if @p Ty is "int const *", this routine
6875/// will add "int const *", "int const volatile *", "int const
6876/// restrict *", and "int const volatile restrict *" to the set of
6877/// pointer types. Returns true if the add of @p Ty itself succeeded,
6878/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006879///
6880/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006881bool
6882BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6883 QualType Ty) {
6884 // Insert this type.
David Blaikie82e95a32014-11-19 07:49:47 +00006885 if (!MemberPointerTypes.insert(Ty).second)
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006886 return false;
6887
John McCall8ccfcb52009-09-24 19:53:00 +00006888 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6889 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006890
John McCall8ccfcb52009-09-24 19:53:00 +00006891 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00006892 // Don't add qualified variants of arrays. For one, they're not allowed
6893 // (the qualifier would sink to the element type), and for another, the
6894 // only overload situation where it matters is subscript or pointer +- int,
6895 // and those shouldn't have qualifier variants anyway.
6896 if (PointeeTy->isArrayType())
6897 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00006898 const Type *ClassTy = PointerTy->getClass();
6899
6900 // Iterate through all strict supersets of the pointee type's CVR
6901 // qualifiers.
6902 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6903 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6904 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006905
John McCall8ccfcb52009-09-24 19:53:00 +00006906 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00006907 MemberPointerTypes.insert(
6908 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006909 }
6910
6911 return true;
6912}
6913
Douglas Gregora11693b2008-11-12 17:17:38 +00006914/// AddTypesConvertedFrom - Add each of the types to which the type @p
6915/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006916/// primarily interested in pointer types and enumeration types. We also
6917/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00006918/// AllowUserConversions is true if we should look at the conversion
6919/// functions of a class type, and AllowExplicitConversions if we
6920/// should also include the explicit conversion functions of a class
6921/// type.
Mike Stump11289f42009-09-09 15:08:12 +00006922void
Douglas Gregor5fb53972009-01-14 15:45:31 +00006923BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006924 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00006925 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006926 bool AllowExplicitConversions,
6927 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006928 // Only deal with canonical types.
6929 Ty = Context.getCanonicalType(Ty);
6930
6931 // Look through reference types; they aren't part of the type of an
6932 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006933 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00006934 Ty = RefTy->getPointeeType();
6935
John McCall33ddac02011-01-19 10:06:00 +00006936 // If we're dealing with an array type, decay to the pointer.
6937 if (Ty->isArrayType())
6938 Ty = SemaRef.Context.getArrayDecayedType(Ty);
6939
6940 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006941 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00006942
Chandler Carruth00a38332010-12-13 01:44:01 +00006943 // Flag if we ever add a non-record type.
6944 const RecordType *TyRec = Ty->getAs<RecordType>();
6945 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6946
Chandler Carruth00a38332010-12-13 01:44:01 +00006947 // Flag if we encounter an arithmetic type.
6948 HasArithmeticOrEnumeralTypes =
6949 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6950
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006951 if (Ty->isObjCIdType() || Ty->isObjCClassType())
6952 PointerTypes.insert(Ty);
6953 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006954 // Insert our type, and its more-qualified variants, into the set
6955 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006956 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00006957 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006958 } else if (Ty->isMemberPointerType()) {
6959 // Member pointers are far easier, since the pointee can't be converted.
6960 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6961 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00006962 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006963 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00006964 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006965 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006966 // We treat vector types as arithmetic types in many contexts as an
6967 // extension.
6968 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006969 VectorTypes.insert(Ty);
Douglas Gregor80af3132011-05-21 23:15:46 +00006970 } else if (Ty->isNullPtrType()) {
6971 HasNullPtrType = true;
Chandler Carruth00a38332010-12-13 01:44:01 +00006972 } else if (AllowUserConversions && TyRec) {
6973 // No conversion functions in incomplete types.
6974 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6975 return;
Mike Stump11289f42009-09-09 15:08:12 +00006976
Chandler Carruth00a38332010-12-13 01:44:01 +00006977 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00006978 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006979 if (isa<UsingShadowDecl>(D))
6980 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00006981
Chandler Carruth00a38332010-12-13 01:44:01 +00006982 // Skip conversion function templates; they don't tell us anything
6983 // about which builtin types we can convert to.
6984 if (isa<FunctionTemplateDecl>(D))
6985 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00006986
Chandler Carruth00a38332010-12-13 01:44:01 +00006987 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6988 if (AllowExplicitConversions || !Conv->isExplicit()) {
6989 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6990 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00006991 }
6992 }
6993 }
6994}
6995
Douglas Gregor84605ae2009-08-24 13:43:27 +00006996/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6997/// the volatile- and non-volatile-qualified assignment operators for the
6998/// given type to the candidate set.
6999static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7000 QualType T,
Richard Smithe54c3072013-05-05 15:51:06 +00007001 ArrayRef<Expr *> Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00007002 OverloadCandidateSet &CandidateSet) {
7003 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00007004
Douglas Gregor84605ae2009-08-24 13:43:27 +00007005 // T& operator=(T&, T)
7006 ParamTypes[0] = S.Context.getLValueReferenceType(T);
7007 ParamTypes[1] = T;
Richard Smithe54c3072013-05-05 15:51:06 +00007008 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor84605ae2009-08-24 13:43:27 +00007009 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00007010
Douglas Gregor84605ae2009-08-24 13:43:27 +00007011 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7012 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00007013 ParamTypes[0]
7014 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00007015 ParamTypes[1] = T;
Richard Smithe54c3072013-05-05 15:51:06 +00007016 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00007017 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00007018 }
7019}
Mike Stump11289f42009-09-09 15:08:12 +00007020
Sebastian Redl1054fae2009-10-25 17:03:50 +00007021/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7022/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007023static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7024 Qualifiers VRQuals;
7025 const RecordType *TyRec;
7026 if (const MemberPointerType *RHSMPType =
7027 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00007028 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007029 else
7030 TyRec = ArgExpr->getType()->getAs<RecordType>();
7031 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007032 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007033 VRQuals.addVolatile();
7034 VRQuals.addRestrict();
7035 return VRQuals;
7036 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007037
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007038 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00007039 if (!ClassDecl->hasDefinition())
7040 return VRQuals;
7041
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00007042 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
John McCallda4458e2010-03-31 01:36:47 +00007043 if (isa<UsingShadowDecl>(D))
7044 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7045 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007046 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7047 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7048 CanTy = ResTypeRef->getPointeeType();
7049 // Need to go down the pointer/mempointer chain and add qualifiers
7050 // as see them.
7051 bool done = false;
7052 while (!done) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00007053 if (CanTy.isRestrictQualified())
7054 VRQuals.addRestrict();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007055 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7056 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007057 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007058 CanTy->getAs<MemberPointerType>())
7059 CanTy = ResTypeMPtr->getPointeeType();
7060 else
7061 done = true;
7062 if (CanTy.isVolatileQualified())
7063 VRQuals.addVolatile();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007064 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7065 return VRQuals;
7066 }
7067 }
7068 }
7069 return VRQuals;
7070}
John McCall52872982010-11-13 05:51:15 +00007071
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007072namespace {
John McCall52872982010-11-13 05:51:15 +00007073
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007074/// \brief Helper class to manage the addition of builtin operator overload
7075/// candidates. It provides shared state and utility methods used throughout
7076/// the process, as well as a helper method to add each group of builtin
7077/// operator overloads from the standard to a candidate set.
7078class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007079 // Common instance state available to all overload candidate addition methods.
7080 Sema &S;
Richard Smithe54c3072013-05-05 15:51:06 +00007081 ArrayRef<Expr *> Args;
Chandler Carruthc6586e52010-12-12 10:35:00 +00007082 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00007083 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007084 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruthc6586e52010-12-12 10:35:00 +00007085 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007086
Chandler Carruthc6586e52010-12-12 10:35:00 +00007087 // Define some constants used to index and iterate over the arithemetic types
7088 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00007089 // The "promoted arithmetic types" are the arithmetic
7090 // types are that preserved by promotion (C++ [over.built]p2).
John McCall52872982010-11-13 05:51:15 +00007091 static const unsigned FirstIntegralType = 3;
Richard Smith521ecc12012-06-10 08:00:26 +00007092 static const unsigned LastIntegralType = 20;
John McCall52872982010-11-13 05:51:15 +00007093 static const unsigned FirstPromotedIntegralType = 3,
Richard Smith521ecc12012-06-10 08:00:26 +00007094 LastPromotedIntegralType = 11;
John McCall52872982010-11-13 05:51:15 +00007095 static const unsigned FirstPromotedArithmeticType = 0,
Richard Smith521ecc12012-06-10 08:00:26 +00007096 LastPromotedArithmeticType = 11;
7097 static const unsigned NumArithmeticTypes = 20;
John McCall52872982010-11-13 05:51:15 +00007098
Chandler Carruthc6586e52010-12-12 10:35:00 +00007099 /// \brief Get the canonical type for a given arithmetic type index.
7100 CanQualType getArithmeticType(unsigned index) {
7101 assert(index < NumArithmeticTypes);
7102 static CanQualType ASTContext::* const
7103 ArithmeticTypes[NumArithmeticTypes] = {
7104 // Start of promoted types.
7105 &ASTContext::FloatTy,
7106 &ASTContext::DoubleTy,
7107 &ASTContext::LongDoubleTy,
John McCall52872982010-11-13 05:51:15 +00007108
Chandler Carruthc6586e52010-12-12 10:35:00 +00007109 // Start of integral types.
7110 &ASTContext::IntTy,
7111 &ASTContext::LongTy,
7112 &ASTContext::LongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00007113 &ASTContext::Int128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00007114 &ASTContext::UnsignedIntTy,
7115 &ASTContext::UnsignedLongTy,
7116 &ASTContext::UnsignedLongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00007117 &ASTContext::UnsignedInt128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00007118 // End of promoted types.
7119
7120 &ASTContext::BoolTy,
7121 &ASTContext::CharTy,
7122 &ASTContext::WCharTy,
7123 &ASTContext::Char16Ty,
7124 &ASTContext::Char32Ty,
7125 &ASTContext::SignedCharTy,
7126 &ASTContext::ShortTy,
7127 &ASTContext::UnsignedCharTy,
7128 &ASTContext::UnsignedShortTy,
7129 // End of integral types.
Richard Smith521ecc12012-06-10 08:00:26 +00007130 // FIXME: What about complex? What about half?
Chandler Carruthc6586e52010-12-12 10:35:00 +00007131 };
7132 return S.Context.*ArithmeticTypes[index];
7133 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007134
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007135 /// \brief Gets the canonical type resulting from the usual arithemetic
7136 /// converions for the given arithmetic types.
7137 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
7138 // Accelerator table for performing the usual arithmetic conversions.
7139 // The rules are basically:
7140 // - if either is floating-point, use the wider floating-point
7141 // - if same signedness, use the higher rank
7142 // - if same size, use unsigned of the higher rank
7143 // - use the larger type
7144 // These rules, together with the axiom that higher ranks are
7145 // never smaller, are sufficient to precompute all of these results
7146 // *except* when dealing with signed types of higher rank.
7147 // (we could precompute SLL x UI for all known platforms, but it's
7148 // better not to make any assumptions).
Richard Smith521ecc12012-06-10 08:00:26 +00007149 // We assume that int128 has a higher rank than long long on all platforms.
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007150 enum PromotedType {
Richard Smith521ecc12012-06-10 08:00:26 +00007151 Dep=-1,
7152 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007153 };
Nuno Lopes9af6b032012-04-21 14:45:25 +00007154 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007155 [LastPromotedArithmeticType] = {
Richard Smith521ecc12012-06-10 08:00:26 +00007156/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
7157/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
7158/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
7159/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
7160/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
7161/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
7162/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
7163/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
7164/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
7165/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
7166/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007167 };
7168
7169 assert(L < LastPromotedArithmeticType);
7170 assert(R < LastPromotedArithmeticType);
7171 int Idx = ConversionsTable[L][R];
7172
7173 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007174 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007175
7176 // Slow path: we need to compare widths.
7177 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007178 CanQualType LT = getArithmeticType(L),
7179 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007180 unsigned LW = S.Context.getIntWidth(LT),
7181 RW = S.Context.getIntWidth(RT);
7182
7183 // If they're different widths, use the signed type.
7184 if (LW > RW) return LT;
7185 else if (LW < RW) return RT;
7186
7187 // Otherwise, use the unsigned type of the signed type's rank.
7188 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
7189 assert(L == SLL || R == SLL);
7190 return S.Context.UnsignedLongLongTy;
7191 }
7192
Chandler Carruth5659c0c2010-12-12 09:22:45 +00007193 /// \brief Helper method to factor out the common pattern of adding overloads
7194 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007195 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007196 bool HasVolatile,
7197 bool HasRestrict) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007198 QualType ParamTypes[2] = {
7199 S.Context.getLValueReferenceType(CandidateTy),
7200 S.Context.IntTy
7201 };
7202
7203 // Non-volatile version.
Richard Smithe54c3072013-05-05 15:51:06 +00007204 if (Args.size() == 1)
7205 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007206 else
Richard Smithe54c3072013-05-05 15:51:06 +00007207 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007208
7209 // Use a heuristic to reduce number of builtin candidates in the set:
7210 // add volatile version only if there are conversions to a volatile type.
7211 if (HasVolatile) {
7212 ParamTypes[0] =
7213 S.Context.getLValueReferenceType(
7214 S.Context.getVolatileType(CandidateTy));
Richard Smithe54c3072013-05-05 15:51:06 +00007215 if (Args.size() == 1)
7216 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007217 else
Richard Smithe54c3072013-05-05 15:51:06 +00007218 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007219 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007220
7221 // Add restrict version only if there are conversions to a restrict type
7222 // and our candidate type is a non-restrict-qualified pointer.
7223 if (HasRestrict && CandidateTy->isAnyPointerType() &&
7224 !CandidateTy.isRestrictQualified()) {
7225 ParamTypes[0]
7226 = S.Context.getLValueReferenceType(
7227 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
Richard Smithe54c3072013-05-05 15:51:06 +00007228 if (Args.size() == 1)
7229 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007230 else
Richard Smithe54c3072013-05-05 15:51:06 +00007231 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007232
7233 if (HasVolatile) {
7234 ParamTypes[0]
7235 = S.Context.getLValueReferenceType(
7236 S.Context.getCVRQualifiedType(CandidateTy,
7237 (Qualifiers::Volatile |
7238 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007239 if (Args.size() == 1)
7240 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007241 else
Richard Smithe54c3072013-05-05 15:51:06 +00007242 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007243 }
7244 }
7245
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007246 }
7247
7248public:
7249 BuiltinOperatorOverloadBuilder(
Richard Smithe54c3072013-05-05 15:51:06 +00007250 Sema &S, ArrayRef<Expr *> Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007251 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00007252 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007253 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007254 OverloadCandidateSet &CandidateSet)
Richard Smithe54c3072013-05-05 15:51:06 +00007255 : S(S), Args(Args),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007256 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00007257 HasArithmeticOrEnumeralCandidateType(
7258 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007259 CandidateTypes(CandidateTypes),
7260 CandidateSet(CandidateSet) {
7261 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007262 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007263 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007264 assert(getArithmeticType(LastPromotedIntegralType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00007265 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007266 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007267 assert(getArithmeticType(FirstPromotedArithmeticType)
7268 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007269 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007270 assert(getArithmeticType(LastPromotedArithmeticType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00007271 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007272 "Invalid last promoted arithmetic type");
7273 }
7274
7275 // C++ [over.built]p3:
7276 //
7277 // For every pair (T, VQ), where T is an arithmetic type, and VQ
7278 // is either volatile or empty, there exist candidate operator
7279 // functions of the form
7280 //
7281 // VQ T& operator++(VQ T&);
7282 // T operator++(VQ T&, int);
7283 //
7284 // C++ [over.built]p4:
7285 //
7286 // For every pair (T, VQ), where T is an arithmetic type other
7287 // than bool, and VQ is either volatile or empty, there exist
7288 // candidate operator functions of the form
7289 //
7290 // VQ T& operator--(VQ T&);
7291 // T operator--(VQ T&, int);
7292 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007293 if (!HasArithmeticOrEnumeralCandidateType)
7294 return;
7295
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007296 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
7297 Arith < NumArithmeticTypes; ++Arith) {
7298 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00007299 getArithmeticType(Arith),
Douglas Gregor5bee2582012-06-04 00:15:09 +00007300 VisibleTypeConversionsQuals.hasVolatile(),
7301 VisibleTypeConversionsQuals.hasRestrict());
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007302 }
7303 }
7304
7305 // C++ [over.built]p5:
7306 //
7307 // For every pair (T, VQ), where T is a cv-qualified or
7308 // cv-unqualified object type, and VQ is either volatile or
7309 // empty, there exist candidate operator functions of the form
7310 //
7311 // T*VQ& operator++(T*VQ&);
7312 // T*VQ& operator--(T*VQ&);
7313 // T* operator++(T*VQ&, int);
7314 // T* operator--(T*VQ&, int);
7315 void addPlusPlusMinusMinusPointerOverloads() {
7316 for (BuiltinCandidateTypeSet::iterator
7317 Ptr = CandidateTypes[0].pointer_begin(),
7318 PtrEnd = CandidateTypes[0].pointer_end();
7319 Ptr != PtrEnd; ++Ptr) {
7320 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00007321 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007322 continue;
7323
7324 addPlusPlusMinusMinusStyleOverloads(*Ptr,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007325 (!(*Ptr).isVolatileQualified() &&
7326 VisibleTypeConversionsQuals.hasVolatile()),
7327 (!(*Ptr).isRestrictQualified() &&
7328 VisibleTypeConversionsQuals.hasRestrict()));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007329 }
7330 }
7331
7332 // C++ [over.built]p6:
7333 // For every cv-qualified or cv-unqualified object type T, there
7334 // exist candidate operator functions of the form
7335 //
7336 // T& operator*(T*);
7337 //
7338 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007339 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00007340 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007341 // T& operator*(T*);
7342 void addUnaryStarPointerOverloads() {
7343 for (BuiltinCandidateTypeSet::iterator
7344 Ptr = CandidateTypes[0].pointer_begin(),
7345 PtrEnd = CandidateTypes[0].pointer_end();
7346 Ptr != PtrEnd; ++Ptr) {
7347 QualType ParamTy = *Ptr;
7348 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007349 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7350 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007351
Douglas Gregor02824322011-01-26 19:30:28 +00007352 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7353 if (Proto->getTypeQuals() || Proto->getRefQualifier())
7354 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007355
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007356 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
Richard Smithe54c3072013-05-05 15:51:06 +00007357 &ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007358 }
7359 }
7360
7361 // C++ [over.built]p9:
7362 // For every promoted arithmetic type T, there exist candidate
7363 // operator functions of the form
7364 //
7365 // T operator+(T);
7366 // T operator-(T);
7367 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007368 if (!HasArithmeticOrEnumeralCandidateType)
7369 return;
7370
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007371 for (unsigned Arith = FirstPromotedArithmeticType;
7372 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007373 QualType ArithTy = getArithmeticType(Arith);
Richard Smithe54c3072013-05-05 15:51:06 +00007374 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007375 }
7376
7377 // Extension: We also add these operators for vector types.
7378 for (BuiltinCandidateTypeSet::iterator
7379 Vec = CandidateTypes[0].vector_begin(),
7380 VecEnd = CandidateTypes[0].vector_end();
7381 Vec != VecEnd; ++Vec) {
7382 QualType VecTy = *Vec;
Richard Smithe54c3072013-05-05 15:51:06 +00007383 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007384 }
7385 }
7386
7387 // C++ [over.built]p8:
7388 // For every type T, there exist candidate operator functions of
7389 // the form
7390 //
7391 // T* operator+(T*);
7392 void addUnaryPlusPointerOverloads() {
7393 for (BuiltinCandidateTypeSet::iterator
7394 Ptr = CandidateTypes[0].pointer_begin(),
7395 PtrEnd = CandidateTypes[0].pointer_end();
7396 Ptr != PtrEnd; ++Ptr) {
7397 QualType ParamTy = *Ptr;
Richard Smithe54c3072013-05-05 15:51:06 +00007398 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007399 }
7400 }
7401
7402 // C++ [over.built]p10:
7403 // For every promoted integral type T, there exist candidate
7404 // operator functions of the form
7405 //
7406 // T operator~(T);
7407 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007408 if (!HasArithmeticOrEnumeralCandidateType)
7409 return;
7410
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007411 for (unsigned Int = FirstPromotedIntegralType;
7412 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007413 QualType IntTy = getArithmeticType(Int);
Richard Smithe54c3072013-05-05 15:51:06 +00007414 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007415 }
7416
7417 // Extension: We also add this operator for vector types.
7418 for (BuiltinCandidateTypeSet::iterator
7419 Vec = CandidateTypes[0].vector_begin(),
7420 VecEnd = CandidateTypes[0].vector_end();
7421 Vec != VecEnd; ++Vec) {
7422 QualType VecTy = *Vec;
Richard Smithe54c3072013-05-05 15:51:06 +00007423 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007424 }
7425 }
7426
7427 // C++ [over.match.oper]p16:
7428 // For every pointer to member type T, there exist candidate operator
7429 // functions of the form
7430 //
7431 // bool operator==(T,T);
7432 // bool operator!=(T,T);
7433 void addEqualEqualOrNotEqualMemberPointerOverloads() {
7434 /// Set of (canonical) types that we've already handled.
7435 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7436
Richard Smithe54c3072013-05-05 15:51:06 +00007437 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007438 for (BuiltinCandidateTypeSet::iterator
7439 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7440 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7441 MemPtr != MemPtrEnd;
7442 ++MemPtr) {
7443 // Don't add the same builtin candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007444 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007445 continue;
7446
7447 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smithe54c3072013-05-05 15:51:06 +00007448 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007449 }
7450 }
7451 }
7452
7453 // C++ [over.built]p15:
7454 //
Douglas Gregor80af3132011-05-21 23:15:46 +00007455 // For every T, where T is an enumeration type, a pointer type, or
7456 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007457 //
7458 // bool operator<(T, T);
7459 // bool operator>(T, T);
7460 // bool operator<=(T, T);
7461 // bool operator>=(T, T);
7462 // bool operator==(T, T);
7463 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007464 void addRelationalPointerOrEnumeralOverloads() {
Eli Friedman14f082b2012-09-18 21:52:24 +00007465 // C++ [over.match.oper]p3:
7466 // [...]the built-in candidates include all of the candidate operator
7467 // functions defined in 13.6 that, compared to the given operator, [...]
7468 // do not have the same parameter-type-list as any non-template non-member
7469 // candidate.
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007470 //
Eli Friedman14f082b2012-09-18 21:52:24 +00007471 // Note that in practice, this only affects enumeration types because there
7472 // aren't any built-in candidates of record type, and a user-defined operator
7473 // must have an operand of record or enumeration type. Also, the only other
7474 // overloaded operator with enumeration arguments, operator=,
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007475 // cannot be overloaded for enumeration types, so this is the only place
7476 // where we must suppress candidates like this.
7477 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7478 UserDefinedBinaryOperators;
7479
Richard Smithe54c3072013-05-05 15:51:06 +00007480 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007481 if (CandidateTypes[ArgIdx].enumeration_begin() !=
7482 CandidateTypes[ArgIdx].enumeration_end()) {
7483 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7484 CEnd = CandidateSet.end();
7485 C != CEnd; ++C) {
7486 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7487 continue;
7488
Eli Friedman14f082b2012-09-18 21:52:24 +00007489 if (C->Function->isFunctionTemplateSpecialization())
7490 continue;
7491
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007492 QualType FirstParamType =
7493 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7494 QualType SecondParamType =
7495 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7496
7497 // Skip if either parameter isn't of enumeral type.
7498 if (!FirstParamType->isEnumeralType() ||
7499 !SecondParamType->isEnumeralType())
7500 continue;
7501
7502 // Add this operator to the set of known user-defined operators.
7503 UserDefinedBinaryOperators.insert(
7504 std::make_pair(S.Context.getCanonicalType(FirstParamType),
7505 S.Context.getCanonicalType(SecondParamType)));
7506 }
7507 }
7508 }
7509
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007510 /// Set of (canonical) types that we've already handled.
7511 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7512
Richard Smithe54c3072013-05-05 15:51:06 +00007513 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007514 for (BuiltinCandidateTypeSet::iterator
7515 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7516 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7517 Ptr != PtrEnd; ++Ptr) {
7518 // Don't add the same builtin candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007519 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007520 continue;
7521
7522 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smithe54c3072013-05-05 15:51:06 +00007523 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007524 }
7525 for (BuiltinCandidateTypeSet::iterator
7526 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7527 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7528 Enum != EnumEnd; ++Enum) {
7529 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
7530
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007531 // Don't add the same builtin candidate twice, or if a user defined
7532 // candidate exists.
David Blaikie82e95a32014-11-19 07:49:47 +00007533 if (!AddedTypes.insert(CanonType).second ||
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007534 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
7535 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007536 continue;
7537
7538 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smithe54c3072013-05-05 15:51:06 +00007539 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007540 }
Douglas Gregor80af3132011-05-21 23:15:46 +00007541
7542 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7543 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
David Blaikie82e95a32014-11-19 07:49:47 +00007544 if (AddedTypes.insert(NullPtrTy).second &&
Richard Smithe54c3072013-05-05 15:51:06 +00007545 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
Douglas Gregor80af3132011-05-21 23:15:46 +00007546 NullPtrTy))) {
7547 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
Richard Smithe54c3072013-05-05 15:51:06 +00007548 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
Douglas Gregor80af3132011-05-21 23:15:46 +00007549 CandidateSet);
7550 }
7551 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007552 }
7553 }
7554
7555 // C++ [over.built]p13:
7556 //
7557 // For every cv-qualified or cv-unqualified object type T
7558 // there exist candidate operator functions of the form
7559 //
7560 // T* operator+(T*, ptrdiff_t);
7561 // T& operator[](T*, ptrdiff_t); [BELOW]
7562 // T* operator-(T*, ptrdiff_t);
7563 // T* operator+(ptrdiff_t, T*);
7564 // T& operator[](ptrdiff_t, T*); [BELOW]
7565 //
7566 // C++ [over.built]p14:
7567 //
7568 // For every T, where T is a pointer to object type, there
7569 // exist candidate operator functions of the form
7570 //
7571 // ptrdiff_t operator-(T, T);
7572 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
7573 /// Set of (canonical) types that we've already handled.
7574 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7575
7576 for (int Arg = 0; Arg < 2; ++Arg) {
Eric Christopher9207a522015-08-21 16:24:01 +00007577 QualType AsymmetricParamTypes[2] = {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007578 S.Context.getPointerDiffType(),
7579 S.Context.getPointerDiffType(),
7580 };
7581 for (BuiltinCandidateTypeSet::iterator
7582 Ptr = CandidateTypes[Arg].pointer_begin(),
7583 PtrEnd = CandidateTypes[Arg].pointer_end();
7584 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00007585 QualType PointeeTy = (*Ptr)->getPointeeType();
7586 if (!PointeeTy->isObjectType())
7587 continue;
7588
Eric Christopher9207a522015-08-21 16:24:01 +00007589 AsymmetricParamTypes[Arg] = *Ptr;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007590 if (Arg == 0 || Op == OO_Plus) {
7591 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
7592 // T* operator+(ptrdiff_t, T*);
Eric Christopher9207a522015-08-21 16:24:01 +00007593 S.AddBuiltinCandidate(*Ptr, AsymmetricParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007594 }
7595 if (Op == OO_Minus) {
7596 // ptrdiff_t operator-(T, T);
David Blaikie82e95a32014-11-19 07:49:47 +00007597 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007598 continue;
7599
7600 QualType ParamTypes[2] = { *Ptr, *Ptr };
7601 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
Richard Smithe54c3072013-05-05 15:51:06 +00007602 Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007603 }
7604 }
7605 }
7606 }
7607
7608 // C++ [over.built]p12:
7609 //
7610 // For every pair of promoted arithmetic types L and R, there
7611 // exist candidate operator functions of the form
7612 //
7613 // LR operator*(L, R);
7614 // LR operator/(L, R);
7615 // LR operator+(L, R);
7616 // LR operator-(L, R);
7617 // bool operator<(L, R);
7618 // bool operator>(L, R);
7619 // bool operator<=(L, R);
7620 // bool operator>=(L, R);
7621 // bool operator==(L, R);
7622 // bool operator!=(L, R);
7623 //
7624 // where LR is the result of the usual arithmetic conversions
7625 // between types L and R.
7626 //
7627 // C++ [over.built]p24:
7628 //
7629 // For every pair of promoted arithmetic types L and R, there exist
7630 // candidate operator functions of the form
7631 //
7632 // LR operator?(bool, L, R);
7633 //
7634 // where LR is the result of the usual arithmetic conversions
7635 // between types L and R.
7636 // Our candidates ignore the first parameter.
7637 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007638 if (!HasArithmeticOrEnumeralCandidateType)
7639 return;
7640
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007641 for (unsigned Left = FirstPromotedArithmeticType;
7642 Left < LastPromotedArithmeticType; ++Left) {
7643 for (unsigned Right = FirstPromotedArithmeticType;
7644 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007645 QualType LandR[2] = { getArithmeticType(Left),
7646 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007647 QualType Result =
7648 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007649 : getUsualArithmeticConversions(Left, Right);
Richard Smithe54c3072013-05-05 15:51:06 +00007650 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007651 }
7652 }
7653
7654 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7655 // conditional operator for vector types.
7656 for (BuiltinCandidateTypeSet::iterator
7657 Vec1 = CandidateTypes[0].vector_begin(),
7658 Vec1End = CandidateTypes[0].vector_end();
7659 Vec1 != Vec1End; ++Vec1) {
7660 for (BuiltinCandidateTypeSet::iterator
7661 Vec2 = CandidateTypes[1].vector_begin(),
7662 Vec2End = CandidateTypes[1].vector_end();
7663 Vec2 != Vec2End; ++Vec2) {
7664 QualType LandR[2] = { *Vec1, *Vec2 };
7665 QualType Result = S.Context.BoolTy;
7666 if (!isComparison) {
7667 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7668 Result = *Vec1;
7669 else
7670 Result = *Vec2;
7671 }
7672
Richard Smithe54c3072013-05-05 15:51:06 +00007673 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007674 }
7675 }
7676 }
7677
7678 // C++ [over.built]p17:
7679 //
7680 // For every pair of promoted integral types L and R, there
7681 // exist candidate operator functions of the form
7682 //
7683 // LR operator%(L, R);
7684 // LR operator&(L, R);
7685 // LR operator^(L, R);
7686 // LR operator|(L, R);
7687 // L operator<<(L, R);
7688 // L operator>>(L, R);
7689 //
7690 // where LR is the result of the usual arithmetic conversions
7691 // between types L and R.
7692 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007693 if (!HasArithmeticOrEnumeralCandidateType)
7694 return;
7695
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007696 for (unsigned Left = FirstPromotedIntegralType;
7697 Left < LastPromotedIntegralType; ++Left) {
7698 for (unsigned Right = FirstPromotedIntegralType;
7699 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007700 QualType LandR[2] = { getArithmeticType(Left),
7701 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007702 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7703 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007704 : getUsualArithmeticConversions(Left, Right);
Richard Smithe54c3072013-05-05 15:51:06 +00007705 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007706 }
7707 }
7708 }
7709
7710 // C++ [over.built]p20:
7711 //
7712 // For every pair (T, VQ), where T is an enumeration or
7713 // pointer to member type and VQ is either volatile or
7714 // empty, there exist candidate operator functions of the form
7715 //
7716 // VQ T& operator=(VQ T&, T);
7717 void addAssignmentMemberPointerOrEnumeralOverloads() {
7718 /// Set of (canonical) types that we've already handled.
7719 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7720
7721 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7722 for (BuiltinCandidateTypeSet::iterator
7723 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7724 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7725 Enum != EnumEnd; ++Enum) {
David Blaikie82e95a32014-11-19 07:49:47 +00007726 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007727 continue;
7728
Richard Smithe54c3072013-05-05 15:51:06 +00007729 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007730 }
7731
7732 for (BuiltinCandidateTypeSet::iterator
7733 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7734 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7735 MemPtr != MemPtrEnd; ++MemPtr) {
David Blaikie82e95a32014-11-19 07:49:47 +00007736 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007737 continue;
7738
Richard Smithe54c3072013-05-05 15:51:06 +00007739 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007740 }
7741 }
7742 }
7743
7744 // C++ [over.built]p19:
7745 //
7746 // For every pair (T, VQ), where T is any type and VQ is either
7747 // volatile or empty, there exist candidate operator functions
7748 // of the form
7749 //
7750 // T*VQ& operator=(T*VQ&, T*);
7751 //
7752 // C++ [over.built]p21:
7753 //
7754 // For every pair (T, VQ), where T is a cv-qualified or
7755 // cv-unqualified object type and VQ is either volatile or
7756 // empty, there exist candidate operator functions of the form
7757 //
7758 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
7759 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
7760 void addAssignmentPointerOverloads(bool isEqualOp) {
7761 /// Set of (canonical) types that we've already handled.
7762 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7763
7764 for (BuiltinCandidateTypeSet::iterator
7765 Ptr = CandidateTypes[0].pointer_begin(),
7766 PtrEnd = CandidateTypes[0].pointer_end();
7767 Ptr != PtrEnd; ++Ptr) {
7768 // If this is operator=, keep track of the builtin candidates we added.
7769 if (isEqualOp)
7770 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00007771 else if (!(*Ptr)->getPointeeType()->isObjectType())
7772 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007773
7774 // non-volatile version
7775 QualType ParamTypes[2] = {
7776 S.Context.getLValueReferenceType(*Ptr),
7777 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7778 };
Richard Smithe54c3072013-05-05 15:51:06 +00007779 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007780 /*IsAssigmentOperator=*/ isEqualOp);
7781
Douglas Gregor5bee2582012-06-04 00:15:09 +00007782 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7783 VisibleTypeConversionsQuals.hasVolatile();
7784 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007785 // volatile version
7786 ParamTypes[0] =
7787 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007788 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007789 /*IsAssigmentOperator=*/isEqualOp);
7790 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007791
7792 if (!(*Ptr).isRestrictQualified() &&
7793 VisibleTypeConversionsQuals.hasRestrict()) {
7794 // restrict version
7795 ParamTypes[0]
7796 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007797 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007798 /*IsAssigmentOperator=*/isEqualOp);
7799
7800 if (NeedVolatile) {
7801 // volatile restrict version
7802 ParamTypes[0]
7803 = S.Context.getLValueReferenceType(
7804 S.Context.getCVRQualifiedType(*Ptr,
7805 (Qualifiers::Volatile |
7806 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007807 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007808 /*IsAssigmentOperator=*/isEqualOp);
7809 }
7810 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007811 }
7812
7813 if (isEqualOp) {
7814 for (BuiltinCandidateTypeSet::iterator
7815 Ptr = CandidateTypes[1].pointer_begin(),
7816 PtrEnd = CandidateTypes[1].pointer_end();
7817 Ptr != PtrEnd; ++Ptr) {
7818 // Make sure we don't add the same candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007819 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007820 continue;
7821
Chandler Carruth8e543b32010-12-12 08:17:55 +00007822 QualType ParamTypes[2] = {
7823 S.Context.getLValueReferenceType(*Ptr),
7824 *Ptr,
7825 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007826
7827 // non-volatile version
Richard Smithe54c3072013-05-05 15:51:06 +00007828 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007829 /*IsAssigmentOperator=*/true);
7830
Douglas Gregor5bee2582012-06-04 00:15:09 +00007831 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7832 VisibleTypeConversionsQuals.hasVolatile();
7833 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007834 // volatile version
7835 ParamTypes[0] =
7836 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007837 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7838 /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007839 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007840
7841 if (!(*Ptr).isRestrictQualified() &&
7842 VisibleTypeConversionsQuals.hasRestrict()) {
7843 // restrict version
7844 ParamTypes[0]
7845 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007846 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7847 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007848
7849 if (NeedVolatile) {
7850 // volatile restrict version
7851 ParamTypes[0]
7852 = S.Context.getLValueReferenceType(
7853 S.Context.getCVRQualifiedType(*Ptr,
7854 (Qualifiers::Volatile |
7855 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007856 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7857 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007858 }
7859 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007860 }
7861 }
7862 }
7863
7864 // C++ [over.built]p18:
7865 //
7866 // For every triple (L, VQ, R), where L is an arithmetic type,
7867 // VQ is either volatile or empty, and R is a promoted
7868 // arithmetic type, there exist candidate operator functions of
7869 // the form
7870 //
7871 // VQ L& operator=(VQ L&, R);
7872 // VQ L& operator*=(VQ L&, R);
7873 // VQ L& operator/=(VQ L&, R);
7874 // VQ L& operator+=(VQ L&, R);
7875 // VQ L& operator-=(VQ L&, R);
7876 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007877 if (!HasArithmeticOrEnumeralCandidateType)
7878 return;
7879
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007880 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7881 for (unsigned Right = FirstPromotedArithmeticType;
7882 Right < LastPromotedArithmeticType; ++Right) {
7883 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00007884 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007885
7886 // Add this built-in operator as a candidate (VQ is empty).
7887 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007888 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smithe54c3072013-05-05 15:51:06 +00007889 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007890 /*IsAssigmentOperator=*/isEqualOp);
7891
7892 // Add this built-in operator as a candidate (VQ is 'volatile').
7893 if (VisibleTypeConversionsQuals.hasVolatile()) {
7894 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007895 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007896 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00007897 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007898 /*IsAssigmentOperator=*/isEqualOp);
7899 }
7900 }
7901 }
7902
7903 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7904 for (BuiltinCandidateTypeSet::iterator
7905 Vec1 = CandidateTypes[0].vector_begin(),
7906 Vec1End = CandidateTypes[0].vector_end();
7907 Vec1 != Vec1End; ++Vec1) {
7908 for (BuiltinCandidateTypeSet::iterator
7909 Vec2 = CandidateTypes[1].vector_begin(),
7910 Vec2End = CandidateTypes[1].vector_end();
7911 Vec2 != Vec2End; ++Vec2) {
7912 QualType ParamTypes[2];
7913 ParamTypes[1] = *Vec2;
7914 // Add this built-in operator as a candidate (VQ is empty).
7915 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
Richard Smithe54c3072013-05-05 15:51:06 +00007916 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007917 /*IsAssigmentOperator=*/isEqualOp);
7918
7919 // Add this built-in operator as a candidate (VQ is 'volatile').
7920 if (VisibleTypeConversionsQuals.hasVolatile()) {
7921 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7922 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00007923 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007924 /*IsAssigmentOperator=*/isEqualOp);
7925 }
7926 }
7927 }
7928 }
7929
7930 // C++ [over.built]p22:
7931 //
7932 // For every triple (L, VQ, R), where L is an integral type, VQ
7933 // is either volatile or empty, and R is a promoted integral
7934 // type, there exist candidate operator functions of the form
7935 //
7936 // VQ L& operator%=(VQ L&, R);
7937 // VQ L& operator<<=(VQ L&, R);
7938 // VQ L& operator>>=(VQ L&, R);
7939 // VQ L& operator&=(VQ L&, R);
7940 // VQ L& operator^=(VQ L&, R);
7941 // VQ L& operator|=(VQ L&, R);
7942 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007943 if (!HasArithmeticOrEnumeralCandidateType)
7944 return;
7945
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007946 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7947 for (unsigned Right = FirstPromotedIntegralType;
7948 Right < LastPromotedIntegralType; ++Right) {
7949 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00007950 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007951
7952 // Add this built-in operator as a candidate (VQ is empty).
7953 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007954 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smithe54c3072013-05-05 15:51:06 +00007955 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007956 if (VisibleTypeConversionsQuals.hasVolatile()) {
7957 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00007958 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007959 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7960 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00007961 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007962 }
7963 }
7964 }
7965 }
7966
7967 // C++ [over.operator]p23:
7968 //
7969 // There also exist candidate operator functions of the form
7970 //
7971 // bool operator!(bool);
7972 // bool operator&&(bool, bool);
7973 // bool operator||(bool, bool);
7974 void addExclaimOverload() {
7975 QualType ParamTy = S.Context.BoolTy;
Richard Smithe54c3072013-05-05 15:51:06 +00007976 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007977 /*IsAssignmentOperator=*/false,
7978 /*NumContextualBoolArguments=*/1);
7979 }
7980 void addAmpAmpOrPipePipeOverload() {
7981 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
Richard Smithe54c3072013-05-05 15:51:06 +00007982 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007983 /*IsAssignmentOperator=*/false,
7984 /*NumContextualBoolArguments=*/2);
7985 }
7986
7987 // C++ [over.built]p13:
7988 //
7989 // For every cv-qualified or cv-unqualified object type T there
7990 // exist candidate operator functions of the form
7991 //
7992 // T* operator+(T*, ptrdiff_t); [ABOVE]
7993 // T& operator[](T*, ptrdiff_t);
7994 // T* operator-(T*, ptrdiff_t); [ABOVE]
7995 // T* operator+(ptrdiff_t, T*); [ABOVE]
7996 // T& operator[](ptrdiff_t, T*);
7997 void addSubscriptOverloads() {
7998 for (BuiltinCandidateTypeSet::iterator
7999 Ptr = CandidateTypes[0].pointer_begin(),
8000 PtrEnd = CandidateTypes[0].pointer_end();
8001 Ptr != PtrEnd; ++Ptr) {
8002 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8003 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00008004 if (!PointeeType->isObjectType())
8005 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008006
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008007 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8008
8009 // T& operator[](T*, ptrdiff_t)
Richard Smithe54c3072013-05-05 15:51:06 +00008010 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008011 }
8012
8013 for (BuiltinCandidateTypeSet::iterator
8014 Ptr = CandidateTypes[1].pointer_begin(),
8015 PtrEnd = CandidateTypes[1].pointer_end();
8016 Ptr != PtrEnd; ++Ptr) {
8017 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8018 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00008019 if (!PointeeType->isObjectType())
8020 continue;
8021
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008022 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8023
8024 // T& operator[](ptrdiff_t, T*)
Richard Smithe54c3072013-05-05 15:51:06 +00008025 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008026 }
8027 }
8028
8029 // C++ [over.built]p11:
8030 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8031 // C1 is the same type as C2 or is a derived class of C2, T is an object
8032 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8033 // there exist candidate operator functions of the form
8034 //
8035 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8036 //
8037 // where CV12 is the union of CV1 and CV2.
8038 void addArrowStarOverloads() {
8039 for (BuiltinCandidateTypeSet::iterator
8040 Ptr = CandidateTypes[0].pointer_begin(),
8041 PtrEnd = CandidateTypes[0].pointer_end();
8042 Ptr != PtrEnd; ++Ptr) {
8043 QualType C1Ty = (*Ptr);
8044 QualType C1;
8045 QualifierCollector Q1;
8046 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8047 if (!isa<RecordType>(C1))
8048 continue;
8049 // heuristic to reduce number of builtin candidates in the set.
8050 // Add volatile/restrict version only if there are conversions to a
8051 // volatile/restrict type.
8052 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8053 continue;
8054 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8055 continue;
8056 for (BuiltinCandidateTypeSet::iterator
8057 MemPtr = CandidateTypes[1].member_pointer_begin(),
8058 MemPtrEnd = CandidateTypes[1].member_pointer_end();
8059 MemPtr != MemPtrEnd; ++MemPtr) {
8060 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8061 QualType C2 = QualType(mptr->getClass(), 0);
8062 C2 = C2.getUnqualifiedType();
8063 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
8064 break;
8065 QualType ParamTypes[2] = { *Ptr, *MemPtr };
8066 // build CV12 T&
8067 QualType T = mptr->getPointeeType();
8068 if (!VisibleTypeConversionsQuals.hasVolatile() &&
8069 T.isVolatileQualified())
8070 continue;
8071 if (!VisibleTypeConversionsQuals.hasRestrict() &&
8072 T.isRestrictQualified())
8073 continue;
8074 T = Q1.apply(S.Context, T);
8075 QualType ResultTy = S.Context.getLValueReferenceType(T);
Richard Smithe54c3072013-05-05 15:51:06 +00008076 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008077 }
8078 }
8079 }
8080
8081 // Note that we don't consider the first argument, since it has been
8082 // contextually converted to bool long ago. The candidates below are
8083 // therefore added as binary.
8084 //
8085 // C++ [over.built]p25:
8086 // For every type T, where T is a pointer, pointer-to-member, or scoped
8087 // enumeration type, there exist candidate operator functions of the form
8088 //
8089 // T operator?(bool, T, T);
8090 //
8091 void addConditionalOperatorOverloads() {
8092 /// Set of (canonical) types that we've already handled.
8093 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8094
8095 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8096 for (BuiltinCandidateTypeSet::iterator
8097 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8098 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8099 Ptr != PtrEnd; ++Ptr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008100 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008101 continue;
8102
8103 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smithe54c3072013-05-05 15:51:06 +00008104 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008105 }
8106
8107 for (BuiltinCandidateTypeSet::iterator
8108 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8109 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8110 MemPtr != MemPtrEnd; ++MemPtr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008111 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008112 continue;
8113
8114 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smithe54c3072013-05-05 15:51:06 +00008115 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008116 }
8117
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008118 if (S.getLangOpts().CPlusPlus11) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008119 for (BuiltinCandidateTypeSet::iterator
8120 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8121 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8122 Enum != EnumEnd; ++Enum) {
8123 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8124 continue;
8125
David Blaikie82e95a32014-11-19 07:49:47 +00008126 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008127 continue;
8128
8129 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smithe54c3072013-05-05 15:51:06 +00008130 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008131 }
8132 }
8133 }
8134 }
8135};
8136
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008137} // end anonymous namespace
8138
8139/// AddBuiltinOperatorCandidates - Add the appropriate built-in
8140/// operator overloads to the candidate set (C++ [over.built]), based
8141/// on the operator @p Op and the arguments given. For example, if the
8142/// operator is a binary '+', this routine might add "int
8143/// operator+(int, int)" to cover integer addition.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00008144void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8145 SourceLocation OpLoc,
8146 ArrayRef<Expr *> Args,
8147 OverloadCandidateSet &CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00008148 // Find all of the types that the arguments can convert to, but only
8149 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00008150 // that make use of these types. Also record whether we encounter non-record
8151 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00008152 Qualifiers VisibleTypeConversionsQuals;
8153 VisibleTypeConversionsQuals.addConst();
Richard Smithe54c3072013-05-05 15:51:06 +00008154 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00008155 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00008156
8157 bool HasNonRecordCandidateType = false;
8158 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008159 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Richard Smithe54c3072013-05-05 15:51:06 +00008160 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Benjamin Kramer57dddd482015-02-17 21:55:18 +00008161 CandidateTypes.emplace_back(*this);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00008162 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8163 OpLoc,
8164 true,
8165 (Op == OO_Exclaim ||
8166 Op == OO_AmpAmp ||
8167 Op == OO_PipePipe),
8168 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00008169 HasNonRecordCandidateType = HasNonRecordCandidateType ||
8170 CandidateTypes[ArgIdx].hasNonRecordTypes();
8171 HasArithmeticOrEnumeralCandidateType =
8172 HasArithmeticOrEnumeralCandidateType ||
8173 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00008174 }
Douglas Gregora11693b2008-11-12 17:17:38 +00008175
Chandler Carruth00a38332010-12-13 01:44:01 +00008176 // Exit early when no non-record types have been added to the candidate set
8177 // for any of the arguments to the operator.
Douglas Gregor877d4eb2011-10-10 14:05:31 +00008178 //
8179 // We can't exit early for !, ||, or &&, since there we have always have
8180 // 'bool' overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00008181 if (!HasNonRecordCandidateType &&
Douglas Gregor877d4eb2011-10-10 14:05:31 +00008182 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth00a38332010-12-13 01:44:01 +00008183 return;
8184
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008185 // Setup an object to manage the common state for building overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00008186 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008187 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00008188 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008189 CandidateTypes, CandidateSet);
8190
8191 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00008192 switch (Op) {
8193 case OO_None:
8194 case NUM_OVERLOADED_OPERATORS:
David Blaikie83d382b2011-09-23 05:06:16 +00008195 llvm_unreachable("Expected an overloaded operator");
Douglas Gregora11693b2008-11-12 17:17:38 +00008196
Chandler Carruth5184de02010-12-12 08:51:33 +00008197 case OO_New:
8198 case OO_Delete:
8199 case OO_Array_New:
8200 case OO_Array_Delete:
8201 case OO_Call:
David Blaikie83d382b2011-09-23 05:06:16 +00008202 llvm_unreachable(
8203 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruth5184de02010-12-12 08:51:33 +00008204
8205 case OO_Comma:
8206 case OO_Arrow:
8207 // C++ [over.match.oper]p3:
8208 // -- For the operator ',', the unary operator '&', or the
8209 // operator '->', the built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00008210 break;
8211
8212 case OO_Plus: // '+' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008213 if (Args.size() == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008214 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00008215 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00008216
8217 case OO_Minus: // '-' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008218 if (Args.size() == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008219 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008220 } else {
8221 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8222 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8223 }
Douglas Gregord08452f2008-11-19 15:42:04 +00008224 break;
8225
Chandler Carruth5184de02010-12-12 08:51:33 +00008226 case OO_Star: // '*' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008227 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008228 OpBuilder.addUnaryStarPointerOverloads();
8229 else
8230 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8231 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008232
Chandler Carruth5184de02010-12-12 08:51:33 +00008233 case OO_Slash:
8234 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008235 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008236
8237 case OO_PlusPlus:
8238 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008239 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8240 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00008241 break;
8242
Douglas Gregor84605ae2009-08-24 13:43:27 +00008243 case OO_EqualEqual:
8244 case OO_ExclaimEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008245 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00008246 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008247
Douglas Gregora11693b2008-11-12 17:17:38 +00008248 case OO_Less:
8249 case OO_Greater:
8250 case OO_LessEqual:
8251 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00008252 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00008253 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
8254 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008255
Douglas Gregora11693b2008-11-12 17:17:38 +00008256 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00008257 case OO_Caret:
8258 case OO_Pipe:
8259 case OO_LessLess:
8260 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008261 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00008262 break;
8263
Chandler Carruth5184de02010-12-12 08:51:33 +00008264 case OO_Amp: // '&' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008265 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008266 // C++ [over.match.oper]p3:
8267 // -- For the operator ',', the unary operator '&', or the
8268 // operator '->', the built-in candidates set is empty.
8269 break;
8270
8271 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8272 break;
8273
8274 case OO_Tilde:
8275 OpBuilder.addUnaryTildePromotedIntegralOverloads();
8276 break;
8277
Douglas Gregora11693b2008-11-12 17:17:38 +00008278 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008279 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00008280 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00008281
8282 case OO_PlusEqual:
8283 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008284 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008285 // Fall through.
8286
8287 case OO_StarEqual:
8288 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008289 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008290 break;
8291
8292 case OO_PercentEqual:
8293 case OO_LessLessEqual:
8294 case OO_GreaterGreaterEqual:
8295 case OO_AmpEqual:
8296 case OO_CaretEqual:
8297 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008298 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008299 break;
8300
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008301 case OO_Exclaim:
8302 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00008303 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008304
Douglas Gregora11693b2008-11-12 17:17:38 +00008305 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008306 case OO_PipePipe:
8307 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00008308 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008309
8310 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008311 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008312 break;
8313
8314 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008315 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008316 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00008317
8318 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008319 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008320 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8321 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008322 }
8323}
8324
Douglas Gregore254f902009-02-04 00:32:51 +00008325/// \brief Add function candidates found via argument-dependent lookup
8326/// to the set of overloading candidates.
8327///
8328/// This routine performs argument-dependent name lookup based on the
8329/// given function name (which may also be an operator name) and adds
8330/// all of the overload candidates found by ADL to the overload
8331/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00008332void
Douglas Gregore254f902009-02-04 00:32:51 +00008333Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smith100b24a2014-04-17 01:52:14 +00008334 SourceLocation Loc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008335 ArrayRef<Expr *> Args,
Douglas Gregor739b107a2011-03-03 02:41:12 +00008336 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008337 OverloadCandidateSet& CandidateSet,
Richard Smithb6626742012-10-18 17:56:02 +00008338 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00008339 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00008340
John McCall91f61fc2010-01-26 06:04:06 +00008341 // FIXME: This approach for uniquing ADL results (and removing
8342 // redundant candidates from the set) relies on pointer-equality,
8343 // which means we need to key off the canonical decl. However,
8344 // always going back to the canonical decl might not get us the
8345 // right set of default arguments. What default arguments are
8346 // we supposed to consider on ADL candidates, anyway?
8347
Douglas Gregorcabea402009-09-22 15:41:20 +00008348 // FIXME: Pass in the explicit template arguments?
Richard Smith100b24a2014-04-17 01:52:14 +00008349 ArgumentDependentLookup(Name, Loc, Args, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00008350
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008351 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008352 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8353 CandEnd = CandidateSet.end();
8354 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00008355 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00008356 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00008357 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00008358 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00008359 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008360
8361 // For each of the ADL candidates we found, add it to the overload
8362 // set.
John McCall8fe68082010-01-26 07:16:45 +00008363 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00008364 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00008365 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00008366 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00008367 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008368
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008369 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8370 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00008371 } else
John McCall4c4c1df2010-01-26 03:27:55 +00008372 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00008373 FoundDecl, ExplicitTemplateArgs,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00008374 Args, CandidateSet, PartialOverloading);
Douglas Gregor15448f82009-06-27 21:05:07 +00008375 }
Douglas Gregore254f902009-02-04 00:32:51 +00008376}
8377
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008378/// isBetterOverloadCandidate - Determines whether the first overload
8379/// candidate is a better candidate than the second (C++ 13.3.3p1).
Richard Smith17c00b42014-11-12 01:24:00 +00008380bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1,
8381 const OverloadCandidate &Cand2,
8382 SourceLocation Loc,
8383 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008384 // Define viable functions to be better candidates than non-viable
8385 // functions.
8386 if (!Cand2.Viable)
8387 return Cand1.Viable;
8388 else if (!Cand1.Viable)
8389 return false;
8390
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008391 // C++ [over.match.best]p1:
8392 //
8393 // -- if F is a static member function, ICS1(F) is defined such
8394 // that ICS1(F) is neither better nor worse than ICS1(G) for
8395 // any function G, and, symmetrically, ICS1(G) is neither
8396 // better nor worse than ICS1(F).
8397 unsigned StartArg = 0;
8398 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8399 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008400
Douglas Gregord3cb3562009-07-07 23:38:56 +00008401 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00008402 // A viable function F1 is defined to be a better function than another
8403 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00008404 // conversion sequence than ICSi(F2), and then...
Benjamin Kramerb0095172012-01-14 16:32:05 +00008405 unsigned NumArgs = Cand1.NumConversions;
8406 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008407 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008408 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall5c32be02010-08-24 20:38:10 +00008409 switch (CompareImplicitConversionSequences(S,
8410 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008411 Cand2.Conversions[ArgIdx])) {
8412 case ImplicitConversionSequence::Better:
8413 // Cand1 has a better conversion sequence.
8414 HasBetterConversion = true;
8415 break;
8416
8417 case ImplicitConversionSequence::Worse:
8418 // Cand1 can't be better than Cand2.
8419 return false;
8420
8421 case ImplicitConversionSequence::Indistinguishable:
8422 // Do nothing.
8423 break;
8424 }
8425 }
8426
Mike Stump11289f42009-09-09 15:08:12 +00008427 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00008428 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008429 if (HasBetterConversion)
8430 return true;
8431
Douglas Gregora1f013e2008-11-07 22:36:19 +00008432 // -- the context is an initialization by user-defined conversion
8433 // (see 8.5, 13.3.1.5) and the standard conversion sequence
8434 // from the return type of F1 to the destination type (i.e.,
8435 // the type of the entity being initialized) is a better
8436 // conversion sequence than the standard conversion sequence
8437 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00008438 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00008439 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00008440 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregor2837aa22012-02-22 17:32:19 +00008441 // First check whether we prefer one of the conversion functions over the
8442 // other. This only distinguishes the results in non-standard, extension
8443 // cases such as the conversion from a lambda closure type to a function
8444 // pointer or block.
Richard Smithec2748a2014-05-17 04:36:39 +00008445 ImplicitConversionSequence::CompareKind Result =
8446 compareConversionFunctions(S, Cand1.Function, Cand2.Function);
8447 if (Result == ImplicitConversionSequence::Indistinguishable)
8448 Result = CompareStandardConversionSequences(S,
8449 Cand1.FinalConversion,
8450 Cand2.FinalConversion);
Richard Smith6fdeaab2014-05-17 01:58:45 +00008451
Richard Smithec2748a2014-05-17 04:36:39 +00008452 if (Result != ImplicitConversionSequence::Indistinguishable)
8453 return Result == ImplicitConversionSequence::Better;
Richard Smith6fdeaab2014-05-17 01:58:45 +00008454
8455 // FIXME: Compare kind of reference binding if conversion functions
8456 // convert to a reference type used in direct reference binding, per
8457 // C++14 [over.match.best]p1 section 2 bullet 3.
8458 }
8459
8460 // -- F1 is a non-template function and F2 is a function template
8461 // specialization, or, if not that,
8462 bool Cand1IsSpecialization = Cand1.Function &&
8463 Cand1.Function->getPrimaryTemplate();
8464 bool Cand2IsSpecialization = Cand2.Function &&
8465 Cand2.Function->getPrimaryTemplate();
8466 if (Cand1IsSpecialization != Cand2IsSpecialization)
8467 return Cand2IsSpecialization;
8468
8469 // -- F1 and F2 are function template specializations, and the function
8470 // template for F1 is more specialized than the template for F2
8471 // according to the partial ordering rules described in 14.5.5.2, or,
8472 // if not that,
8473 if (Cand1IsSpecialization && Cand2IsSpecialization) {
8474 if (FunctionTemplateDecl *BetterTemplate
8475 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
8476 Cand2.Function->getPrimaryTemplate(),
8477 Loc,
8478 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
8479 : TPOC_Call,
8480 Cand1.ExplicitCallArguments,
8481 Cand2.ExplicitCallArguments))
8482 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregora1f013e2008-11-07 22:36:19 +00008483 }
8484
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008485 // Check for enable_if value-based overload resolution.
8486 if (Cand1.Function && Cand2.Function &&
8487 (Cand1.Function->hasAttr<EnableIfAttr>() ||
8488 Cand2.Function->hasAttr<EnableIfAttr>())) {
8489 // FIXME: The next several lines are just
8490 // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8491 // instead of reverse order which is how they're stored in the AST.
8492 AttrVec Cand1Attrs;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008493 if (Cand1.Function->hasAttrs()) {
8494 Cand1Attrs = Cand1.Function->getAttrs();
Richard Smith9516eee2014-05-17 02:21:47 +00008495 Cand1Attrs.erase(std::remove_if(Cand1Attrs.begin(), Cand1Attrs.end(),
8496 IsNotEnableIfAttr),
8497 Cand1Attrs.end());
8498 std::reverse(Cand1Attrs.begin(), Cand1Attrs.end());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008499 }
8500
8501 AttrVec Cand2Attrs;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008502 if (Cand2.Function->hasAttrs()) {
8503 Cand2Attrs = Cand2.Function->getAttrs();
Richard Smith9516eee2014-05-17 02:21:47 +00008504 Cand2Attrs.erase(std::remove_if(Cand2Attrs.begin(), Cand2Attrs.end(),
8505 IsNotEnableIfAttr),
8506 Cand2Attrs.end());
8507 std::reverse(Cand2Attrs.begin(), Cand2Attrs.end());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008508 }
Richard Smith9516eee2014-05-17 02:21:47 +00008509
8510 // Candidate 1 is better if it has strictly more attributes and
8511 // the common sequence is identical.
8512 if (Cand1Attrs.size() <= Cand2Attrs.size())
8513 return false;
8514
8515 auto Cand1I = Cand1Attrs.begin();
8516 for (auto &Cand2A : Cand2Attrs) {
8517 auto &Cand1A = *Cand1I++;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008518 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
Richard Smith9516eee2014-05-17 02:21:47 +00008519 cast<EnableIfAttr>(Cand1A)->getCond()->Profile(Cand1ID,
8520 S.getASTContext(), true);
8521 cast<EnableIfAttr>(Cand2A)->getCond()->Profile(Cand2ID,
8522 S.getASTContext(), true);
Nick Lewyckyd950ae72014-01-21 01:30:30 +00008523 if (Cand1ID != Cand2ID)
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008524 return false;
8525 }
Richard Smith9516eee2014-05-17 02:21:47 +00008526
8527 return true;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008528 }
8529
Artem Belevich94a55e82015-09-22 17:22:59 +00008530 if (S.getLangOpts().CUDA && S.getLangOpts().CUDATargetOverloads &&
8531 Cand1.Function && Cand2.Function) {
8532 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
8533 return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
8534 S.IdentifyCUDAPreference(Caller, Cand2.Function);
8535 }
8536
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008537 return false;
8538}
8539
Mike Stump11289f42009-09-09 15:08:12 +00008540/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008541/// within an overload candidate set.
8542///
James Dennettffad8b72012-06-22 08:10:18 +00008543/// \param Loc The location of the function name (or operator symbol) for
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008544/// which overload resolution occurs.
8545///
James Dennettffad8b72012-06-22 08:10:18 +00008546/// \param Best If overload resolution was successful or found a deleted
8547/// function, \p Best points to the candidate function found.
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008548///
8549/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00008550OverloadingResult
8551OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00008552 iterator &Best,
Chandler Carruth30141632011-02-25 19:41:05 +00008553 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008554 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00008555 Best = end();
8556 for (iterator Cand = begin(); Cand != end(); ++Cand) {
8557 if (Cand->Viable)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008558 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00008559 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008560 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008561 }
8562
8563 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00008564 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008565 return OR_No_Viable_Function;
8566
8567 // Make sure that this function is better than every other viable
8568 // function. If not, we have an ambiguity.
John McCall5c32be02010-08-24 20:38:10 +00008569 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00008570 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008571 Cand != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008572 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00008573 UserDefinedConversion)) {
John McCall5c32be02010-08-24 20:38:10 +00008574 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008575 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00008576 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008577 }
Mike Stump11289f42009-09-09 15:08:12 +00008578
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008579 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00008580 if (Best->Function &&
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00008581 (Best->Function->isDeleted() ||
8582 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor171c45a2009-02-18 21:56:37 +00008583 return OR_Deleted;
8584
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008585 return OR_Success;
8586}
8587
John McCall53262c92010-01-12 02:15:36 +00008588namespace {
8589
8590enum OverloadCandidateKind {
8591 oc_function,
8592 oc_method,
8593 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00008594 oc_function_template,
8595 oc_method_template,
8596 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00008597 oc_implicit_default_constructor,
8598 oc_implicit_copy_constructor,
Alexis Hunt119c10e2011-05-25 23:16:36 +00008599 oc_implicit_move_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00008600 oc_implicit_copy_assignment,
Alexis Hunt119c10e2011-05-25 23:16:36 +00008601 oc_implicit_move_assignment,
Sebastian Redl08905022011-02-05 19:23:19 +00008602 oc_implicit_inherited_constructor
John McCall53262c92010-01-12 02:15:36 +00008603};
8604
John McCalle1ac8d12010-01-13 00:25:19 +00008605OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
8606 FunctionDecl *Fn,
8607 std::string &Description) {
8608 bool isTemplate = false;
8609
8610 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
8611 isTemplate = true;
8612 Description = S.getTemplateArgumentBindingsText(
8613 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
8614 }
John McCallfd0b2f82010-01-06 09:43:14 +00008615
8616 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00008617 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00008618 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00008619
Sebastian Redl08905022011-02-05 19:23:19 +00008620 if (Ctor->getInheritedConstructor())
8621 return oc_implicit_inherited_constructor;
8622
Alexis Hunt119c10e2011-05-25 23:16:36 +00008623 if (Ctor->isDefaultConstructor())
8624 return oc_implicit_default_constructor;
8625
8626 if (Ctor->isMoveConstructor())
8627 return oc_implicit_move_constructor;
8628
8629 assert(Ctor->isCopyConstructor() &&
8630 "unexpected sort of implicit constructor");
8631 return oc_implicit_copy_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00008632 }
8633
8634 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
8635 // This actually gets spelled 'candidate function' for now, but
8636 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00008637 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00008638 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00008639
Alexis Hunt119c10e2011-05-25 23:16:36 +00008640 if (Meth->isMoveAssignmentOperator())
8641 return oc_implicit_move_assignment;
8642
Douglas Gregor12695102012-02-10 08:36:38 +00008643 if (Meth->isCopyAssignmentOperator())
8644 return oc_implicit_copy_assignment;
8645
8646 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
8647 return oc_method;
John McCall53262c92010-01-12 02:15:36 +00008648 }
8649
John McCalle1ac8d12010-01-13 00:25:19 +00008650 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00008651}
8652
Larisse Voufo98b20f12013-07-19 23:00:19 +00008653void MaybeEmitInheritedConstructorNote(Sema &S, Decl *Fn) {
Sebastian Redl08905022011-02-05 19:23:19 +00008654 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
8655 if (!Ctor) return;
8656
8657 Ctor = Ctor->getInheritedConstructor();
8658 if (!Ctor) return;
8659
8660 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
8661}
8662
John McCall53262c92010-01-12 02:15:36 +00008663} // end anonymous namespace
8664
8665// Notes the location of an overload candidate.
Richard Trieucaff2472011-11-23 22:32:32 +00008666void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
John McCalle1ac8d12010-01-13 00:25:19 +00008667 std::string FnDesc;
8668 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieucaff2472011-11-23 22:32:32 +00008669 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
8670 << (unsigned) K << FnDesc;
8671 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
8672 Diag(Fn->getLocation(), PD);
Sebastian Redl08905022011-02-05 19:23:19 +00008673 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallfd0b2f82010-01-06 09:43:14 +00008674}
8675
Nick Lewyckyed4265c2013-09-22 10:06:01 +00008676// Notes the location of all overload candidates designated through
Douglas Gregorb491ed32011-02-19 21:32:49 +00008677// OverloadedExpr
Richard Trieucaff2472011-11-23 22:32:32 +00008678void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008679 assert(OverloadedExpr->getType() == Context.OverloadTy);
8680
8681 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
8682 OverloadExpr *OvlExpr = Ovl.Expression;
8683
8684 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8685 IEnd = OvlExpr->decls_end();
8686 I != IEnd; ++I) {
8687 if (FunctionTemplateDecl *FunTmpl =
8688 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieucaff2472011-11-23 22:32:32 +00008689 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008690 } else if (FunctionDecl *Fun
8691 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieucaff2472011-11-23 22:32:32 +00008692 NoteOverloadCandidate(Fun, DestType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008693 }
8694 }
8695}
8696
John McCall0d1da222010-01-12 00:44:57 +00008697/// Diagnoses an ambiguous conversion. The partial diagnostic is the
8698/// "lead" diagnostic; it will be given two arguments, the source and
8699/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00008700void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
8701 Sema &S,
8702 SourceLocation CaretLoc,
8703 const PartialDiagnostic &PDiag) const {
8704 S.Diag(CaretLoc, PDiag)
8705 << Ambiguous.getFromType() << Ambiguous.getToType();
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00008706 // FIXME: The note limiting machinery is borrowed from
8707 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
8708 // refactoring here.
8709 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
8710 unsigned CandsShown = 0;
8711 AmbiguousConversionSequence::const_iterator I, E;
8712 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
8713 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
8714 break;
8715 ++CandsShown;
John McCall5c32be02010-08-24 20:38:10 +00008716 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00008717 }
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00008718 if (I != E)
8719 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
John McCall12f97bc2010-01-08 04:41:39 +00008720}
8721
Richard Smith17c00b42014-11-12 01:24:00 +00008722static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
8723 unsigned I) {
John McCall6a61b522010-01-13 09:16:55 +00008724 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
8725 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00008726 assert(Cand->Function && "for now, candidate must be a function");
8727 FunctionDecl *Fn = Cand->Function;
8728
8729 // There's a conversion slot for the object argument if this is a
8730 // non-constructor method. Note that 'I' corresponds the
8731 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00008732 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00008733 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00008734 if (I == 0)
8735 isObjectArgument = true;
8736 else
8737 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00008738 }
8739
John McCalle1ac8d12010-01-13 00:25:19 +00008740 std::string FnDesc;
8741 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8742
John McCall6a61b522010-01-13 09:16:55 +00008743 Expr *FromExpr = Conv.Bad.FromExpr;
8744 QualType FromTy = Conv.Bad.getFromType();
8745 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00008746
John McCallfb7ad0f2010-02-02 02:42:52 +00008747 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00008748 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00008749 Expr *E = FromExpr->IgnoreParens();
8750 if (isa<UnaryOperator>(E))
8751 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00008752 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00008753
8754 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
8755 << (unsigned) FnKind << FnDesc
8756 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8757 << ToTy << Name << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008758 MaybeEmitInheritedConstructorNote(S, Fn);
John McCallfb7ad0f2010-02-02 02:42:52 +00008759 return;
8760 }
8761
John McCall6d174642010-01-23 08:10:49 +00008762 // Do some hand-waving analysis to see if the non-viability is due
8763 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00008764 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
8765 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
8766 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
8767 CToTy = RT->getPointeeType();
8768 else {
8769 // TODO: detect and diagnose the full richness of const mismatches.
8770 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
8771 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
8772 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
8773 }
8774
8775 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
8776 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall47000992010-01-14 03:28:57 +00008777 Qualifiers FromQs = CFromTy.getQualifiers();
8778 Qualifiers ToQs = CToTy.getQualifiers();
8779
8780 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
8781 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
8782 << (unsigned) FnKind << FnDesc
8783 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8784 << FromTy
8785 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
8786 << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008787 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00008788 return;
8789 }
8790
John McCall31168b02011-06-15 23:02:42 +00008791 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00008792 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCall31168b02011-06-15 23:02:42 +00008793 << (unsigned) FnKind << FnDesc
8794 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8795 << FromTy
8796 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
8797 << (unsigned) isObjectArgument << I+1;
8798 MaybeEmitInheritedConstructorNote(S, Fn);
8799 return;
8800 }
8801
Douglas Gregoraec25842011-04-26 23:16:46 +00008802 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
8803 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
8804 << (unsigned) FnKind << FnDesc
8805 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8806 << FromTy
8807 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
8808 << (unsigned) isObjectArgument << I+1;
8809 MaybeEmitInheritedConstructorNote(S, Fn);
8810 return;
8811 }
8812
John McCall47000992010-01-14 03:28:57 +00008813 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
8814 assert(CVR && "unexpected qualifiers mismatch");
8815
8816 if (isObjectArgument) {
8817 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
8818 << (unsigned) FnKind << FnDesc
8819 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8820 << FromTy << (CVR - 1);
8821 } else {
8822 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
8823 << (unsigned) FnKind << FnDesc
8824 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8825 << FromTy << (CVR - 1) << I+1;
8826 }
Sebastian Redl08905022011-02-05 19:23:19 +00008827 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00008828 return;
8829 }
8830
Sebastian Redla72462c2011-09-24 17:48:32 +00008831 // Special diagnostic for failure to convert an initializer list, since
8832 // telling the user that it has type void is not useful.
8833 if (FromExpr && isa<InitListExpr>(FromExpr)) {
8834 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
8835 << (unsigned) FnKind << FnDesc
8836 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8837 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8838 MaybeEmitInheritedConstructorNote(S, Fn);
8839 return;
8840 }
8841
John McCall6d174642010-01-23 08:10:49 +00008842 // Diagnose references or pointers to incomplete types differently,
8843 // since it's far from impossible that the incompleteness triggered
8844 // the failure.
8845 QualType TempFromTy = FromTy.getNonReferenceType();
8846 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
8847 TempFromTy = PTy->getPointeeType();
8848 if (TempFromTy->isIncompleteType()) {
8849 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
8850 << (unsigned) FnKind << FnDesc
8851 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8852 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008853 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6d174642010-01-23 08:10:49 +00008854 return;
8855 }
8856
Douglas Gregor56f2e342010-06-30 23:01:39 +00008857 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008858 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00008859 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
8860 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
8861 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8862 FromPtrTy->getPointeeType()) &&
8863 !FromPtrTy->getPointeeType()->isIncompleteType() &&
8864 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008865 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00008866 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008867 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00008868 }
8869 } else if (const ObjCObjectPointerType *FromPtrTy
8870 = FromTy->getAs<ObjCObjectPointerType>()) {
8871 if (const ObjCObjectPointerType *ToPtrTy
8872 = ToTy->getAs<ObjCObjectPointerType>())
8873 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
8874 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
8875 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8876 FromPtrTy->getPointeeType()) &&
8877 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008878 BaseToDerivedConversion = 2;
8879 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00008880 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8881 !FromTy->isIncompleteType() &&
8882 !ToRefTy->getPointeeType()->isIncompleteType() &&
8883 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
8884 BaseToDerivedConversion = 3;
8885 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
8886 ToTy.getNonReferenceType().getCanonicalType() ==
8887 FromTy.getNonReferenceType().getCanonicalType()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00008888 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
8889 << (unsigned) FnKind << FnDesc
8890 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8891 << (unsigned) isObjectArgument << I + 1;
8892 MaybeEmitInheritedConstructorNote(S, Fn);
8893 return;
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008894 }
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00008895 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008896
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008897 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008898 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008899 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00008900 << (unsigned) FnKind << FnDesc
8901 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008902 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008903 << FromTy << ToTy << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008904 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor56f2e342010-06-30 23:01:39 +00008905 return;
8906 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008907
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00008908 if (isa<ObjCObjectPointerType>(CFromTy) &&
8909 isa<PointerType>(CToTy)) {
8910 Qualifiers FromQs = CFromTy.getQualifiers();
8911 Qualifiers ToQs = CToTy.getQualifiers();
8912 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8913 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8914 << (unsigned) FnKind << FnDesc
8915 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8916 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8917 MaybeEmitInheritedConstructorNote(S, Fn);
8918 return;
8919 }
8920 }
8921
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008922 // Emit the generic diagnostic and, optionally, add the hints to it.
8923 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8924 FDiag << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00008925 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008926 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8927 << (unsigned) (Cand->Fix.Kind);
8928
8929 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer490afa62012-01-14 21:05:10 +00008930 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8931 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008932 FDiag << *HI;
8933 S.Diag(Fn->getLocation(), FDiag);
8934
Sebastian Redl08905022011-02-05 19:23:19 +00008935 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6a61b522010-01-13 09:16:55 +00008936}
8937
Larisse Voufo98b20f12013-07-19 23:00:19 +00008938/// Additional arity mismatch diagnosis specific to a function overload
8939/// candidates. This is not covered by the more general DiagnoseArityMismatch()
8940/// over a candidate in any candidate set.
Richard Smith17c00b42014-11-12 01:24:00 +00008941static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
8942 unsigned NumArgs) {
John McCall6a61b522010-01-13 09:16:55 +00008943 FunctionDecl *Fn = Cand->Function;
John McCall6a61b522010-01-13 09:16:55 +00008944 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008945
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00008946 // With invalid overloaded operators, it's possible that we think we
Larisse Voufo98b20f12013-07-19 23:00:19 +00008947 // have an arity mismatch when in fact it looks like we have the
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00008948 // right number of arguments, because only overloaded operators have
8949 // the weird behavior of overloading member and non-member functions.
8950 // Just don't report anything.
8951 if (Fn->isInvalidDecl() &&
8952 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
Larisse Voufo98b20f12013-07-19 23:00:19 +00008953 return true;
8954
8955 if (NumArgs < MinParams) {
8956 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8957 (Cand->FailureKind == ovl_fail_bad_deduction &&
8958 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
8959 } else {
8960 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8961 (Cand->FailureKind == ovl_fail_bad_deduction &&
8962 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
8963 }
8964
8965 return false;
8966}
8967
8968/// General arity mismatch diagnosis over a candidate in a candidate set.
Richard Smith17c00b42014-11-12 01:24:00 +00008969static void DiagnoseArityMismatch(Sema &S, Decl *D, unsigned NumFormalArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00008970 assert(isa<FunctionDecl>(D) &&
8971 "The templated declaration should at least be a function"
8972 " when diagnosing bad template argument deduction due to too many"
8973 " or too few arguments");
8974
8975 FunctionDecl *Fn = cast<FunctionDecl>(D);
8976
8977 // TODO: treat calls to a missing default constructor as a special case
8978 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8979 unsigned MinParams = Fn->getMinRequiredArguments();
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00008980
John McCall6a61b522010-01-13 09:16:55 +00008981 // at least / at most / exactly
8982 unsigned mode, modeCount;
8983 if (NumFormalArgs < MinParams) {
Alp Toker9cacbab2014-01-20 20:26:09 +00008984 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
8985 FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00008986 mode = 0; // "at least"
8987 else
8988 mode = 2; // "exactly"
8989 modeCount = MinParams;
8990 } else {
Alp Toker9cacbab2014-01-20 20:26:09 +00008991 if (MinParams != FnTy->getNumParams())
John McCall6a61b522010-01-13 09:16:55 +00008992 mode = 1; // "at most"
8993 else
8994 mode = 2; // "exactly"
Alp Toker9cacbab2014-01-20 20:26:09 +00008995 modeCount = FnTy->getNumParams();
John McCall6a61b522010-01-13 09:16:55 +00008996 }
8997
8998 std::string Description;
8999 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
9000
Richard Smith10ff50d2012-05-11 05:16:41 +00009001 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
9002 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
Craig Topperc3ec1492014-05-26 06:22:03 +00009003 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9004 << mode << Fn->getParamDecl(0) << NumFormalArgs;
Richard Smith10ff50d2012-05-11 05:16:41 +00009005 else
9006 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Craig Topperc3ec1492014-05-26 06:22:03 +00009007 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9008 << mode << modeCount << NumFormalArgs;
Sebastian Redl08905022011-02-05 19:23:19 +00009009 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009010}
9011
Larisse Voufo98b20f12013-07-19 23:00:19 +00009012/// Arity mismatch diagnosis specific to a function overload candidate.
Richard Smith17c00b42014-11-12 01:24:00 +00009013static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
9014 unsigned NumFormalArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009015 if (!CheckArityMismatch(S, Cand, NumFormalArgs))
9016 DiagnoseArityMismatch(S, Cand->Function, NumFormalArgs);
9017}
Larisse Voufo47c08452013-07-19 22:53:23 +00009018
Richard Smith17c00b42014-11-12 01:24:00 +00009019static TemplateDecl *getDescribedTemplate(Decl *Templated) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009020 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Templated))
9021 return FD->getDescribedFunctionTemplate();
9022 else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Templated))
9023 return RD->getDescribedClassTemplate();
9024
9025 llvm_unreachable("Unsupported: Getting the described template declaration"
9026 " for bad deduction diagnosis");
9027}
9028
9029/// Diagnose a failed template-argument deduction.
Richard Smith17c00b42014-11-12 01:24:00 +00009030static void DiagnoseBadDeduction(Sema &S, Decl *Templated,
9031 DeductionFailureInfo &DeductionFailure,
9032 unsigned NumArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009033 TemplateParameter Param = DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009034 NamedDecl *ParamD;
9035 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
9036 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
9037 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
Larisse Voufo98b20f12013-07-19 23:00:19 +00009038 switch (DeductionFailure.Result) {
John McCall8b9ed552010-02-01 18:53:26 +00009039 case Sema::TDK_Success:
9040 llvm_unreachable("TDK_success while diagnosing bad deduction");
9041
9042 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00009043 assert(ParamD && "no parameter found for incomplete deduction result");
Larisse Voufo98b20f12013-07-19 23:00:19 +00009044 S.Diag(Templated->getLocation(),
9045 diag::note_ovl_candidate_incomplete_deduction)
9046 << ParamD->getDeclName();
9047 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall8b9ed552010-02-01 18:53:26 +00009048 return;
9049 }
9050
John McCall42d7d192010-08-05 09:05:08 +00009051 case Sema::TDK_Underqualified: {
9052 assert(ParamD && "no parameter found for bad qualifiers deduction result");
9053 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
9054
Larisse Voufo98b20f12013-07-19 23:00:19 +00009055 QualType Param = DeductionFailure.getFirstArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00009056
9057 // Param will have been canonicalized, but it should just be a
9058 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00009059 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00009060 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00009061 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00009062 assert(S.Context.hasSameType(Param, NonCanonParam));
9063
9064 // Arg has also been canonicalized, but there's nothing we can do
9065 // about that. It also doesn't matter as much, because it won't
9066 // have any template parameters in it (because deduction isn't
9067 // done on dependent types).
Larisse Voufo98b20f12013-07-19 23:00:19 +00009068 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00009069
Larisse Voufo98b20f12013-07-19 23:00:19 +00009070 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
9071 << ParamD->getDeclName() << Arg << NonCanonParam;
9072 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall42d7d192010-08-05 09:05:08 +00009073 return;
9074 }
9075
9076 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00009077 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009078 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009079 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009080 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009081 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009082 which = 1;
9083 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009084 which = 2;
9085 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009086
Larisse Voufo98b20f12013-07-19 23:00:19 +00009087 S.Diag(Templated->getLocation(),
9088 diag::note_ovl_candidate_inconsistent_deduction)
9089 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
9090 << *DeductionFailure.getSecondArg();
9091 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009092 return;
9093 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00009094
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009095 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009096 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009097 if (ParamD->getDeclName())
Larisse Voufo98b20f12013-07-19 23:00:19 +00009098 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009099 diag::note_ovl_candidate_explicit_arg_mismatch_named)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009100 << ParamD->getDeclName();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009101 else {
9102 int index = 0;
9103 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
9104 index = TTP->getIndex();
9105 else if (NonTypeTemplateParmDecl *NTTP
9106 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
9107 index = NTTP->getIndex();
9108 else
9109 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
Larisse Voufo98b20f12013-07-19 23:00:19 +00009110 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009111 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009112 << (index + 1);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009113 }
Larisse Voufo98b20f12013-07-19 23:00:19 +00009114 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009115 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009116
Douglas Gregor02eb4832010-05-08 18:13:28 +00009117 case Sema::TDK_TooManyArguments:
9118 case Sema::TDK_TooFewArguments:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009119 DiagnoseArityMismatch(S, Templated, NumArgs);
Douglas Gregor02eb4832010-05-08 18:13:28 +00009120 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00009121
9122 case Sema::TDK_InstantiationDepth:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009123 S.Diag(Templated->getLocation(),
9124 diag::note_ovl_candidate_instantiation_depth);
9125 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregord09efd42010-05-08 20:07:26 +00009126 return;
9127
9128 case Sema::TDK_SubstitutionFailure: {
Richard Smith9ca64612012-05-07 09:03:25 +00009129 // Format the template argument list into the argument string.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009130 SmallString<128> TemplateArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00009131 if (TemplateArgumentList *Args =
Larisse Voufo98b20f12013-07-19 23:00:19 +00009132 DeductionFailure.getTemplateArgumentList()) {
Richard Smith9ca64612012-05-07 09:03:25 +00009133 TemplateArgString = " ";
9134 TemplateArgString += S.getTemplateArgumentBindingsText(
Larisse Voufo98b20f12013-07-19 23:00:19 +00009135 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
Richard Smith9ca64612012-05-07 09:03:25 +00009136 }
9137
Richard Smith6f8d2c62012-05-09 05:17:00 +00009138 // If this candidate was disabled by enable_if, say so.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009139 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
Richard Smith6f8d2c62012-05-09 05:17:00 +00009140 if (PDiag && PDiag->second.getDiagID() ==
9141 diag::err_typename_nested_not_found_enable_if) {
9142 // FIXME: Use the source range of the condition, and the fully-qualified
9143 // name of the enable_if template. These are both present in PDiag.
9144 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
9145 << "'enable_if'" << TemplateArgString;
9146 return;
9147 }
9148
Richard Smith9ca64612012-05-07 09:03:25 +00009149 // Format the SFINAE diagnostic into the argument string.
9150 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
9151 // formatted message in another diagnostic.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009152 SmallString<128> SFINAEArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00009153 SourceRange R;
Richard Smith6f8d2c62012-05-09 05:17:00 +00009154 if (PDiag) {
Richard Smith9ca64612012-05-07 09:03:25 +00009155 SFINAEArgString = ": ";
9156 R = SourceRange(PDiag->first, PDiag->first);
9157 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
9158 }
9159
Larisse Voufo98b20f12013-07-19 23:00:19 +00009160 S.Diag(Templated->getLocation(),
9161 diag::note_ovl_candidate_substitution_failure)
9162 << TemplateArgString << SFINAEArgString << R;
9163 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregord09efd42010-05-08 20:07:26 +00009164 return;
9165 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009166
Richard Smith8c6eeb92013-01-31 04:03:12 +00009167 case Sema::TDK_FailedOverloadResolution: {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009168 OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr());
9169 S.Diag(Templated->getLocation(),
Richard Smith8c6eeb92013-01-31 04:03:12 +00009170 diag::note_ovl_candidate_failed_overload_resolution)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009171 << R.Expression->getName();
Richard Smith8c6eeb92013-01-31 04:03:12 +00009172 return;
9173 }
9174
Richard Trieue3732352013-04-08 21:11:40 +00009175 case Sema::TDK_NonDeducedMismatch: {
Richard Smith44ecdbd2013-01-31 05:19:49 +00009176 // FIXME: Provide a source location to indicate what we couldn't match.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009177 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
9178 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
Richard Trieue3732352013-04-08 21:11:40 +00009179 if (FirstTA.getKind() == TemplateArgument::Template &&
9180 SecondTA.getKind() == TemplateArgument::Template) {
9181 TemplateName FirstTN = FirstTA.getAsTemplate();
9182 TemplateName SecondTN = SecondTA.getAsTemplate();
9183 if (FirstTN.getKind() == TemplateName::Template &&
9184 SecondTN.getKind() == TemplateName::Template) {
9185 if (FirstTN.getAsTemplateDecl()->getName() ==
9186 SecondTN.getAsTemplateDecl()->getName()) {
9187 // FIXME: This fixes a bad diagnostic where both templates are named
9188 // the same. This particular case is a bit difficult since:
9189 // 1) It is passed as a string to the diagnostic printer.
9190 // 2) The diagnostic printer only attempts to find a better
9191 // name for types, not decls.
9192 // Ideally, this should folded into the diagnostic printer.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009193 S.Diag(Templated->getLocation(),
Richard Trieue3732352013-04-08 21:11:40 +00009194 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
9195 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
9196 return;
9197 }
9198 }
9199 }
Faisal Vali2b391ab2013-09-26 19:54:12 +00009200 // FIXME: For generic lambda parameters, check if the function is a lambda
9201 // call operator, and if so, emit a prettier and more informative
9202 // diagnostic that mentions 'auto' and lambda in addition to
9203 // (or instead of?) the canonical template type parameters.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009204 S.Diag(Templated->getLocation(),
9205 diag::note_ovl_candidate_non_deduced_mismatch)
9206 << FirstTA << SecondTA;
Richard Smith44ecdbd2013-01-31 05:19:49 +00009207 return;
Richard Trieue3732352013-04-08 21:11:40 +00009208 }
John McCall8b9ed552010-02-01 18:53:26 +00009209 // TODO: diagnose these individually, then kill off
9210 // note_ovl_candidate_bad_deduction, which is uselessly vague.
Richard Smith44ecdbd2013-01-31 05:19:49 +00009211 case Sema::TDK_MiscellaneousDeductionFailure:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009212 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
9213 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall8b9ed552010-02-01 18:53:26 +00009214 return;
9215 }
9216}
9217
Larisse Voufo98b20f12013-07-19 23:00:19 +00009218/// Diagnose a failed template-argument deduction, for function calls.
Richard Smith17c00b42014-11-12 01:24:00 +00009219static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
9220 unsigned NumArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009221 unsigned TDK = Cand->DeductionFailure.Result;
9222 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
9223 if (CheckArityMismatch(S, Cand, NumArgs))
9224 return;
9225 }
9226 DiagnoseBadDeduction(S, Cand->Function, // pattern
9227 Cand->DeductionFailure, NumArgs);
9228}
9229
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009230/// CUDA: diagnose an invalid call across targets.
Richard Smith17c00b42014-11-12 01:24:00 +00009231static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009232 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
9233 FunctionDecl *Callee = Cand->Function;
9234
9235 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
9236 CalleeTarget = S.IdentifyCUDATarget(Callee);
9237
9238 std::string FnDesc;
9239 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
9240
9241 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
Eli Bendersky9a220fc2014-09-29 20:38:29 +00009242 << (unsigned)FnKind << CalleeTarget << CallerTarget;
9243
9244 // This could be an implicit constructor for which we could not infer the
9245 // target due to a collsion. Diagnose that case.
9246 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
9247 if (Meth != nullptr && Meth->isImplicit()) {
9248 CXXRecordDecl *ParentClass = Meth->getParent();
9249 Sema::CXXSpecialMember CSM;
9250
9251 switch (FnKind) {
9252 default:
9253 return;
9254 case oc_implicit_default_constructor:
9255 CSM = Sema::CXXDefaultConstructor;
9256 break;
9257 case oc_implicit_copy_constructor:
9258 CSM = Sema::CXXCopyConstructor;
9259 break;
9260 case oc_implicit_move_constructor:
9261 CSM = Sema::CXXMoveConstructor;
9262 break;
9263 case oc_implicit_copy_assignment:
9264 CSM = Sema::CXXCopyAssignment;
9265 break;
9266 case oc_implicit_move_assignment:
9267 CSM = Sema::CXXMoveAssignment;
9268 break;
9269 };
9270
9271 bool ConstRHS = false;
9272 if (Meth->getNumParams()) {
9273 if (const ReferenceType *RT =
9274 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
9275 ConstRHS = RT->getPointeeType().isConstQualified();
9276 }
9277 }
9278
9279 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
9280 /* ConstRHS */ ConstRHS,
9281 /* Diagnose */ true);
9282 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009283}
9284
Richard Smith17c00b42014-11-12 01:24:00 +00009285static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009286 FunctionDecl *Callee = Cand->Function;
9287 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
9288
9289 S.Diag(Callee->getLocation(),
9290 diag::note_ovl_candidate_disabled_by_enable_if_attr)
9291 << Attr->getCond()->getSourceRange() << Attr->getMessage();
9292}
9293
John McCall8b9ed552010-02-01 18:53:26 +00009294/// Generates a 'note' diagnostic for an overload candidate. We've
9295/// already generated a primary error at the call site.
9296///
9297/// It really does need to be a single diagnostic with its caret
9298/// pointed at the candidate declaration. Yes, this creates some
9299/// major challenges of technical writing. Yes, this makes pointing
9300/// out problems with specific arguments quite awkward. It's still
9301/// better than generating twenty screens of text for every failed
9302/// overload.
9303///
9304/// It would be great to be able to express per-candidate problems
9305/// more richly for those diagnostic clients that cared, but we'd
9306/// still have to be just as careful with the default diagnostics.
Richard Smith17c00b42014-11-12 01:24:00 +00009307static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
9308 unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00009309 FunctionDecl *Fn = Cand->Function;
9310
John McCall12f97bc2010-01-08 04:41:39 +00009311 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00009312 if (Cand->Viable && (Fn->isDeleted() ||
9313 S.isFunctionConsideredUnavailable(Fn))) {
John McCalle1ac8d12010-01-13 00:25:19 +00009314 std::string FnDesc;
9315 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00009316
9317 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
Richard Smith6f1e2c62012-04-02 20:59:25 +00009318 << FnKind << FnDesc
9319 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
Sebastian Redl08905022011-02-05 19:23:19 +00009320 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalld3224162010-01-08 00:58:21 +00009321 return;
John McCall12f97bc2010-01-08 04:41:39 +00009322 }
9323
John McCalle1ac8d12010-01-13 00:25:19 +00009324 // We don't really have anything else to say about viable candidates.
9325 if (Cand->Viable) {
9326 S.NoteOverloadCandidate(Fn);
9327 return;
9328 }
John McCall0d1da222010-01-12 00:44:57 +00009329
John McCall6a61b522010-01-13 09:16:55 +00009330 switch (Cand->FailureKind) {
9331 case ovl_fail_too_many_arguments:
9332 case ovl_fail_too_few_arguments:
9333 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00009334
John McCall6a61b522010-01-13 09:16:55 +00009335 case ovl_fail_bad_deduction:
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009336 return DiagnoseBadDeduction(S, Cand, NumArgs);
John McCall8b9ed552010-02-01 18:53:26 +00009337
John McCall578a1f82014-12-14 01:46:53 +00009338 case ovl_fail_illegal_constructor: {
9339 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
9340 << (Fn->getPrimaryTemplate() ? 1 : 0);
9341 MaybeEmitInheritedConstructorNote(S, Fn);
9342 return;
9343 }
9344
John McCallfe796dd2010-01-23 05:17:32 +00009345 case ovl_fail_trivial_conversion:
9346 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00009347 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00009348 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009349
John McCall65eb8792010-02-25 01:37:24 +00009350 case ovl_fail_bad_conversion: {
9351 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009352 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00009353 if (Cand->Conversions[I].isBad())
9354 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009355
John McCall6a61b522010-01-13 09:16:55 +00009356 // FIXME: this currently happens when we're called from SemaInit
9357 // when user-conversion overload fails. Figure out how to handle
9358 // those conditions and diagnose them well.
9359 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009360 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009361
9362 case ovl_fail_bad_target:
9363 return DiagnoseBadTarget(S, Cand);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009364
9365 case ovl_fail_enable_if:
9366 return DiagnoseFailedEnableIfAttr(S, Cand);
John McCall65eb8792010-02-25 01:37:24 +00009367 }
John McCalld3224162010-01-08 00:58:21 +00009368}
9369
Richard Smith17c00b42014-11-12 01:24:00 +00009370static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
John McCalld3224162010-01-08 00:58:21 +00009371 // Desugar the type of the surrogate down to a function type,
9372 // retaining as many typedefs as possible while still showing
9373 // the function type (and, therefore, its parameter types).
9374 QualType FnType = Cand->Surrogate->getConversionType();
9375 bool isLValueReference = false;
9376 bool isRValueReference = false;
9377 bool isPointer = false;
9378 if (const LValueReferenceType *FnTypeRef =
9379 FnType->getAs<LValueReferenceType>()) {
9380 FnType = FnTypeRef->getPointeeType();
9381 isLValueReference = true;
9382 } else if (const RValueReferenceType *FnTypeRef =
9383 FnType->getAs<RValueReferenceType>()) {
9384 FnType = FnTypeRef->getPointeeType();
9385 isRValueReference = true;
9386 }
9387 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
9388 FnType = FnTypePtr->getPointeeType();
9389 isPointer = true;
9390 }
9391 // Desugar down to a function type.
9392 FnType = QualType(FnType->getAs<FunctionType>(), 0);
9393 // Reconstruct the pointer/reference as appropriate.
9394 if (isPointer) FnType = S.Context.getPointerType(FnType);
9395 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
9396 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
9397
9398 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
9399 << FnType;
Sebastian Redl08905022011-02-05 19:23:19 +00009400 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalld3224162010-01-08 00:58:21 +00009401}
9402
Richard Smith17c00b42014-11-12 01:24:00 +00009403static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
9404 SourceLocation OpLoc,
9405 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00009406 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalld3224162010-01-08 00:58:21 +00009407 std::string TypeStr("operator");
9408 TypeStr += Opc;
9409 TypeStr += "(";
9410 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramerb0095172012-01-14 16:32:05 +00009411 if (Cand->NumConversions == 1) {
John McCalld3224162010-01-08 00:58:21 +00009412 TypeStr += ")";
9413 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
9414 } else {
9415 TypeStr += ", ";
9416 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
9417 TypeStr += ")";
9418 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
9419 }
9420}
9421
Richard Smith17c00b42014-11-12 01:24:00 +00009422static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
9423 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00009424 unsigned NoOperands = Cand->NumConversions;
John McCalld3224162010-01-08 00:58:21 +00009425 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
9426 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00009427 if (ICS.isBad()) break; // all meaningless after first invalid
9428 if (!ICS.isAmbiguous()) continue;
9429
John McCall5c32be02010-08-24 20:38:10 +00009430 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00009431 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00009432 }
9433}
9434
Larisse Voufo98b20f12013-07-19 23:00:19 +00009435static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
John McCall3712d9e2010-01-15 23:32:50 +00009436 if (Cand->Function)
9437 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00009438 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00009439 return Cand->Surrogate->getLocation();
9440 return SourceLocation();
9441}
9442
Larisse Voufo98b20f12013-07-19 23:00:19 +00009443static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
Chandler Carruth73fddfe2011-09-10 00:51:24 +00009444 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009445 case Sema::TDK_Success:
David Blaikie83d382b2011-09-23 05:06:16 +00009446 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00009447
Douglas Gregorc5c01a62012-09-13 21:01:57 +00009448 case Sema::TDK_Invalid:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009449 case Sema::TDK_Incomplete:
9450 return 1;
9451
9452 case Sema::TDK_Underqualified:
9453 case Sema::TDK_Inconsistent:
9454 return 2;
9455
9456 case Sema::TDK_SubstitutionFailure:
9457 case Sema::TDK_NonDeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +00009458 case Sema::TDK_MiscellaneousDeductionFailure:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009459 return 3;
9460
9461 case Sema::TDK_InstantiationDepth:
9462 case Sema::TDK_FailedOverloadResolution:
9463 return 4;
9464
9465 case Sema::TDK_InvalidExplicitArguments:
9466 return 5;
9467
9468 case Sema::TDK_TooManyArguments:
9469 case Sema::TDK_TooFewArguments:
9470 return 6;
9471 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00009472 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009473}
9474
Richard Smith17c00b42014-11-12 01:24:00 +00009475namespace {
John McCallad2587a2010-01-12 00:48:53 +00009476struct CompareOverloadCandidatesForDisplay {
9477 Sema &S;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009478 size_t NumArgs;
9479
9480 CompareOverloadCandidatesForDisplay(Sema &S, size_t nArgs)
9481 : S(S), NumArgs(nArgs) {}
John McCall12f97bc2010-01-08 04:41:39 +00009482
9483 bool operator()(const OverloadCandidate *L,
9484 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00009485 // Fast-path this check.
9486 if (L == R) return false;
9487
John McCall12f97bc2010-01-08 04:41:39 +00009488 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00009489 if (L->Viable) {
9490 if (!R->Viable) return true;
9491
9492 // TODO: introduce a tri-valued comparison for overload
9493 // candidates. Would be more worthwhile if we had a sort
9494 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00009495 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
9496 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00009497 } else if (R->Viable)
9498 return false;
John McCall12f97bc2010-01-08 04:41:39 +00009499
John McCall3712d9e2010-01-15 23:32:50 +00009500 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00009501
John McCall3712d9e2010-01-15 23:32:50 +00009502 // Criteria by which we can sort non-viable candidates:
9503 if (!L->Viable) {
9504 // 1. Arity mismatches come after other candidates.
9505 if (L->FailureKind == ovl_fail_too_many_arguments ||
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009506 L->FailureKind == ovl_fail_too_few_arguments) {
9507 if (R->FailureKind == ovl_fail_too_many_arguments ||
9508 R->FailureKind == ovl_fail_too_few_arguments) {
Kaelyn Takata50c4ffc2014-05-07 00:43:38 +00009509 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
9510 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
9511 if (LDist == RDist) {
9512 if (L->FailureKind == R->FailureKind)
9513 // Sort non-surrogates before surrogates.
9514 return !L->IsSurrogate && R->IsSurrogate;
9515 // Sort candidates requiring fewer parameters than there were
9516 // arguments given after candidates requiring more parameters
9517 // than there were arguments given.
9518 return L->FailureKind == ovl_fail_too_many_arguments;
9519 }
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009520 return LDist < RDist;
9521 }
John McCall3712d9e2010-01-15 23:32:50 +00009522 return false;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009523 }
John McCall3712d9e2010-01-15 23:32:50 +00009524 if (R->FailureKind == ovl_fail_too_many_arguments ||
9525 R->FailureKind == ovl_fail_too_few_arguments)
9526 return true;
John McCall12f97bc2010-01-08 04:41:39 +00009527
John McCallfe796dd2010-01-23 05:17:32 +00009528 // 2. Bad conversions come first and are ordered by the number
9529 // of bad conversions and quality of good conversions.
9530 if (L->FailureKind == ovl_fail_bad_conversion) {
9531 if (R->FailureKind != ovl_fail_bad_conversion)
9532 return true;
9533
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009534 // The conversion that can be fixed with a smaller number of changes,
9535 // comes first.
9536 unsigned numLFixes = L->Fix.NumConversionsFixed;
9537 unsigned numRFixes = R->Fix.NumConversionsFixed;
9538 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
9539 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00009540 if (numLFixes != numRFixes) {
David Blaikie7a3cbb22015-03-09 02:02:07 +00009541 return numLFixes < numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00009542 }
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009543
John McCallfe796dd2010-01-23 05:17:32 +00009544 // If there's any ordering between the defined conversions...
9545 // FIXME: this might not be transitive.
Benjamin Kramerb0095172012-01-14 16:32:05 +00009546 assert(L->NumConversions == R->NumConversions);
John McCallfe796dd2010-01-23 05:17:32 +00009547
9548 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00009549 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009550 for (unsigned E = L->NumConversions; I != E; ++I) {
John McCall5c32be02010-08-24 20:38:10 +00009551 switch (CompareImplicitConversionSequences(S,
9552 L->Conversions[I],
9553 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00009554 case ImplicitConversionSequence::Better:
9555 leftBetter++;
9556 break;
9557
9558 case ImplicitConversionSequence::Worse:
9559 leftBetter--;
9560 break;
9561
9562 case ImplicitConversionSequence::Indistinguishable:
9563 break;
9564 }
9565 }
9566 if (leftBetter > 0) return true;
9567 if (leftBetter < 0) return false;
9568
9569 } else if (R->FailureKind == ovl_fail_bad_conversion)
9570 return false;
9571
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009572 if (L->FailureKind == ovl_fail_bad_deduction) {
9573 if (R->FailureKind != ovl_fail_bad_deduction)
9574 return true;
9575
9576 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9577 return RankDeductionFailure(L->DeductionFailure)
Eli Friedman1e7a0c62011-10-14 23:10:30 +00009578 < RankDeductionFailure(R->DeductionFailure);
Eli Friedmane2c600c2011-10-14 21:52:24 +00009579 } else if (R->FailureKind == ovl_fail_bad_deduction)
9580 return false;
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009581
John McCall3712d9e2010-01-15 23:32:50 +00009582 // TODO: others?
9583 }
9584
9585 // Sort everything else by location.
9586 SourceLocation LLoc = GetLocationForCandidate(L);
9587 SourceLocation RLoc = GetLocationForCandidate(R);
9588
9589 // Put candidates without locations (e.g. builtins) at the end.
9590 if (LLoc.isInvalid()) return false;
9591 if (RLoc.isInvalid()) return true;
9592
9593 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00009594 }
9595};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00009596}
John McCall12f97bc2010-01-08 04:41:39 +00009597
John McCallfe796dd2010-01-23 05:17:32 +00009598/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009599/// computes up to the first. Produces the FixIt set if possible.
Richard Smith17c00b42014-11-12 01:24:00 +00009600static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
9601 ArrayRef<Expr *> Args) {
John McCallfe796dd2010-01-23 05:17:32 +00009602 assert(!Cand->Viable);
9603
9604 // Don't do anything on failures other than bad conversion.
9605 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
9606
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009607 // We only want the FixIts if all the arguments can be corrected.
9608 bool Unfixable = false;
Anna Zaks1b068122011-07-28 19:46:48 +00009609 // Use a implicit copy initialization to check conversion fixes.
9610 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009611
John McCallfe796dd2010-01-23 05:17:32 +00009612 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00009613 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009614 unsigned ConvCount = Cand->NumConversions;
John McCallfe796dd2010-01-23 05:17:32 +00009615 while (true) {
9616 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
9617 ConvIdx++;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009618 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaks1b068122011-07-28 19:46:48 +00009619 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCallfe796dd2010-01-23 05:17:32 +00009620 break;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009621 }
John McCallfe796dd2010-01-23 05:17:32 +00009622 }
9623
9624 if (ConvIdx == ConvCount)
9625 return;
9626
John McCall65eb8792010-02-25 01:37:24 +00009627 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
9628 "remaining conversion is initialized?");
9629
Douglas Gregoradc7a702010-04-16 17:45:54 +00009630 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00009631 // operation somehow.
9632 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00009633
9634 const FunctionProtoType* Proto;
9635 unsigned ArgIdx = ConvIdx;
9636
9637 if (Cand->IsSurrogate) {
9638 QualType ConvType
9639 = Cand->Surrogate->getConversionType().getNonReferenceType();
9640 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9641 ConvType = ConvPtrType->getPointeeType();
9642 Proto = ConvType->getAs<FunctionProtoType>();
9643 ArgIdx--;
9644 } else if (Cand->Function) {
9645 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
9646 if (isa<CXXMethodDecl>(Cand->Function) &&
9647 !isa<CXXConstructorDecl>(Cand->Function))
9648 ArgIdx--;
9649 } else {
9650 // Builtin binary operator with a bad first conversion.
9651 assert(ConvCount <= 3);
9652 for (; ConvIdx != ConvCount; ++ConvIdx)
9653 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00009654 = TryCopyInitialization(S, Args[ConvIdx],
9655 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009656 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00009657 /*InOverloadResolution*/ true,
9658 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00009659 S.getLangOpts().ObjCAutoRefCount);
John McCallfe796dd2010-01-23 05:17:32 +00009660 return;
9661 }
9662
9663 // Fill in the rest of the conversions.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00009664 unsigned NumParams = Proto->getNumParams();
John McCallfe796dd2010-01-23 05:17:32 +00009665 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00009666 if (ArgIdx < NumParams) {
Alp Toker9cacbab2014-01-20 20:26:09 +00009667 Cand->Conversions[ConvIdx] = TryCopyInitialization(
9668 S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions,
9669 /*InOverloadResolution=*/true,
9670 /*AllowObjCWritebackConversion=*/
9671 S.getLangOpts().ObjCAutoRefCount);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009672 // Store the FixIt in the candidate if it exists.
9673 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaks1b068122011-07-28 19:46:48 +00009674 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009675 }
John McCallfe796dd2010-01-23 05:17:32 +00009676 else
9677 Cand->Conversions[ConvIdx].setEllipsis();
9678 }
9679}
9680
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009681/// PrintOverloadCandidates - When overload resolution fails, prints
9682/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00009683/// set.
John McCall5c32be02010-08-24 20:38:10 +00009684void OverloadCandidateSet::NoteCandidates(Sema &S,
9685 OverloadCandidateDisplayKind OCD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009686 ArrayRef<Expr *> Args,
David Blaikie1d202a62012-10-08 01:11:04 +00009687 StringRef Opc,
John McCall5c32be02010-08-24 20:38:10 +00009688 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00009689 // Sort the candidates by viability and position. Sorting directly would
9690 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009691 SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +00009692 if (OCD == OCD_AllCandidates) Cands.reserve(size());
9693 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +00009694 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00009695 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00009696 else if (OCD == OCD_AllCandidates) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009697 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009698 if (Cand->Function || Cand->IsSurrogate)
9699 Cands.push_back(Cand);
9700 // Otherwise, this a non-viable builtin candidate. We do not, in general,
9701 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00009702 }
9703 }
9704
John McCallad2587a2010-01-12 00:48:53 +00009705 std::sort(Cands.begin(), Cands.end(),
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009706 CompareOverloadCandidatesForDisplay(S, Args.size()));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009707
John McCall0d1da222010-01-12 00:44:57 +00009708 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00009709
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009710 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Douglas Gregor79591782012-10-23 23:11:23 +00009711 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009712 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00009713 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9714 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00009715
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009716 // Set an arbitrary limit on the number of candidate functions we'll spam
9717 // the user with. FIXME: This limit should depend on details of the
9718 // candidate list.
Douglas Gregor79591782012-10-23 23:11:23 +00009719 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009720 break;
9721 }
9722 ++CandsShown;
9723
John McCalld3224162010-01-08 00:58:21 +00009724 if (Cand->Function)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009725 NoteFunctionCandidate(S, Cand, Args.size());
John McCalld3224162010-01-08 00:58:21 +00009726 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +00009727 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009728 else {
9729 assert(Cand->Viable &&
9730 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00009731 // Generally we only see ambiguities including viable builtin
9732 // operators if overload resolution got screwed up by an
9733 // ambiguous user-defined conversion.
9734 //
9735 // FIXME: It's quite possible for different conversions to see
9736 // different ambiguities, though.
9737 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +00009738 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +00009739 ReportedAmbiguousConversions = true;
9740 }
John McCalld3224162010-01-08 00:58:21 +00009741
John McCall0d1da222010-01-12 00:44:57 +00009742 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +00009743 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00009744 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009745 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009746
9747 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +00009748 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009749}
9750
Larisse Voufo98b20f12013-07-19 23:00:19 +00009751static SourceLocation
9752GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
9753 return Cand->Specialization ? Cand->Specialization->getLocation()
9754 : SourceLocation();
9755}
9756
Richard Smith17c00b42014-11-12 01:24:00 +00009757namespace {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009758struct CompareTemplateSpecCandidatesForDisplay {
9759 Sema &S;
9760 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
9761
9762 bool operator()(const TemplateSpecCandidate *L,
9763 const TemplateSpecCandidate *R) {
9764 // Fast-path this check.
9765 if (L == R)
9766 return false;
9767
9768 // Assuming that both candidates are not matches...
9769
9770 // Sort by the ranking of deduction failures.
9771 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9772 return RankDeductionFailure(L->DeductionFailure) <
9773 RankDeductionFailure(R->DeductionFailure);
9774
9775 // Sort everything else by location.
9776 SourceLocation LLoc = GetLocationForCandidate(L);
9777 SourceLocation RLoc = GetLocationForCandidate(R);
9778
9779 // Put candidates without locations (e.g. builtins) at the end.
9780 if (LLoc.isInvalid())
9781 return false;
9782 if (RLoc.isInvalid())
9783 return true;
9784
9785 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
9786 }
9787};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00009788}
Larisse Voufo98b20f12013-07-19 23:00:19 +00009789
9790/// Diagnose a template argument deduction failure.
9791/// We are treating these failures as overload failures due to bad
9792/// deductions.
9793void TemplateSpecCandidate::NoteDeductionFailure(Sema &S) {
9794 DiagnoseBadDeduction(S, Specialization, // pattern
9795 DeductionFailure, /*NumArgs=*/0);
9796}
9797
9798void TemplateSpecCandidateSet::destroyCandidates() {
9799 for (iterator i = begin(), e = end(); i != e; ++i) {
9800 i->DeductionFailure.Destroy();
9801 }
9802}
9803
9804void TemplateSpecCandidateSet::clear() {
9805 destroyCandidates();
9806 Candidates.clear();
9807}
9808
9809/// NoteCandidates - When no template specialization match is found, prints
9810/// diagnostic messages containing the non-matching specializations that form
9811/// the candidate set.
9812/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
9813/// OCD == OCD_AllCandidates and Cand->Viable == false.
9814void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
9815 // Sort the candidates by position (assuming no candidate is a match).
9816 // Sorting directly would be prohibitive, so we make a set of pointers
9817 // and sort those.
9818 SmallVector<TemplateSpecCandidate *, 32> Cands;
9819 Cands.reserve(size());
9820 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
9821 if (Cand->Specialization)
9822 Cands.push_back(Cand);
Alp Tokerd4733632013-12-05 04:47:09 +00009823 // Otherwise, this is a non-matching builtin candidate. We do not,
Larisse Voufo98b20f12013-07-19 23:00:19 +00009824 // in general, want to list every possible builtin candidate.
9825 }
9826
9827 std::sort(Cands.begin(), Cands.end(),
9828 CompareTemplateSpecCandidatesForDisplay(S));
9829
9830 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
9831 // for generalization purposes (?).
9832 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9833
9834 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
9835 unsigned CandsShown = 0;
9836 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9837 TemplateSpecCandidate *Cand = *I;
9838
9839 // Set an arbitrary limit on the number of candidates we'll spam
9840 // the user with. FIXME: This limit should depend on details of the
9841 // candidate list.
9842 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9843 break;
9844 ++CandsShown;
9845
9846 assert(Cand->Specialization &&
9847 "Non-matching built-in candidates are not added to Cands.");
9848 Cand->NoteDeductionFailure(S);
9849 }
9850
9851 if (I != E)
9852 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
9853}
9854
Douglas Gregorb491ed32011-02-19 21:32:49 +00009855// [PossiblyAFunctionType] --> [Return]
9856// NonFunctionType --> NonFunctionType
9857// R (A) --> R(A)
9858// R (*)(A) --> R (A)
9859// R (&)(A) --> R (A)
9860// R (S::*)(A) --> R (A)
9861QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
9862 QualType Ret = PossiblyAFunctionType;
9863 if (const PointerType *ToTypePtr =
9864 PossiblyAFunctionType->getAs<PointerType>())
9865 Ret = ToTypePtr->getPointeeType();
9866 else if (const ReferenceType *ToTypeRef =
9867 PossiblyAFunctionType->getAs<ReferenceType>())
9868 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00009869 else if (const MemberPointerType *MemTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +00009870 PossiblyAFunctionType->getAs<MemberPointerType>())
9871 Ret = MemTypePtr->getPointeeType();
9872 Ret =
9873 Context.getCanonicalType(Ret).getUnqualifiedType();
9874 return Ret;
9875}
Douglas Gregorcd695e52008-11-10 20:40:00 +00009876
Richard Smith17c00b42014-11-12 01:24:00 +00009877namespace {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009878// A helper class to help with address of function resolution
9879// - allows us to avoid passing around all those ugly parameters
Richard Smith17c00b42014-11-12 01:24:00 +00009880class AddressOfFunctionResolver {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009881 Sema& S;
9882 Expr* SourceExpr;
9883 const QualType& TargetType;
9884 QualType TargetFunctionType; // Extracted function type from target type
9885
9886 bool Complain;
9887 //DeclAccessPair& ResultFunctionAccessPair;
9888 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009889
Douglas Gregorb491ed32011-02-19 21:32:49 +00009890 bool TargetTypeIsNonStaticMemberFunction;
9891 bool FoundNonTemplateFunction;
David Majnemera4f7c7a2013-08-01 06:13:59 +00009892 bool StaticMemberFunctionFromBoundPointer;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009893
Douglas Gregorb491ed32011-02-19 21:32:49 +00009894 OverloadExpr::FindResult OvlExprInfo;
9895 OverloadExpr *OvlExpr;
9896 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009897 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Larisse Voufo98b20f12013-07-19 23:00:19 +00009898 TemplateSpecCandidateSet FailedCandidates;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009899
Douglas Gregorb491ed32011-02-19 21:32:49 +00009900public:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009901 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
9902 const QualType &TargetType, bool Complain)
9903 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
9904 Complain(Complain), Context(S.getASTContext()),
9905 TargetTypeIsNonStaticMemberFunction(
9906 !!TargetType->getAs<MemberPointerType>()),
9907 FoundNonTemplateFunction(false),
David Majnemera4f7c7a2013-08-01 06:13:59 +00009908 StaticMemberFunctionFromBoundPointer(false),
Larisse Voufo98b20f12013-07-19 23:00:19 +00009909 OvlExprInfo(OverloadExpr::find(SourceExpr)),
9910 OvlExpr(OvlExprInfo.Expression),
9911 FailedCandidates(OvlExpr->getNameLoc()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009912 ExtractUnqualifiedFunctionTypeFromTargetType();
Chandler Carruthffce2452011-03-29 08:08:18 +00009913
David Majnemera4f7c7a2013-08-01 06:13:59 +00009914 if (TargetFunctionType->isFunctionType()) {
9915 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
9916 if (!UME->isImplicitAccess() &&
9917 !S.ResolveSingleFunctionTemplateSpecialization(UME))
9918 StaticMemberFunctionFromBoundPointer = true;
9919 } else if (OvlExpr->hasExplicitTemplateArgs()) {
9920 DeclAccessPair dap;
9921 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
9922 OvlExpr, false, &dap)) {
9923 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
9924 if (!Method->isStatic()) {
9925 // If the target type is a non-function type and the function found
9926 // is a non-static member function, pretend as if that was the
9927 // target, it's the only possible type to end up with.
9928 TargetTypeIsNonStaticMemberFunction = true;
Chandler Carruthffce2452011-03-29 08:08:18 +00009929
David Majnemera4f7c7a2013-08-01 06:13:59 +00009930 // And skip adding the function if its not in the proper form.
9931 // We'll diagnose this due to an empty set of functions.
9932 if (!OvlExprInfo.HasFormOfMemberPointer)
9933 return;
Chandler Carruthffce2452011-03-29 08:08:18 +00009934 }
9935
David Majnemera4f7c7a2013-08-01 06:13:59 +00009936 Matches.push_back(std::make_pair(dap, Fn));
Douglas Gregor9b146582009-07-08 20:55:45 +00009937 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00009938 return;
Douglas Gregor9b146582009-07-08 20:55:45 +00009939 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00009940
9941 if (OvlExpr->hasExplicitTemplateArgs())
9942 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00009943
Douglas Gregorb491ed32011-02-19 21:32:49 +00009944 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
9945 // C++ [over.over]p4:
9946 // If more than one function is selected, [...]
9947 if (Matches.size() > 1) {
9948 if (FoundNonTemplateFunction)
9949 EliminateAllTemplateMatches();
9950 else
9951 EliminateAllExceptMostSpecializedTemplate();
9952 }
9953 }
Artem Belevich94a55e82015-09-22 17:22:59 +00009954
9955 if (S.getLangOpts().CUDA && S.getLangOpts().CUDATargetOverloads &&
9956 Matches.size() > 1)
9957 EliminateSuboptimalCudaMatches();
Douglas Gregorb491ed32011-02-19 21:32:49 +00009958 }
9959
9960private:
9961 bool isTargetTypeAFunction() const {
9962 return TargetFunctionType->isFunctionType();
9963 }
9964
9965 // [ToType] [Return]
9966
9967 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
9968 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
9969 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
9970 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
9971 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
9972 }
9973
9974 // return true if any matching specializations were found
9975 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
9976 const DeclAccessPair& CurAccessFunPair) {
9977 if (CXXMethodDecl *Method
9978 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
9979 // Skip non-static function templates when converting to pointer, and
9980 // static when converting to member pointer.
9981 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9982 return false;
9983 }
9984 else if (TargetTypeIsNonStaticMemberFunction)
9985 return false;
9986
9987 // C++ [over.over]p2:
9988 // If the name is a function template, template argument deduction is
9989 // done (14.8.2.2), and if the argument deduction succeeds, the
9990 // resulting template argument list is used to generate a single
9991 // function template specialization, which is added to the set of
9992 // overloaded functions considered.
Craig Topperc3ec1492014-05-26 06:22:03 +00009993 FunctionDecl *Specialization = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +00009994 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregorb491ed32011-02-19 21:32:49 +00009995 if (Sema::TemplateDeductionResult Result
9996 = S.DeduceTemplateArguments(FunctionTemplate,
9997 &OvlExplicitTemplateArgs,
9998 TargetFunctionType, Specialization,
Douglas Gregor19a41f12013-04-17 08:45:07 +00009999 Info, /*InOverloadResolution=*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010000 // Make a note of the failed deduction for diagnostics.
10001 FailedCandidates.addCandidate()
10002 .set(FunctionTemplate->getTemplatedDecl(),
10003 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregorb491ed32011-02-19 21:32:49 +000010004 return false;
10005 }
10006
Douglas Gregor19a41f12013-04-17 08:45:07 +000010007 // Template argument deduction ensures that we have an exact match or
10008 // compatible pointer-to-function arguments that would be adjusted by ICS.
Douglas Gregorb491ed32011-02-19 21:32:49 +000010009 // This function template specicalization works.
10010 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
Douglas Gregor19a41f12013-04-17 08:45:07 +000010011 assert(S.isSameOrCompatibleFunctionType(
10012 Context.getCanonicalType(Specialization->getType()),
10013 Context.getCanonicalType(TargetFunctionType)));
Douglas Gregorb491ed32011-02-19 21:32:49 +000010014 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
10015 return true;
10016 }
10017
10018 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
10019 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +000010020 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +000010021 // Skip non-static functions when converting to pointer, and static
10022 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +000010023 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10024 return false;
10025 }
10026 else if (TargetTypeIsNonStaticMemberFunction)
10027 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010028
Chandler Carruthc25c6ee2009-12-29 06:17:27 +000010029 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000010030 if (S.getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010031 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
Eli Bendersky9a220fc2014-09-29 20:38:29 +000010032 if (!Caller->isImplicit() && S.CheckCUDATarget(Caller, FunDecl))
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010033 return false;
10034
Richard Smith2a7d4812013-05-04 07:00:32 +000010035 // If any candidate has a placeholder return type, trigger its deduction
10036 // now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +000010037 if (S.getLangOpts().CPlusPlus14 &&
Alp Toker314cc812014-01-25 16:55:45 +000010038 FunDecl->getReturnType()->isUndeducedType() &&
Richard Smith2a7d4812013-05-04 07:00:32 +000010039 S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain))
10040 return false;
10041
Douglas Gregor40cb9ad2009-12-09 00:47:37 +000010042 QualType ResultTy;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010043 if (Context.hasSameUnqualifiedType(TargetFunctionType,
10044 FunDecl->getType()) ||
Chandler Carruth53e61b02011-06-18 01:19:03 +000010045 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
10046 ResultTy)) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010047 Matches.push_back(std::make_pair(CurAccessFunPair,
10048 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +000010049 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010050 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +000010051 }
Mike Stump11289f42009-09-09 15:08:12 +000010052 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010053
10054 return false;
10055 }
10056
10057 bool FindAllFunctionsThatMatchTargetTypeExactly() {
10058 bool Ret = false;
10059
10060 // If the overload expression doesn't have the form of a pointer to
10061 // member, don't try to convert it to a pointer-to-member type.
10062 if (IsInvalidFormOfPointerToMemberFunction())
10063 return false;
10064
10065 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10066 E = OvlExpr->decls_end();
10067 I != E; ++I) {
10068 // Look through any using declarations to find the underlying function.
10069 NamedDecl *Fn = (*I)->getUnderlyingDecl();
10070
10071 // C++ [over.over]p3:
10072 // Non-member functions and static member functions match
10073 // targets of type "pointer-to-function" or "reference-to-function."
10074 // Nonstatic member functions match targets of
10075 // type "pointer-to-member-function."
10076 // Note that according to DR 247, the containing class does not matter.
10077 if (FunctionTemplateDecl *FunctionTemplate
10078 = dyn_cast<FunctionTemplateDecl>(Fn)) {
10079 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
10080 Ret = true;
10081 }
10082 // If we have explicit template arguments supplied, skip non-templates.
10083 else if (!OvlExpr->hasExplicitTemplateArgs() &&
10084 AddMatchingNonTemplateFunction(Fn, I.getPair()))
10085 Ret = true;
10086 }
10087 assert(Ret || Matches.empty());
10088 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010089 }
10090
Douglas Gregorb491ed32011-02-19 21:32:49 +000010091 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +000010092 // [...] and any given function template specialization F1 is
10093 // eliminated if the set contains a second function template
10094 // specialization whose function template is more specialized
10095 // than the function template of F1 according to the partial
10096 // ordering rules of 14.5.5.2.
10097
10098 // The algorithm specified above is quadratic. We instead use a
10099 // two-pass algorithm (similar to the one used to identify the
10100 // best viable function in an overload set) that identifies the
10101 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +000010102
10103 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
10104 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
10105 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010106
Larisse Voufo98b20f12013-07-19 23:00:19 +000010107 // TODO: It looks like FailedCandidates does not serve much purpose
10108 // here, since the no_viable diagnostic has index 0.
10109 UnresolvedSetIterator Result = S.getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +000010110 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +000010111 SourceExpr->getLocStart(), S.PDiag(),
10112 S.PDiag(diag::err_addr_ovl_ambiguous) << Matches[0]
10113 .second->getDeclName(),
10114 S.PDiag(diag::note_ovl_candidate) << (unsigned)oc_function_template,
10115 Complain, TargetFunctionType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010116
Douglas Gregorb491ed32011-02-19 21:32:49 +000010117 if (Result != MatchesCopy.end()) {
10118 // Make it the first and only element
10119 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
10120 Matches[0].second = cast<FunctionDecl>(*Result);
10121 Matches.resize(1);
John McCall58cc69d2010-01-27 01:50:18 +000010122 }
10123 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010124
Douglas Gregorb491ed32011-02-19 21:32:49 +000010125 void EliminateAllTemplateMatches() {
10126 // [...] any function template specializations in the set are
10127 // eliminated if the set also contains a non-template function, [...]
10128 for (unsigned I = 0, N = Matches.size(); I != N; ) {
Craig Topperc3ec1492014-05-26 06:22:03 +000010129 if (Matches[I].second->getPrimaryTemplate() == nullptr)
Douglas Gregorb491ed32011-02-19 21:32:49 +000010130 ++I;
10131 else {
10132 Matches[I] = Matches[--N];
Artem Belevich94a55e82015-09-22 17:22:59 +000010133 Matches.resize(N);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010134 }
10135 }
10136 }
10137
Artem Belevich94a55e82015-09-22 17:22:59 +000010138 void EliminateSuboptimalCudaMatches() {
10139 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
10140 }
10141
Douglas Gregorb491ed32011-02-19 21:32:49 +000010142public:
10143 void ComplainNoMatchesFound() const {
10144 assert(Matches.empty());
10145 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
10146 << OvlExpr->getName() << TargetFunctionType
10147 << OvlExpr->getSourceRange();
Richard Smith0d905472013-08-14 00:00:44 +000010148 if (FailedCandidates.empty())
10149 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
10150 else {
10151 // We have some deduction failure messages. Use them to diagnose
10152 // the function templates, and diagnose the non-template candidates
10153 // normally.
10154 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10155 IEnd = OvlExpr->decls_end();
10156 I != IEnd; ++I)
10157 if (FunctionDecl *Fun =
10158 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
10159 S.NoteOverloadCandidate(Fun, TargetFunctionType);
10160 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
10161 }
10162 }
10163
Douglas Gregorb491ed32011-02-19 21:32:49 +000010164 bool IsInvalidFormOfPointerToMemberFunction() const {
10165 return TargetTypeIsNonStaticMemberFunction &&
10166 !OvlExprInfo.HasFormOfMemberPointer;
10167 }
David Majnemera4f7c7a2013-08-01 06:13:59 +000010168
Douglas Gregorb491ed32011-02-19 21:32:49 +000010169 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
10170 // TODO: Should we condition this on whether any functions might
10171 // have matched, or is it more appropriate to do that in callers?
10172 // TODO: a fixit wouldn't hurt.
10173 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
10174 << TargetType << OvlExpr->getSourceRange();
10175 }
David Majnemera4f7c7a2013-08-01 06:13:59 +000010176
10177 bool IsStaticMemberFunctionFromBoundPointer() const {
10178 return StaticMemberFunctionFromBoundPointer;
10179 }
10180
10181 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
10182 S.Diag(OvlExpr->getLocStart(),
10183 diag::err_invalid_form_pointer_member_function)
10184 << OvlExpr->getSourceRange();
10185 }
10186
Douglas Gregorb491ed32011-02-19 21:32:49 +000010187 void ComplainOfInvalidConversion() const {
10188 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
10189 << OvlExpr->getName() << TargetType;
10190 }
10191
10192 void ComplainMultipleMatchesFound() const {
10193 assert(Matches.size() > 1);
10194 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
10195 << OvlExpr->getName()
10196 << OvlExpr->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +000010197 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010198 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010199
10200 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
10201
Douglas Gregorb491ed32011-02-19 21:32:49 +000010202 int getNumMatches() const { return Matches.size(); }
10203
10204 FunctionDecl* getMatchingFunctionDecl() const {
Craig Topperc3ec1492014-05-26 06:22:03 +000010205 if (Matches.size() != 1) return nullptr;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010206 return Matches[0].second;
10207 }
10208
10209 const DeclAccessPair* getMatchingFunctionAccessPair() const {
Craig Topperc3ec1492014-05-26 06:22:03 +000010210 if (Matches.size() != 1) return nullptr;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010211 return &Matches[0].first;
10212 }
10213};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010214}
Richard Smith17c00b42014-11-12 01:24:00 +000010215
Douglas Gregorb491ed32011-02-19 21:32:49 +000010216/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
10217/// an overloaded function (C++ [over.over]), where @p From is an
10218/// expression with overloaded function type and @p ToType is the type
10219/// we're trying to resolve to. For example:
10220///
10221/// @code
10222/// int f(double);
10223/// int f(int);
10224///
10225/// int (*pfd)(double) = f; // selects f(double)
10226/// @endcode
10227///
10228/// This routine returns the resulting FunctionDecl if it could be
10229/// resolved, and NULL otherwise. When @p Complain is true, this
10230/// routine will emit diagnostics if there is an error.
10231FunctionDecl *
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010232Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
10233 QualType TargetType,
10234 bool Complain,
10235 DeclAccessPair &FoundResult,
10236 bool *pHadMultipleCandidates) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010237 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010238
10239 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
10240 Complain);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010241 int NumMatches = Resolver.getNumMatches();
Craig Topperc3ec1492014-05-26 06:22:03 +000010242 FunctionDecl *Fn = nullptr;
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010243 if (NumMatches == 0 && Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010244 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
10245 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
10246 else
10247 Resolver.ComplainNoMatchesFound();
10248 }
10249 else if (NumMatches > 1 && Complain)
10250 Resolver.ComplainMultipleMatchesFound();
10251 else if (NumMatches == 1) {
10252 Fn = Resolver.getMatchingFunctionDecl();
10253 assert(Fn);
10254 FoundResult = *Resolver.getMatchingFunctionAccessPair();
David Majnemera4f7c7a2013-08-01 06:13:59 +000010255 if (Complain) {
10256 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
10257 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
10258 else
10259 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
10260 }
Sebastian Redldf4b80e2009-10-17 21:12:09 +000010261 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010262
10263 if (pHadMultipleCandidates)
10264 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregorb491ed32011-02-19 21:32:49 +000010265 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010266}
10267
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010268/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010269/// resolve that overloaded function expression down to a single function.
10270///
10271/// This routine can only resolve template-ids that refer to a single function
10272/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010273/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010274/// as described in C++0x [temp.arg.explicit]p3.
Alp Toker67b47ac2013-10-20 18:48:56 +000010275///
10276/// If no template-ids are found, no diagnostics are emitted and NULL is
10277/// returned.
John McCall0009fcc2011-04-26 20:42:42 +000010278FunctionDecl *
10279Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
10280 bool Complain,
10281 DeclAccessPair *FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010282 // C++ [over.over]p1:
10283 // [...] [Note: any redundant set of parentheses surrounding the
10284 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010285 // C++ [over.over]p1:
10286 // [...] The overloaded function name can be preceded by the &
10287 // operator.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010288
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010289 // If we didn't actually find any template-ids, we're done.
John McCall0009fcc2011-04-26 20:42:42 +000010290 if (!ovl->hasExplicitTemplateArgs())
Craig Topperc3ec1492014-05-26 06:22:03 +000010291 return nullptr;
John McCall1acbbb52010-02-02 06:20:04 +000010292
10293 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall0009fcc2011-04-26 20:42:42 +000010294 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010295 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010296
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010297 // Look through all of the overloaded functions, searching for one
10298 // whose type matches exactly.
Craig Topperc3ec1492014-05-26 06:22:03 +000010299 FunctionDecl *Matched = nullptr;
John McCall0009fcc2011-04-26 20:42:42 +000010300 for (UnresolvedSetIterator I = ovl->decls_begin(),
10301 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010302 // C++0x [temp.arg.explicit]p3:
10303 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010304 // where deduction is not done, if a template argument list is
10305 // specified and it, along with any default template arguments,
10306 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010307 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +000010308 FunctionTemplateDecl *FunctionTemplate
10309 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010310
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010311 // C++ [over.over]p2:
10312 // If the name is a function template, template argument deduction is
10313 // done (14.8.2.2), and if the argument deduction succeeds, the
10314 // resulting template argument list is used to generate a single
10315 // function template specialization, which is added to the set of
10316 // overloaded functions considered.
Craig Topperc3ec1492014-05-26 06:22:03 +000010317 FunctionDecl *Specialization = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +000010318 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010319 if (TemplateDeductionResult Result
10320 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
Douglas Gregor19a41f12013-04-17 08:45:07 +000010321 Specialization, Info,
10322 /*InOverloadResolution=*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010323 // Make a note of the failed deduction for diagnostics.
10324 // TODO: Actually use the failed-deduction info?
10325 FailedCandidates.addCandidate()
10326 .set(FunctionTemplate->getTemplatedDecl(),
10327 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010328 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010329 }
10330
John McCall0009fcc2011-04-26 20:42:42 +000010331 assert(Specialization && "no specialization and no error?");
10332
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010333 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +000010334 if (Matched) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010335 if (Complain) {
John McCall0009fcc2011-04-26 20:42:42 +000010336 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
10337 << ovl->getName();
10338 NoteAllOverloadCandidates(ovl);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010339 }
Craig Topperc3ec1492014-05-26 06:22:03 +000010340 return nullptr;
John McCall0009fcc2011-04-26 20:42:42 +000010341 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010342
John McCall0009fcc2011-04-26 20:42:42 +000010343 Matched = Specialization;
10344 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010345 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010346
Aaron Ballmandd69ef32014-08-19 15:55:55 +000010347 if (Matched && getLangOpts().CPlusPlus14 &&
Alp Toker314cc812014-01-25 16:55:45 +000010348 Matched->getReturnType()->isUndeducedType() &&
Richard Smith2a7d4812013-05-04 07:00:32 +000010349 DeduceReturnType(Matched, ovl->getExprLoc(), Complain))
Craig Topperc3ec1492014-05-26 06:22:03 +000010350 return nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +000010351
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010352 return Matched;
10353}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010354
Douglas Gregor1beec452011-03-12 01:48:56 +000010355
10356
10357
John McCall50a2c2c2011-10-11 23:14:30 +000010358// Resolve and fix an overloaded expression that can be resolved
10359// because it identifies a single function template specialization.
10360//
Douglas Gregor1beec452011-03-12 01:48:56 +000010361// Last three arguments should only be supplied if Complain = true
John McCall50a2c2c2011-10-11 23:14:30 +000010362//
10363// Return true if it was logically possible to so resolve the
10364// expression, regardless of whether or not it succeeded. Always
10365// returns true if 'complain' is set.
10366bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
10367 ExprResult &SrcExpr, bool doFunctionPointerConverion,
10368 bool complain, const SourceRange& OpRangeForComplaining,
Douglas Gregor1beec452011-03-12 01:48:56 +000010369 QualType DestTypeForComplaining,
John McCall0009fcc2011-04-26 20:42:42 +000010370 unsigned DiagIDForComplaining) {
John McCall50a2c2c2011-10-11 23:14:30 +000010371 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregor1beec452011-03-12 01:48:56 +000010372
John McCall50a2c2c2011-10-11 23:14:30 +000010373 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregor1beec452011-03-12 01:48:56 +000010374
John McCall0009fcc2011-04-26 20:42:42 +000010375 DeclAccessPair found;
10376 ExprResult SingleFunctionExpression;
10377 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
10378 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010379 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall50a2c2c2011-10-11 23:14:30 +000010380 SrcExpr = ExprError();
10381 return true;
10382 }
John McCall0009fcc2011-04-26 20:42:42 +000010383
10384 // It is only correct to resolve to an instance method if we're
10385 // resolving a form that's permitted to be a pointer to member.
10386 // Otherwise we'll end up making a bound member expression, which
10387 // is illegal in all the contexts we resolve like this.
10388 if (!ovl.HasFormOfMemberPointer &&
10389 isa<CXXMethodDecl>(fn) &&
10390 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall50a2c2c2011-10-11 23:14:30 +000010391 if (!complain) return false;
10392
10393 Diag(ovl.Expression->getExprLoc(),
10394 diag::err_bound_member_function)
10395 << 0 << ovl.Expression->getSourceRange();
10396
10397 // TODO: I believe we only end up here if there's a mix of
10398 // static and non-static candidates (otherwise the expression
10399 // would have 'bound member' type, not 'overload' type).
10400 // Ideally we would note which candidate was chosen and why
10401 // the static candidates were rejected.
10402 SrcExpr = ExprError();
10403 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000010404 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +000010405
Sylvestre Ledrua5202662012-07-31 06:56:50 +000010406 // Fix the expression to refer to 'fn'.
John McCall0009fcc2011-04-26 20:42:42 +000010407 SingleFunctionExpression =
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010408 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
John McCall0009fcc2011-04-26 20:42:42 +000010409
10410 // If desired, do function-to-pointer decay.
John McCall50a2c2c2011-10-11 23:14:30 +000010411 if (doFunctionPointerConverion) {
John McCall0009fcc2011-04-26 20:42:42 +000010412 SingleFunctionExpression =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010413 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
John McCall50a2c2c2011-10-11 23:14:30 +000010414 if (SingleFunctionExpression.isInvalid()) {
10415 SrcExpr = ExprError();
10416 return true;
10417 }
10418 }
John McCall0009fcc2011-04-26 20:42:42 +000010419 }
10420
10421 if (!SingleFunctionExpression.isUsable()) {
10422 if (complain) {
10423 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
10424 << ovl.Expression->getName()
10425 << DestTypeForComplaining
10426 << OpRangeForComplaining
10427 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall50a2c2c2011-10-11 23:14:30 +000010428 NoteAllOverloadCandidates(SrcExpr.get());
10429
10430 SrcExpr = ExprError();
10431 return true;
10432 }
10433
10434 return false;
John McCall0009fcc2011-04-26 20:42:42 +000010435 }
10436
John McCall50a2c2c2011-10-11 23:14:30 +000010437 SrcExpr = SingleFunctionExpression;
10438 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000010439}
10440
Douglas Gregorcabea402009-09-22 15:41:20 +000010441/// \brief Add a single candidate to the overload set.
10442static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +000010443 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +000010444 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010445 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000010446 OverloadCandidateSet &CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +000010447 bool PartialOverloading,
10448 bool KnownValid) {
John McCalla0296f72010-03-19 07:35:19 +000010449 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +000010450 if (isa<UsingShadowDecl>(Callee))
10451 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
10452
Douglas Gregorcabea402009-09-22 15:41:20 +000010453 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith95ce4f62011-06-26 22:19:54 +000010454 if (ExplicitTemplateArgs) {
10455 assert(!KnownValid && "Explicit template arguments?");
10456 return;
10457 }
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000010458 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
10459 /*SuppressUsedConversions=*/false,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010460 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000010461 return;
John McCalld14a8642009-11-21 08:51:07 +000010462 }
10463
10464 if (FunctionTemplateDecl *FuncTemplate
10465 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +000010466 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000010467 ExplicitTemplateArgs, Args, CandidateSet,
10468 /*SuppressUsedConversions=*/false,
10469 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +000010470 return;
10471 }
10472
Richard Smith95ce4f62011-06-26 22:19:54 +000010473 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregorcabea402009-09-22 15:41:20 +000010474}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010475
Douglas Gregorcabea402009-09-22 15:41:20 +000010476/// \brief Add the overload candidates named by callee and/or found by argument
10477/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +000010478void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010479 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000010480 OverloadCandidateSet &CandidateSet,
10481 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +000010482
10483#ifndef NDEBUG
10484 // Verify that ArgumentDependentLookup is consistent with the rules
10485 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +000010486 //
Douglas Gregorcabea402009-09-22 15:41:20 +000010487 // Let X be the lookup set produced by unqualified lookup (3.4.1)
10488 // and let Y be the lookup set produced by argument dependent
10489 // lookup (defined as follows). If X contains
10490 //
10491 // -- a declaration of a class member, or
10492 //
10493 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +000010494 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +000010495 //
10496 // -- a declaration that is neither a function or a function
10497 // template
10498 //
10499 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +000010500
John McCall57500772009-12-16 12:17:52 +000010501 if (ULE->requiresADL()) {
10502 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10503 E = ULE->decls_end(); I != E; ++I) {
10504 assert(!(*I)->getDeclContext()->isRecord());
10505 assert(isa<UsingShadowDecl>(*I) ||
10506 !(*I)->getDeclContext()->isFunctionOrMethod());
10507 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +000010508 }
10509 }
10510#endif
10511
John McCall57500772009-12-16 12:17:52 +000010512 // It would be nice to avoid this copy.
10513 TemplateArgumentListInfo TABuffer;
Craig Topperc3ec1492014-05-26 06:22:03 +000010514 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
John McCall57500772009-12-16 12:17:52 +000010515 if (ULE->hasExplicitTemplateArgs()) {
10516 ULE->copyTemplateArgumentsInto(TABuffer);
10517 ExplicitTemplateArgs = &TABuffer;
10518 }
10519
10520 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10521 E = ULE->decls_end(); I != E; ++I)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010522 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
10523 CandidateSet, PartialOverloading,
10524 /*KnownValid*/ true);
John McCalld14a8642009-11-21 08:51:07 +000010525
John McCall57500772009-12-16 12:17:52 +000010526 if (ULE->requiresADL())
Richard Smith100b24a2014-04-17 01:52:14 +000010527 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010528 Args, ExplicitTemplateArgs,
Richard Smithb6626742012-10-18 17:56:02 +000010529 CandidateSet, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000010530}
John McCalld681c392009-12-16 08:11:27 +000010531
Richard Smith0603bbb2013-06-12 22:56:54 +000010532/// Determine whether a declaration with the specified name could be moved into
10533/// a different namespace.
10534static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
10535 switch (Name.getCXXOverloadedOperator()) {
10536 case OO_New: case OO_Array_New:
10537 case OO_Delete: case OO_Array_Delete:
10538 return false;
10539
10540 default:
10541 return true;
10542 }
10543}
10544
Richard Smith998a5912011-06-05 22:42:48 +000010545/// Attempt to recover from an ill-formed use of a non-dependent name in a
10546/// template, where the non-dependent name was declared after the template
10547/// was defined. This is common in code written for a compilers which do not
10548/// correctly implement two-stage name lookup.
10549///
10550/// Returns true if a viable candidate was found and a diagnostic was issued.
10551static bool
10552DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
10553 const CXXScopeSpec &SS, LookupResult &R,
Richard Smith100b24a2014-04-17 01:52:14 +000010554 OverloadCandidateSet::CandidateSetKind CSK,
Richard Smith998a5912011-06-05 22:42:48 +000010555 TemplateArgumentListInfo *ExplicitTemplateArgs,
Hans Wennborg64937c62015-06-11 21:21:57 +000010556 ArrayRef<Expr *> Args,
10557 bool *DoDiagnoseEmptyLookup = nullptr) {
Richard Smith998a5912011-06-05 22:42:48 +000010558 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
10559 return false;
10560
10561 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewyckyfcd5e7a2012-03-14 20:41:00 +000010562 if (DC->isTransparentContext())
10563 continue;
10564
Richard Smith998a5912011-06-05 22:42:48 +000010565 SemaRef.LookupQualifiedName(R, DC);
10566
10567 if (!R.empty()) {
10568 R.suppressDiagnostics();
10569
10570 if (isa<CXXRecordDecl>(DC)) {
10571 // Don't diagnose names we find in classes; we get much better
10572 // diagnostics for these from DiagnoseEmptyLookup.
10573 R.clear();
Hans Wennborg64937c62015-06-11 21:21:57 +000010574 if (DoDiagnoseEmptyLookup)
10575 *DoDiagnoseEmptyLookup = true;
Richard Smith998a5912011-06-05 22:42:48 +000010576 return false;
10577 }
10578
Richard Smith100b24a2014-04-17 01:52:14 +000010579 OverloadCandidateSet Candidates(FnLoc, CSK);
Richard Smith998a5912011-06-05 22:42:48 +000010580 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
10581 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010582 ExplicitTemplateArgs, Args,
Richard Smith95ce4f62011-06-26 22:19:54 +000010583 Candidates, false, /*KnownValid*/ false);
Richard Smith998a5912011-06-05 22:42:48 +000010584
10585 OverloadCandidateSet::iterator Best;
Richard Smith95ce4f62011-06-26 22:19:54 +000010586 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smith998a5912011-06-05 22:42:48 +000010587 // No viable functions. Don't bother the user with notes for functions
10588 // which don't work and shouldn't be found anyway.
Richard Smith95ce4f62011-06-26 22:19:54 +000010589 R.clear();
Richard Smith998a5912011-06-05 22:42:48 +000010590 return false;
Richard Smith95ce4f62011-06-26 22:19:54 +000010591 }
Richard Smith998a5912011-06-05 22:42:48 +000010592
10593 // Find the namespaces where ADL would have looked, and suggest
10594 // declaring the function there instead.
10595 Sema::AssociatedNamespaceSet AssociatedNamespaces;
10596 Sema::AssociatedClassSet AssociatedClasses;
John McCall7d8b0412012-08-24 20:38:34 +000010597 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
Richard Smith998a5912011-06-05 22:42:48 +000010598 AssociatedNamespaces,
10599 AssociatedClasses);
Chandler Carruthd50f1692011-06-05 23:36:55 +000010600 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smith0603bbb2013-06-12 22:56:54 +000010601 if (canBeDeclaredInNamespace(R.getLookupName())) {
10602 DeclContext *Std = SemaRef.getStdNamespace();
10603 for (Sema::AssociatedNamespaceSet::iterator
10604 it = AssociatedNamespaces.begin(),
10605 end = AssociatedNamespaces.end(); it != end; ++it) {
10606 // Never suggest declaring a function within namespace 'std'.
10607 if (Std && Std->Encloses(*it))
10608 continue;
Richard Smith21bae432012-12-22 02:46:14 +000010609
Richard Smith0603bbb2013-06-12 22:56:54 +000010610 // Never suggest declaring a function within a namespace with a
10611 // reserved name, like __gnu_cxx.
10612 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
10613 if (NS &&
10614 NS->getQualifiedNameAsString().find("__") != std::string::npos)
10615 continue;
10616
10617 SuggestedNamespaces.insert(*it);
10618 }
Richard Smith998a5912011-06-05 22:42:48 +000010619 }
10620
10621 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
10622 << R.getLookupName();
Chandler Carruthd50f1692011-06-05 23:36:55 +000010623 if (SuggestedNamespaces.empty()) {
Richard Smith998a5912011-06-05 22:42:48 +000010624 SemaRef.Diag(Best->Function->getLocation(),
10625 diag::note_not_found_by_two_phase_lookup)
10626 << R.getLookupName() << 0;
Chandler Carruthd50f1692011-06-05 23:36:55 +000010627 } else if (SuggestedNamespaces.size() == 1) {
Richard Smith998a5912011-06-05 22:42:48 +000010628 SemaRef.Diag(Best->Function->getLocation(),
10629 diag::note_not_found_by_two_phase_lookup)
Chandler Carruthd50f1692011-06-05 23:36:55 +000010630 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smith998a5912011-06-05 22:42:48 +000010631 } else {
10632 // FIXME: It would be useful to list the associated namespaces here,
10633 // but the diagnostics infrastructure doesn't provide a way to produce
10634 // a localized representation of a list of items.
10635 SemaRef.Diag(Best->Function->getLocation(),
10636 diag::note_not_found_by_two_phase_lookup)
10637 << R.getLookupName() << 2;
10638 }
10639
10640 // Try to recover by calling this function.
10641 return true;
10642 }
10643
10644 R.clear();
10645 }
10646
10647 return false;
10648}
10649
10650/// Attempt to recover from ill-formed use of a non-dependent operator in a
10651/// template, where the non-dependent operator was declared after the template
10652/// was defined.
10653///
10654/// Returns true if a viable candidate was found and a diagnostic was issued.
10655static bool
10656DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
10657 SourceLocation OpLoc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010658 ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +000010659 DeclarationName OpName =
10660 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
10661 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
10662 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Richard Smith100b24a2014-04-17 01:52:14 +000010663 OverloadCandidateSet::CSK_Operator,
Craig Topperc3ec1492014-05-26 06:22:03 +000010664 /*ExplicitTemplateArgs=*/nullptr, Args);
Richard Smith998a5912011-06-05 22:42:48 +000010665}
10666
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000010667namespace {
Richard Smith88d67f32012-09-25 04:46:05 +000010668class BuildRecoveryCallExprRAII {
10669 Sema &SemaRef;
10670public:
10671 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
10672 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
10673 SemaRef.IsBuildingRecoveryCallExpr = true;
10674 }
10675
10676 ~BuildRecoveryCallExprRAII() {
10677 SemaRef.IsBuildingRecoveryCallExpr = false;
10678 }
10679};
10680
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010681}
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000010682
Kaelyn Takata89c881b2014-10-27 18:07:29 +000010683static std::unique_ptr<CorrectionCandidateCallback>
10684MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
10685 bool HasTemplateArgs, bool AllowTypoCorrection) {
10686 if (!AllowTypoCorrection)
10687 return llvm::make_unique<NoTypoCorrectionCCC>();
10688 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
10689 HasTemplateArgs, ME);
10690}
10691
John McCalld681c392009-12-16 08:11:27 +000010692/// Attempts to recover from a call where no functions were found.
10693///
10694/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +000010695static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +000010696BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +000010697 UnresolvedLookupExpr *ULE,
10698 SourceLocation LParenLoc,
Craig Toppere3d2ecbe2014-06-28 23:22:33 +000010699 MutableArrayRef<Expr *> Args,
Richard Smith998a5912011-06-05 22:42:48 +000010700 SourceLocation RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000010701 bool EmptyLookup, bool AllowTypoCorrection) {
Richard Smith88d67f32012-09-25 04:46:05 +000010702 // Do not try to recover if it is already building a recovery call.
10703 // This stops infinite loops for template instantiations like
10704 //
10705 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
10706 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
10707 //
10708 if (SemaRef.IsBuildingRecoveryCallExpr)
10709 return ExprError();
10710 BuildRecoveryCallExprRAII RCE(SemaRef);
John McCalld681c392009-12-16 08:11:27 +000010711
10712 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +000010713 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +000010714 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCalld681c392009-12-16 08:11:27 +000010715
John McCall57500772009-12-16 12:17:52 +000010716 TemplateArgumentListInfo TABuffer;
Craig Topperc3ec1492014-05-26 06:22:03 +000010717 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
John McCall57500772009-12-16 12:17:52 +000010718 if (ULE->hasExplicitTemplateArgs()) {
10719 ULE->copyTemplateArgumentsInto(TABuffer);
10720 ExplicitTemplateArgs = &TABuffer;
10721 }
10722
John McCalld681c392009-12-16 08:11:27 +000010723 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
10724 Sema::LookupOrdinaryName);
Hans Wennborg64937c62015-06-11 21:21:57 +000010725 bool DoDiagnoseEmptyLookup = EmptyLookup;
Richard Smith998a5912011-06-05 22:42:48 +000010726 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Richard Smith100b24a2014-04-17 01:52:14 +000010727 OverloadCandidateSet::CSK_Normal,
Hans Wennborg64937c62015-06-11 21:21:57 +000010728 ExplicitTemplateArgs, Args,
10729 &DoDiagnoseEmptyLookup) &&
10730 (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup(
10731 S, SS, R,
10732 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
10733 ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
10734 ExplicitTemplateArgs, Args)))
John McCallfaf5fb42010-08-26 23:41:50 +000010735 return ExprError();
John McCalld681c392009-12-16 08:11:27 +000010736
John McCall57500772009-12-16 12:17:52 +000010737 assert(!R.empty() && "lookup results empty despite recovery");
10738
10739 // Build an implicit member call if appropriate. Just drop the
10740 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +000010741 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +000010742 if ((*R.begin())->isCXXClassMember())
Aaron Ballman6924dcd2015-09-01 14:49:24 +000010743 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
10744 ExplicitTemplateArgs, S);
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000010745 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnara7945c982012-01-27 09:46:47 +000010746 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000010747 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +000010748 else
10749 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
10750
10751 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +000010752 return ExprError();
John McCall57500772009-12-16 12:17:52 +000010753
10754 // This shouldn't cause an infinite loop because we're giving it
Richard Smith998a5912011-06-05 22:42:48 +000010755 // an expression with viable lookup results, which should never
John McCall57500772009-12-16 12:17:52 +000010756 // end up here.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010757 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010758 MultiExprArg(Args.data(), Args.size()),
10759 RParenLoc);
John McCalld681c392009-12-16 08:11:27 +000010760}
Douglas Gregor4038cf42010-06-08 17:35:15 +000010761
Sam Panzer0f384432012-08-21 00:52:01 +000010762/// \brief Constructs and populates an OverloadedCandidateSet from
10763/// the given function.
10764/// \returns true when an the ExprResult output parameter has been set.
10765bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
10766 UnresolvedLookupExpr *ULE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010767 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010768 SourceLocation RParenLoc,
10769 OverloadCandidateSet *CandidateSet,
10770 ExprResult *Result) {
John McCall57500772009-12-16 12:17:52 +000010771#ifndef NDEBUG
10772 if (ULE->requiresADL()) {
10773 // To do ADL, we must have found an unqualified name.
10774 assert(!ULE->getQualifier() && "qualified name with ADL");
10775
10776 // We don't perform ADL for implicit declarations of builtins.
10777 // Verify that this was correctly set up.
10778 FunctionDecl *F;
10779 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
10780 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
10781 F->getBuiltinID() && F->isImplicit())
David Blaikie83d382b2011-09-23 05:06:16 +000010782 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010783
John McCall57500772009-12-16 12:17:52 +000010784 // We don't perform ADL in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010785 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smithb6626742012-10-18 17:56:02 +000010786 }
John McCall57500772009-12-16 12:17:52 +000010787#endif
10788
John McCall4124c492011-10-17 18:40:02 +000010789 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010790 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
Sam Panzer0f384432012-08-21 00:52:01 +000010791 *Result = ExprError();
10792 return true;
10793 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +000010794
John McCall57500772009-12-16 12:17:52 +000010795 // Add the functions denoted by the callee to the set of candidate
10796 // functions, including those from argument-dependent lookup.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010797 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
John McCalld681c392009-12-16 08:11:27 +000010798
Hans Wennborgb2747382015-06-12 21:23:23 +000010799 if (getLangOpts().MSVCCompat &&
10800 CurContext->isDependentContext() && !isSFINAEContext() &&
Hans Wennborg64937c62015-06-11 21:21:57 +000010801 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
10802
10803 OverloadCandidateSet::iterator Best;
10804 if (CandidateSet->empty() ||
10805 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) ==
10806 OR_No_Viable_Function) {
10807 // In Microsoft mode, if we are inside a template class member function then
10808 // create a type dependent CallExpr. The goal is to postpone name lookup
10809 // to instantiation time to be able to search into type dependent base
10810 // classes.
10811 CallExpr *CE = new (Context) CallExpr(
10812 Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc);
Sebastian Redlb49c46c2011-09-24 17:48:00 +000010813 CE->setTypeDependent(true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010814 *Result = CE;
Sam Panzer0f384432012-08-21 00:52:01 +000010815 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +000010816 }
Francois Pichetbcf64712011-09-07 00:14:57 +000010817 }
John McCalld681c392009-12-16 08:11:27 +000010818
Hans Wennborg64937c62015-06-11 21:21:57 +000010819 if (CandidateSet->empty())
10820 return false;
10821
John McCall4124c492011-10-17 18:40:02 +000010822 UnbridgedCasts.restore();
Sam Panzer0f384432012-08-21 00:52:01 +000010823 return false;
10824}
John McCall4124c492011-10-17 18:40:02 +000010825
Sam Panzer0f384432012-08-21 00:52:01 +000010826/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
10827/// the completed call expression. If overload resolution fails, emits
10828/// diagnostics and returns ExprError()
10829static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
10830 UnresolvedLookupExpr *ULE,
10831 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010832 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010833 SourceLocation RParenLoc,
10834 Expr *ExecConfig,
10835 OverloadCandidateSet *CandidateSet,
10836 OverloadCandidateSet::iterator *Best,
10837 OverloadingResult OverloadResult,
10838 bool AllowTypoCorrection) {
10839 if (CandidateSet->empty())
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010840 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010841 RParenLoc, /*EmptyLookup=*/true,
10842 AllowTypoCorrection);
10843
10844 switch (OverloadResult) {
John McCall57500772009-12-16 12:17:52 +000010845 case OR_Success: {
Sam Panzer0f384432012-08-21 00:52:01 +000010846 FunctionDecl *FDecl = (*Best)->Function;
Sam Panzer0f384432012-08-21 00:52:01 +000010847 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000010848 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
10849 return ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000010850 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010851 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10852 ExecConfig);
John McCall57500772009-12-16 12:17:52 +000010853 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010854
Richard Smith998a5912011-06-05 22:42:48 +000010855 case OR_No_Viable_Function: {
10856 // Try to recover by looking for viable functions which the user might
10857 // have meant to call.
Sam Panzer0f384432012-08-21 00:52:01 +000010858 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010859 Args, RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000010860 /*EmptyLookup=*/false,
10861 AllowTypoCorrection);
Richard Smith998a5912011-06-05 22:42:48 +000010862 if (!Recovery.isInvalid())
10863 return Recovery;
10864
Sam Panzer0f384432012-08-21 00:52:01 +000010865 SemaRef.Diag(Fn->getLocStart(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010866 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +000010867 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010868 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010869 break;
Richard Smith998a5912011-06-05 22:42:48 +000010870 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010871
10872 case OR_Ambiguous:
Sam Panzer0f384432012-08-21 00:52:01 +000010873 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +000010874 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010875 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010876 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000010877
Sam Panzer0f384432012-08-21 00:52:01 +000010878 case OR_Deleted: {
10879 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
10880 << (*Best)->Function->isDeleted()
10881 << ULE->getName()
10882 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
10883 << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010884 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Argyrios Kyrtzidis3eaa22a2011-11-04 15:58:13 +000010885
Sam Panzer0f384432012-08-21 00:52:01 +000010886 // We emitted an error for the unvailable/deleted function call but keep
10887 // the call in the AST.
10888 FunctionDecl *FDecl = (*Best)->Function;
10889 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010890 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10891 ExecConfig);
Sam Panzer0f384432012-08-21 00:52:01 +000010892 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010893 }
10894
Douglas Gregorb412e172010-07-25 18:17:45 +000010895 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +000010896 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010897}
10898
Sam Panzer0f384432012-08-21 00:52:01 +000010899/// BuildOverloadedCallExpr - Given the call expression that calls Fn
10900/// (which eventually refers to the declaration Func) and the call
10901/// arguments Args/NumArgs, attempt to resolve the function call down
10902/// to a specific function. If overload resolution succeeds, returns
10903/// the call expression produced by overload resolution.
10904/// Otherwise, emits diagnostics and returns ExprError.
10905ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
10906 UnresolvedLookupExpr *ULE,
10907 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010908 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010909 SourceLocation RParenLoc,
10910 Expr *ExecConfig,
10911 bool AllowTypoCorrection) {
Richard Smith100b24a2014-04-17 01:52:14 +000010912 OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
10913 OverloadCandidateSet::CSK_Normal);
Sam Panzer0f384432012-08-21 00:52:01 +000010914 ExprResult result;
10915
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010916 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
10917 &result))
Sam Panzer0f384432012-08-21 00:52:01 +000010918 return result;
10919
10920 OverloadCandidateSet::iterator Best;
10921 OverloadingResult OverloadResult =
10922 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
10923
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010924 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010925 RParenLoc, ExecConfig, &CandidateSet,
10926 &Best, OverloadResult,
10927 AllowTypoCorrection);
10928}
10929
John McCall4c4c1df2010-01-26 03:27:55 +000010930static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +000010931 return Functions.size() > 1 ||
10932 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
10933}
10934
Douglas Gregor084d8552009-03-13 23:49:33 +000010935/// \brief Create a unary operation that may resolve to an overloaded
10936/// operator.
10937///
10938/// \param OpLoc The location of the operator itself (e.g., '*').
10939///
10940/// \param OpcIn The UnaryOperator::Opcode that describes this
10941/// operator.
10942///
James Dennett18348b62012-06-22 08:52:37 +000010943/// \param Fns The set of non-member functions that will be
Douglas Gregor084d8552009-03-13 23:49:33 +000010944/// considered by overload resolution. The caller needs to build this
10945/// set based on the context using, e.g.,
10946/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10947/// set should not contain any member functions; those will be added
10948/// by CreateOverloadedUnaryOp().
10949///
James Dennett91738ff2012-06-22 10:32:46 +000010950/// \param Input The input argument.
John McCalldadc5752010-08-24 06:29:42 +000010951ExprResult
John McCall4c4c1df2010-01-26 03:27:55 +000010952Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
10953 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +000010954 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +000010955 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor084d8552009-03-13 23:49:33 +000010956
10957 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
10958 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
10959 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000010960 // TODO: provide better source location info.
10961 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +000010962
John McCall4124c492011-10-17 18:40:02 +000010963 if (checkPlaceholderForOverload(*this, Input))
10964 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000010965
Craig Topperc3ec1492014-05-26 06:22:03 +000010966 Expr *Args[2] = { Input, nullptr };
Douglas Gregor084d8552009-03-13 23:49:33 +000010967 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +000010968
Douglas Gregor084d8552009-03-13 23:49:33 +000010969 // For post-increment and post-decrement, add the implicit '0' as
10970 // the second argument, so that we know this is a post-increment or
10971 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +000010972 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +000010973 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +000010974 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
10975 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +000010976 NumArgs = 2;
10977 }
10978
Richard Smithe54c3072013-05-05 15:51:06 +000010979 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
10980
Douglas Gregor084d8552009-03-13 23:49:33 +000010981 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +000010982 if (Fns.empty())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010983 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
10984 VK_RValue, OK_Ordinary, OpLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010985
Craig Topperc3ec1492014-05-26 06:22:03 +000010986 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +000010987 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000010988 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000010989 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000010990 /*ADL*/ true, IsOverloaded(Fns),
10991 Fns.begin(), Fns.end());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010992 return new (Context)
10993 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
10994 VK_RValue, OpLoc, false);
Douglas Gregor084d8552009-03-13 23:49:33 +000010995 }
10996
10997 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000010998 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
Douglas Gregor084d8552009-03-13 23:49:33 +000010999
11000 // Add the candidates from the given function set.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011001 AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000011002
11003 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000011004 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000011005
John McCall4c4c1df2010-01-26 03:27:55 +000011006 // Add candidates from ADL.
Richard Smith100b24a2014-04-17 01:52:14 +000011007 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
Craig Topperc3ec1492014-05-26 06:22:03 +000011008 /*ExplicitTemplateArgs*/nullptr,
11009 CandidateSet);
John McCall4c4c1df2010-01-26 03:27:55 +000011010
Douglas Gregor084d8552009-03-13 23:49:33 +000011011 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011012 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000011013
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011014 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11015
Douglas Gregor084d8552009-03-13 23:49:33 +000011016 // Perform overload resolution.
11017 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011018 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +000011019 case OR_Success: {
11020 // We found a built-in operator or an overloaded operator.
11021 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +000011022
Douglas Gregor084d8552009-03-13 23:49:33 +000011023 if (FnDecl) {
11024 // We matched an overloaded operator. Build a call to that
11025 // operator.
Mike Stump11289f42009-09-09 15:08:12 +000011026
Douglas Gregor084d8552009-03-13 23:49:33 +000011027 // Convert the arguments.
11028 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Craig Topperc3ec1492014-05-26 06:22:03 +000011029 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000011030
John Wiegley01296292011-04-08 18:41:53 +000011031 ExprResult InputRes =
Craig Topperc3ec1492014-05-26 06:22:03 +000011032 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000011033 Best->FoundDecl, Method);
11034 if (InputRes.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000011035 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011036 Input = InputRes.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000011037 } else {
11038 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000011039 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +000011040 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000011041 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +000011042 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011043 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +000011044 Input);
Douglas Gregore6600372009-12-23 17:40:29 +000011045 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000011046 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011047 Input = InputInit.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000011048 }
11049
Douglas Gregor084d8552009-03-13 23:49:33 +000011050 // Build the actual expression node.
Nick Lewycky134af912013-02-07 05:08:22 +000011051 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011052 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011053 if (FnExpr.isInvalid())
11054 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +000011055
Richard Smithc1564702013-11-15 02:58:23 +000011056 // Determine the result type.
Alp Toker314cc812014-01-25 16:55:45 +000011057 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000011058 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11059 ResultTy = ResultTy.getNonLValueExprType(Context);
11060
Eli Friedman030eee42009-11-18 03:58:17 +000011061 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +000011062 CallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011063 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
Lang Hames5de91cc2012-10-02 04:45:10 +000011064 ResultTy, VK, OpLoc, false);
John McCall4fa0d5f2010-05-06 18:15:07 +000011065
Alp Toker314cc812014-01-25 16:55:45 +000011066 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
Anders Carlssonf64a3da2009-10-13 21:19:37 +000011067 return ExprError();
11068
John McCallb268a282010-08-23 23:25:46 +000011069 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +000011070 } else {
11071 // We matched a built-in operator. Convert the arguments, then
11072 // break out so that we will build the appropriate built-in
11073 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000011074 ExprResult InputRes =
11075 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
11076 Best->Conversions[0], AA_Passing);
11077 if (InputRes.isInvalid())
11078 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011079 Input = InputRes.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000011080 break;
Douglas Gregor084d8552009-03-13 23:49:33 +000011081 }
John Wiegley01296292011-04-08 18:41:53 +000011082 }
11083
11084 case OR_No_Viable_Function:
Richard Smith998a5912011-06-05 22:42:48 +000011085 // This is an erroneous use of an operator which can be overloaded by
11086 // a non-member function. Check for non-member operators which were
11087 // defined too late to be candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011088 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
Richard Smith998a5912011-06-05 22:42:48 +000011089 // FIXME: Recover by calling the found function.
11090 return ExprError();
11091
John Wiegley01296292011-04-08 18:41:53 +000011092 // No viable function; fall through to handling this as a
11093 // built-in operator, which will produce an error message for us.
11094 break;
11095
11096 case OR_Ambiguous:
11097 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
11098 << UnaryOperator::getOpcodeStr(Opc)
11099 << Input->getType()
11100 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000011101 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
John Wiegley01296292011-04-08 18:41:53 +000011102 UnaryOperator::getOpcodeStr(Opc), OpLoc);
11103 return ExprError();
11104
11105 case OR_Deleted:
11106 Diag(OpLoc, diag::err_ovl_deleted_oper)
11107 << Best->Function->isDeleted()
11108 << UnaryOperator::getOpcodeStr(Opc)
11109 << getDeletedOrUnavailableSuffix(Best->Function)
11110 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000011111 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000011112 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011113 return ExprError();
11114 }
Douglas Gregor084d8552009-03-13 23:49:33 +000011115
11116 // Either we found no viable overloaded operator or we matched a
11117 // built-in operator. In either case, fall through to trying to
11118 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +000011119 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +000011120}
11121
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011122/// \brief Create a binary operation that may resolve to an overloaded
11123/// operator.
11124///
11125/// \param OpLoc The location of the operator itself (e.g., '+').
11126///
11127/// \param OpcIn The BinaryOperator::Opcode that describes this
11128/// operator.
11129///
James Dennett18348b62012-06-22 08:52:37 +000011130/// \param Fns The set of non-member functions that will be
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011131/// considered by overload resolution. The caller needs to build this
11132/// set based on the context using, e.g.,
11133/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11134/// set should not contain any member functions; those will be added
11135/// by CreateOverloadedBinOp().
11136///
11137/// \param LHS Left-hand argument.
11138/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +000011139ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011140Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +000011141 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +000011142 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011143 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011144 Expr *Args[2] = { LHS, RHS };
Craig Topperc3ec1492014-05-26 06:22:03 +000011145 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011146
11147 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
11148 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
11149 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
11150
11151 // If either side is type-dependent, create an appropriate dependent
11152 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +000011153 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +000011154 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011155 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +000011156 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +000011157 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011158 return new (Context) BinaryOperator(
11159 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
11160 OpLoc, FPFeatures.fp_contract);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011161
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011162 return new (Context) CompoundAssignOperator(
11163 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
11164 Context.DependentTy, Context.DependentTy, OpLoc,
11165 FPFeatures.fp_contract);
Douglas Gregor5287f092009-11-05 00:51:44 +000011166 }
John McCall4c4c1df2010-01-26 03:27:55 +000011167
11168 // FIXME: save results of ADL from here?
Craig Topperc3ec1492014-05-26 06:22:03 +000011169 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011170 // TODO: provide better source location info in DNLoc component.
11171 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +000011172 UnresolvedLookupExpr *Fn
Douglas Gregor0da1d432011-02-28 20:01:57 +000011173 = UnresolvedLookupExpr::Create(Context, NamingClass,
11174 NestedNameSpecifierLoc(), OpNameInfo,
11175 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000011176 Fns.begin(), Fns.end());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011177 return new (Context)
11178 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
11179 VK_RValue, OpLoc, FPFeatures.fp_contract);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011180 }
11181
John McCall4124c492011-10-17 18:40:02 +000011182 // Always do placeholder-like conversions on the RHS.
11183 if (checkPlaceholderForOverload(*this, Args[1]))
11184 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011185
John McCall526ab472011-10-25 17:37:35 +000011186 // Do placeholder-like conversion on the LHS; note that we should
11187 // not get here with a PseudoObject LHS.
11188 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall4124c492011-10-17 18:40:02 +000011189 if (checkPlaceholderForOverload(*this, Args[0]))
11190 return ExprError();
11191
Sebastian Redl6a96bf72009-11-18 23:10:33 +000011192 // If this is the assignment operator, we only perform overload resolution
11193 // if the left-hand side is a class or enumeration type. This is actually
11194 // a hack. The standard requires that we do overload resolution between the
11195 // various built-in candidates, but as DR507 points out, this can lead to
11196 // problems. So we do it this way, which pretty much follows what GCC does.
11197 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +000011198 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +000011199 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011200
John McCalle26a8722010-12-04 08:14:53 +000011201 // If this is the .* operator, which is not overloadable, just
11202 // create a built-in binary operator.
11203 if (Opc == BO_PtrMemD)
11204 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11205
Douglas Gregor084d8552009-03-13 23:49:33 +000011206 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000011207 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011208
11209 // Add the candidates from the given function set.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011210 AddFunctionCandidates(Fns, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011211
11212 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000011213 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011214
Richard Smith0daabd72014-09-23 20:31:39 +000011215 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
11216 // performed for an assignment operator (nor for operator[] nor operator->,
11217 // which don't get here).
11218 if (Opc != BO_Assign)
11219 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
11220 /*ExplicitTemplateArgs*/ nullptr,
11221 CandidateSet);
John McCall4c4c1df2010-01-26 03:27:55 +000011222
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011223 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011224 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011225
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011226 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11227
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011228 // Perform overload resolution.
11229 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011230 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +000011231 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011232 // We found a built-in operator or an overloaded operator.
11233 FunctionDecl *FnDecl = Best->Function;
11234
11235 if (FnDecl) {
11236 // We matched an overloaded operator. Build a call to that
11237 // operator.
11238
11239 // Convert the arguments.
11240 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +000011241 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +000011242 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000011243
Chandler Carruth8e543b32010-12-12 08:17:55 +000011244 ExprResult Arg1 =
11245 PerformCopyInitialization(
11246 InitializedEntity::InitializeParameter(Context,
11247 FnDecl->getParamDecl(0)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011248 SourceLocation(), Args[1]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011249 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011250 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011251
John Wiegley01296292011-04-08 18:41:53 +000011252 ExprResult Arg0 =
Craig Topperc3ec1492014-05-26 06:22:03 +000011253 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000011254 Best->FoundDecl, Method);
11255 if (Arg0.isInvalid())
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011256 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011257 Args[0] = Arg0.getAs<Expr>();
11258 Args[1] = RHS = Arg1.getAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011259 } else {
11260 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +000011261 ExprResult Arg0 = PerformCopyInitialization(
11262 InitializedEntity::InitializeParameter(Context,
11263 FnDecl->getParamDecl(0)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011264 SourceLocation(), Args[0]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011265 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011266 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011267
Chandler Carruth8e543b32010-12-12 08:17:55 +000011268 ExprResult Arg1 =
11269 PerformCopyInitialization(
11270 InitializedEntity::InitializeParameter(Context,
11271 FnDecl->getParamDecl(1)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011272 SourceLocation(), Args[1]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011273 if (Arg1.isInvalid())
11274 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011275 Args[0] = LHS = Arg0.getAs<Expr>();
11276 Args[1] = RHS = Arg1.getAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011277 }
11278
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011279 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011280 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000011281 Best->FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011282 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011283 if (FnExpr.isInvalid())
11284 return ExprError();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011285
Richard Smithc1564702013-11-15 02:58:23 +000011286 // Determine the result type.
Alp Toker314cc812014-01-25 16:55:45 +000011287 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000011288 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11289 ResultTy = ResultTy.getNonLValueExprType(Context);
11290
John McCallb268a282010-08-23 23:25:46 +000011291 CXXOperatorCallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011292 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
Lang Hames5de91cc2012-10-02 04:45:10 +000011293 Args, ResultTy, VK, OpLoc,
11294 FPFeatures.fp_contract);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011295
Alp Toker314cc812014-01-25 16:55:45 +000011296 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000011297 FnDecl))
11298 return ExprError();
11299
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000011300 ArrayRef<const Expr *> ArgsArray(Args, 2);
11301 // Cut off the implicit 'this'.
11302 if (isa<CXXMethodDecl>(FnDecl))
11303 ArgsArray = ArgsArray.slice(1);
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011304
11305 // Check for a self move.
11306 if (Op == OO_Equal)
11307 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
11308
Douglas Gregorb4866e82015-06-19 18:13:19 +000011309 checkCall(FnDecl, nullptr, ArgsArray, isa<CXXMethodDecl>(FnDecl), OpLoc,
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000011310 TheCall->getSourceRange(), VariadicDoesNotApply);
11311
John McCallb268a282010-08-23 23:25:46 +000011312 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011313 } else {
11314 // We matched a built-in operator. Convert the arguments, then
11315 // break out so that we will build the appropriate built-in
11316 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000011317 ExprResult ArgsRes0 =
11318 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11319 Best->Conversions[0], AA_Passing);
11320 if (ArgsRes0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011321 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011322 Args[0] = ArgsRes0.get();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011323
John Wiegley01296292011-04-08 18:41:53 +000011324 ExprResult ArgsRes1 =
11325 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11326 Best->Conversions[1], AA_Passing);
11327 if (ArgsRes1.isInvalid())
11328 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011329 Args[1] = ArgsRes1.get();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011330 break;
11331 }
11332 }
11333
Douglas Gregor66950a32009-09-30 21:46:01 +000011334 case OR_No_Viable_Function: {
11335 // C++ [over.match.oper]p9:
11336 // If the operator is the operator , [...] and there are no
11337 // viable functions, then the operator is assumed to be the
11338 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +000011339 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +000011340 break;
11341
Chandler Carruth8e543b32010-12-12 08:17:55 +000011342 // For class as left operand for assignment or compound assigment
11343 // operator do not fall through to handling in built-in, but report that
11344 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +000011345 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011346 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +000011347 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +000011348 Diag(OpLoc, diag::err_ovl_no_viable_oper)
11349 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +000011350 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Eli Friedmana31efa02013-08-28 20:35:35 +000011351 if (Args[0]->getType()->isIncompleteType()) {
11352 Diag(OpLoc, diag::note_assign_lhs_incomplete)
11353 << Args[0]->getType()
11354 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11355 }
Douglas Gregor66950a32009-09-30 21:46:01 +000011356 } else {
Richard Smith998a5912011-06-05 22:42:48 +000011357 // This is an erroneous use of an operator which can be overloaded by
11358 // a non-member function. Check for non-member operators which were
11359 // defined too late to be candidates.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011360 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smith998a5912011-06-05 22:42:48 +000011361 // FIXME: Recover by calling the found function.
11362 return ExprError();
11363
Douglas Gregor66950a32009-09-30 21:46:01 +000011364 // No viable function; try to create a built-in operation, which will
11365 // produce an error. Then, show the non-viable candidates.
11366 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +000011367 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011368 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +000011369 "C++ binary operator overloading is missing candidates!");
11370 if (Result.isInvalid())
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011371 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011372 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011373 return Result;
Douglas Gregor66950a32009-09-30 21:46:01 +000011374 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011375
11376 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000011377 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011378 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +000011379 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +000011380 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011381 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011382 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011383 return ExprError();
11384
11385 case OR_Deleted:
Douglas Gregor74f7d502012-02-15 19:33:52 +000011386 if (isImplicitlyDeleted(Best->Function)) {
11387 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11388 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
Richard Smithde1a4872012-12-28 12:23:24 +000011389 << Context.getRecordType(Method->getParent())
11390 << getSpecialMember(Method);
Richard Smith6f1e2c62012-04-02 20:59:25 +000011391
Richard Smithde1a4872012-12-28 12:23:24 +000011392 // The user probably meant to call this special member. Just
11393 // explain why it's deleted.
11394 NoteDeletedFunction(Method);
11395 return ExprError();
Douglas Gregor74f7d502012-02-15 19:33:52 +000011396 } else {
11397 Diag(OpLoc, diag::err_ovl_deleted_oper)
11398 << Best->Function->isDeleted()
11399 << BinaryOperator::getOpcodeStr(Opc)
11400 << getDeletedOrUnavailableSuffix(Best->Function)
11401 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11402 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011403 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000011404 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011405 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +000011406 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011407
Douglas Gregor66950a32009-09-30 21:46:01 +000011408 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +000011409 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011410}
11411
John McCalldadc5752010-08-24 06:29:42 +000011412ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +000011413Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
11414 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +000011415 Expr *Base, Expr *Idx) {
11416 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +000011417 DeclarationName OpName =
11418 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
11419
11420 // If either side is type-dependent, create an appropriate dependent
11421 // expression.
11422 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
11423
Craig Topperc3ec1492014-05-26 06:22:03 +000011424 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011425 // CHECKME: no 'operator' keyword?
11426 DeclarationNameInfo OpNameInfo(OpName, LLoc);
11427 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +000011428 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000011429 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000011430 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000011431 /*ADL*/ true, /*Overloaded*/ false,
11432 UnresolvedSetIterator(),
11433 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +000011434 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +000011435
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011436 return new (Context)
11437 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
11438 Context.DependentTy, VK_RValue, RLoc, false);
Sebastian Redladba46e2009-10-29 20:17:01 +000011439 }
11440
John McCall4124c492011-10-17 18:40:02 +000011441 // Handle placeholders on both operands.
11442 if (checkPlaceholderForOverload(*this, Args[0]))
11443 return ExprError();
11444 if (checkPlaceholderForOverload(*this, Args[1]))
11445 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011446
Sebastian Redladba46e2009-10-29 20:17:01 +000011447 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000011448 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
Sebastian Redladba46e2009-10-29 20:17:01 +000011449
11450 // Subscript can only be overloaded as a member function.
11451
11452 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000011453 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000011454
11455 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011456 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000011457
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011458 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11459
Sebastian Redladba46e2009-10-29 20:17:01 +000011460 // Perform overload resolution.
11461 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011462 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +000011463 case OR_Success: {
11464 // We found a built-in operator or an overloaded operator.
11465 FunctionDecl *FnDecl = Best->Function;
11466
11467 if (FnDecl) {
11468 // We matched an overloaded operator. Build a call to that
11469 // operator.
11470
John McCalla0296f72010-03-19 07:35:19 +000011471 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall58cc69d2010-01-27 01:50:18 +000011472
Sebastian Redladba46e2009-10-29 20:17:01 +000011473 // Convert the arguments.
11474 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley01296292011-04-08 18:41:53 +000011475 ExprResult Arg0 =
Craig Topperc3ec1492014-05-26 06:22:03 +000011476 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000011477 Best->FoundDecl, Method);
11478 if (Arg0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000011479 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011480 Args[0] = Arg0.get();
Sebastian Redladba46e2009-10-29 20:17:01 +000011481
Anders Carlssona68e51e2010-01-29 18:37:50 +000011482 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000011483 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +000011484 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000011485 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +000011486 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011487 SourceLocation(),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011488 Args[1]);
Anders Carlssona68e51e2010-01-29 18:37:50 +000011489 if (InputInit.isInvalid())
11490 return ExprError();
11491
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011492 Args[1] = InputInit.getAs<Expr>();
Anders Carlssona68e51e2010-01-29 18:37:50 +000011493
Sebastian Redladba46e2009-10-29 20:17:01 +000011494 // Build the actual expression node.
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011495 DeclarationNameInfo OpLocInfo(OpName, LLoc);
11496 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011497 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000011498 Best->FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011499 HadMultipleCandidates,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011500 OpLocInfo.getLoc(),
11501 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000011502 if (FnExpr.isInvalid())
11503 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000011504
Richard Smithc1564702013-11-15 02:58:23 +000011505 // Determine the result type
Alp Toker314cc812014-01-25 16:55:45 +000011506 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000011507 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11508 ResultTy = ResultTy.getNonLValueExprType(Context);
11509
John McCallb268a282010-08-23 23:25:46 +000011510 CXXOperatorCallExpr *TheCall =
11511 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011512 FnExpr.get(), Args,
Lang Hames5de91cc2012-10-02 04:45:10 +000011513 ResultTy, VK, RLoc,
11514 false);
Sebastian Redladba46e2009-10-29 20:17:01 +000011515
Alp Toker314cc812014-01-25 16:55:45 +000011516 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
Sebastian Redladba46e2009-10-29 20:17:01 +000011517 return ExprError();
11518
John McCallb268a282010-08-23 23:25:46 +000011519 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +000011520 } else {
11521 // We matched a built-in operator. Convert the arguments, then
11522 // break out so that we will build the appropriate built-in
11523 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000011524 ExprResult ArgsRes0 =
11525 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11526 Best->Conversions[0], AA_Passing);
11527 if (ArgsRes0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000011528 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011529 Args[0] = ArgsRes0.get();
John Wiegley01296292011-04-08 18:41:53 +000011530
11531 ExprResult ArgsRes1 =
11532 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11533 Best->Conversions[1], AA_Passing);
11534 if (ArgsRes1.isInvalid())
11535 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011536 Args[1] = ArgsRes1.get();
Sebastian Redladba46e2009-10-29 20:17:01 +000011537
11538 break;
11539 }
11540 }
11541
11542 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +000011543 if (CandidateSet.empty())
11544 Diag(LLoc, diag::err_ovl_no_oper)
11545 << Args[0]->getType() << /*subscript*/ 0
11546 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11547 else
11548 Diag(LLoc, diag::err_ovl_no_viable_subscript)
11549 << Args[0]->getType()
11550 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011551 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011552 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +000011553 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000011554 }
11555
11556 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000011557 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011558 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +000011559 << Args[0]->getType() << Args[1]->getType()
11560 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011561 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011562 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000011563 return ExprError();
11564
11565 case OR_Deleted:
11566 Diag(LLoc, diag::err_ovl_deleted_oper)
11567 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000011568 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +000011569 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011570 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011571 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000011572 return ExprError();
11573 }
11574
11575 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +000011576 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000011577}
11578
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011579/// BuildCallToMemberFunction - Build a call to a member
11580/// function. MemExpr is the expression that refers to the member
11581/// function (and includes the object parameter), Args/NumArgs are the
11582/// arguments to the function call (not including the object
11583/// parameter). The caller needs to validate that the member
John McCall0009fcc2011-04-26 20:42:42 +000011584/// expression refers to a non-static member function or an overloaded
11585/// member function.
John McCalldadc5752010-08-24 06:29:42 +000011586ExprResult
Mike Stump11289f42009-09-09 15:08:12 +000011587Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011588 SourceLocation LParenLoc,
11589 MultiExprArg Args,
11590 SourceLocation RParenLoc) {
John McCall0009fcc2011-04-26 20:42:42 +000011591 assert(MemExprE->getType() == Context.BoundMemberTy ||
11592 MemExprE->getType() == Context.OverloadTy);
11593
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011594 // Dig out the member expression. This holds both the object
11595 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +000011596 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011597
John McCall0009fcc2011-04-26 20:42:42 +000011598 // Determine whether this is a call to a pointer-to-member function.
11599 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
11600 assert(op->getType() == Context.BoundMemberTy);
11601 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
11602
11603 QualType fnType =
11604 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
11605
11606 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
11607 QualType resultType = proto->getCallResultType(Context);
Alp Toker314cc812014-01-25 16:55:45 +000011608 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
John McCall0009fcc2011-04-26 20:42:42 +000011609
11610 // Check that the object type isn't more qualified than the
11611 // member function we're calling.
11612 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
11613
11614 QualType objectType = op->getLHS()->getType();
11615 if (op->getOpcode() == BO_PtrMemI)
11616 objectType = objectType->castAs<PointerType>()->getPointeeType();
11617 Qualifiers objectQuals = objectType.getQualifiers();
11618
11619 Qualifiers difference = objectQuals - funcQuals;
11620 difference.removeObjCGCAttr();
11621 difference.removeAddressSpace();
11622 if (difference) {
11623 std::string qualsString = difference.getAsString();
11624 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
11625 << fnType.getUnqualifiedType()
11626 << qualsString
11627 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
11628 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011629
John McCall0009fcc2011-04-26 20:42:42 +000011630 CXXMemberCallExpr *call
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011631 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall0009fcc2011-04-26 20:42:42 +000011632 resultType, valueKind, RParenLoc);
11633
Alp Toker314cc812014-01-25 16:55:45 +000011634 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
Craig Topperc3ec1492014-05-26 06:22:03 +000011635 call, nullptr))
John McCall0009fcc2011-04-26 20:42:42 +000011636 return ExprError();
11637
Craig Topperc3ec1492014-05-26 06:22:03 +000011638 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
John McCall0009fcc2011-04-26 20:42:42 +000011639 return ExprError();
11640
Richard Trieu9be9c682013-06-22 02:30:38 +000011641 if (CheckOtherCall(call, proto))
11642 return ExprError();
11643
John McCall0009fcc2011-04-26 20:42:42 +000011644 return MaybeBindToTemporary(call);
11645 }
11646
David Majnemerced8bdf2015-02-25 17:36:15 +000011647 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
11648 return new (Context)
11649 CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc);
11650
John McCall4124c492011-10-17 18:40:02 +000011651 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011652 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000011653 return ExprError();
11654
John McCall10eae182009-11-30 22:42:35 +000011655 MemberExpr *MemExpr;
Craig Topperc3ec1492014-05-26 06:22:03 +000011656 CXXMethodDecl *Method = nullptr;
11657 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
11658 NestedNameSpecifier *Qualifier = nullptr;
John McCall10eae182009-11-30 22:42:35 +000011659 if (isa<MemberExpr>(NakedMemExpr)) {
11660 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +000011661 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +000011662 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +000011663 Qualifier = MemExpr->getQualifier();
John McCall4124c492011-10-17 18:40:02 +000011664 UnbridgedCasts.restore();
Nick Lewyckye283c552015-08-25 22:33:16 +000011665
11666 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
11667 Diag(MemExprE->getLocStart(),
11668 diag::err_ovl_no_viable_member_function_in_call)
11669 << Method << Method->getSourceRange();
11670 Diag(Method->getLocation(),
11671 diag::note_ovl_candidate_disabled_by_enable_if_attr)
11672 << Attr->getCond()->getSourceRange() << Attr->getMessage();
11673 return ExprError();
11674 }
John McCall10eae182009-11-30 22:42:35 +000011675 } else {
11676 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +000011677 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011678
John McCall6e9f8f62009-12-03 04:06:58 +000011679 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +000011680 Expr::Classification ObjectClassification
11681 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
11682 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +000011683
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011684 // Add overload candidates
Richard Smith100b24a2014-04-17 01:52:14 +000011685 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
11686 OverloadCandidateSet::CSK_Normal);
Mike Stump11289f42009-09-09 15:08:12 +000011687
John McCall2d74de92009-12-01 22:10:20 +000011688 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000011689 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCall2d74de92009-12-01 22:10:20 +000011690 if (UnresExpr->hasExplicitTemplateArgs()) {
11691 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11692 TemplateArgs = &TemplateArgsBuffer;
11693 }
11694
John McCall10eae182009-11-30 22:42:35 +000011695 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
11696 E = UnresExpr->decls_end(); I != E; ++I) {
11697
John McCall6e9f8f62009-12-03 04:06:58 +000011698 NamedDecl *Func = *I;
11699 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
11700 if (isa<UsingShadowDecl>(Func))
11701 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
11702
Douglas Gregor02824322011-01-26 19:30:28 +000011703
Francois Pichet64225792011-01-18 05:04:39 +000011704 // Microsoft supports direct constructor calls.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011705 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011706 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011707 Args, CandidateSet);
Francois Pichet64225792011-01-18 05:04:39 +000011708 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +000011709 // If explicit template arguments were provided, we can't call a
11710 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +000011711 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +000011712 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011713
John McCalla0296f72010-03-19 07:35:19 +000011714 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011715 ObjectClassification, Args, CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +000011716 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000011717 } else {
John McCall10eae182009-11-30 22:42:35 +000011718 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +000011719 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011720 ObjectType, ObjectClassification,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011721 Args, CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000011722 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000011723 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000011724 }
Mike Stump11289f42009-09-09 15:08:12 +000011725
John McCall10eae182009-11-30 22:42:35 +000011726 DeclarationName DeclName = UnresExpr->getMemberName();
11727
John McCall4124c492011-10-17 18:40:02 +000011728 UnbridgedCasts.restore();
11729
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011730 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011731 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +000011732 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011733 case OR_Success:
11734 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +000011735 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +000011736 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000011737 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
11738 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000011739 // If FoundDecl is different from Method (such as if one is a template
11740 // and the other a specialization), make sure DiagnoseUseOfDecl is
11741 // called on both.
11742 // FIXME: This would be more comprehensively addressed by modifying
11743 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
11744 // being used.
11745 if (Method != FoundDecl.getDecl() &&
11746 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
11747 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011748 break;
11749
11750 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +000011751 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011752 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000011753 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011754 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011755 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000011756 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011757
11758 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +000011759 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000011760 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011761 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011762 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000011763 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000011764
11765 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +000011766 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +000011767 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000011768 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000011769 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000011770 << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011771 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000011772 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000011773 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011774 }
11775
John McCall16df1e52010-03-30 21:47:33 +000011776 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +000011777
John McCall2d74de92009-12-01 22:10:20 +000011778 // If overload resolution picked a static member, build a
11779 // non-member call based on that function.
11780 if (Method->isStatic()) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011781 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
11782 RParenLoc);
John McCall2d74de92009-12-01 22:10:20 +000011783 }
11784
John McCall10eae182009-11-30 22:42:35 +000011785 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011786 }
11787
Alp Toker314cc812014-01-25 16:55:45 +000011788 QualType ResultType = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000011789 ExprValueKind VK = Expr::getValueKindForType(ResultType);
11790 ResultType = ResultType.getNonLValueExprType(Context);
11791
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011792 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011793 CXXMemberCallExpr *TheCall =
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011794 new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall7decc9e2010-11-18 06:31:45 +000011795 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011796
Eli Bendersky291a57e2014-09-25 23:59:08 +000011797 // (CUDA B.1): Check for invalid calls between targets.
11798 if (getLangOpts().CUDA) {
11799 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) {
11800 if (CheckCUDATarget(Caller, Method)) {
11801 Diag(MemExpr->getMemberLoc(), diag::err_ref_bad_target)
11802 << IdentifyCUDATarget(Method) << Method->getIdentifier()
11803 << IdentifyCUDATarget(Caller);
11804 return ExprError();
11805 }
11806 }
11807 }
11808
Anders Carlssonc4859ba2009-10-10 00:06:20 +000011809 // Check for a valid return type.
Alp Toker314cc812014-01-25 16:55:45 +000011810 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +000011811 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +000011812 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011813
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011814 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +000011815 // We only need to do this if there was actually an overload; otherwise
11816 // it was done at lookup.
John Wiegley01296292011-04-08 18:41:53 +000011817 if (!Method->isStatic()) {
11818 ExprResult ObjectArg =
11819 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
11820 FoundDecl, Method);
11821 if (ObjectArg.isInvalid())
11822 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011823 MemExpr->setBase(ObjectArg.get());
John Wiegley01296292011-04-08 18:41:53 +000011824 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011825
11826 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +000011827 const FunctionProtoType *Proto =
11828 Method->getType()->getAs<FunctionProtoType>();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011829 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011830 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +000011831 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011832
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011833 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000011834
Richard Smith55ce3522012-06-25 20:30:08 +000011835 if (CheckFunctionCall(Method, TheCall, Proto))
John McCall2d74de92009-12-01 22:10:20 +000011836 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +000011837
Anders Carlsson47061ee2011-05-06 14:25:31 +000011838 if ((isa<CXXConstructorDecl>(CurContext) ||
11839 isa<CXXDestructorDecl>(CurContext)) &&
11840 TheCall->getMethodDecl()->isPure()) {
11841 const CXXMethodDecl *MD = TheCall->getMethodDecl();
11842
Davide Italianoccb37382015-07-14 23:36:10 +000011843 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
11844 MemExpr->performsVirtualDispatch(getLangOpts())) {
11845 Diag(MemExpr->getLocStart(),
Anders Carlsson47061ee2011-05-06 14:25:31 +000011846 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
11847 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
11848 << MD->getParent()->getDeclName();
11849
11850 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Davide Italianoccb37382015-07-14 23:36:10 +000011851 if (getLangOpts().AppleKext)
11852 Diag(MemExpr->getLocStart(),
11853 diag::note_pure_qualified_call_kext)
11854 << MD->getParent()->getDeclName()
11855 << MD->getDeclName();
Chandler Carruth59259262011-06-27 08:31:58 +000011856 }
Anders Carlsson47061ee2011-05-06 14:25:31 +000011857 }
John McCallb268a282010-08-23 23:25:46 +000011858 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011859}
11860
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011861/// BuildCallToObjectOfClassType - Build a call to an object of class
11862/// type (C++ [over.call.object]), which can end up invoking an
11863/// overloaded function call operator (@c operator()) or performing a
11864/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +000011865ExprResult
John Wiegley01296292011-04-08 18:41:53 +000011866Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregorb0846b02008-12-06 00:22:45 +000011867 SourceLocation LParenLoc,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011868 MultiExprArg Args,
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011869 SourceLocation RParenLoc) {
John McCall4124c492011-10-17 18:40:02 +000011870 if (checkPlaceholderForOverload(*this, Obj))
11871 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011872 ExprResult Object = Obj;
John McCall4124c492011-10-17 18:40:02 +000011873
11874 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011875 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000011876 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011877
Nico Weberb58e51c2014-11-19 05:21:39 +000011878 assert(Object.get()->getType()->isRecordType() &&
11879 "Requires object type argument");
John Wiegley01296292011-04-08 18:41:53 +000011880 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +000011881
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011882 // C++ [over.call.object]p1:
11883 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +000011884 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011885 // candidate functions includes at least the function call
11886 // operators of T. The function call operators of T are obtained by
11887 // ordinary lookup of the name operator() in the context of
11888 // (E).operator().
Richard Smith100b24a2014-04-17 01:52:14 +000011889 OverloadCandidateSet CandidateSet(LParenLoc,
11890 OverloadCandidateSet::CSK_Operator);
Douglas Gregor91f84212008-12-11 16:49:14 +000011891 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +000011892
John Wiegley01296292011-04-08 18:41:53 +000011893 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000011894 diag::err_incomplete_object_call, Object.get()))
Douglas Gregorc473cbb2009-11-15 07:48:03 +000011895 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011896
John McCall27b18f82009-11-17 02:14:36 +000011897 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
11898 LookupQualifiedName(R, Record->getDecl());
11899 R.suppressDiagnostics();
11900
Douglas Gregorc473cbb2009-11-15 07:48:03 +000011901 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +000011902 Oper != OperEnd; ++Oper) {
John Wiegley01296292011-04-08 18:41:53 +000011903 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011904 Object.get()->Classify(Context),
11905 Args, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +000011906 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +000011907 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011908
Douglas Gregorab7897a2008-11-19 22:57:39 +000011909 // C++ [over.call.object]p2:
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000011910 // In addition, for each (non-explicit in C++0x) conversion function
11911 // declared in T of the form
Douglas Gregorab7897a2008-11-19 22:57:39 +000011912 //
11913 // operator conversion-type-id () cv-qualifier;
11914 //
11915 // where cv-qualifier is the same cv-qualification as, or a
11916 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +000011917 // denotes the type "pointer to function of (P1,...,Pn) returning
11918 // R", or the type "reference to pointer to function of
11919 // (P1,...,Pn) returning R", or the type "reference to function
11920 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +000011921 // is also considered as a candidate function. Similarly,
11922 // surrogate call functions are added to the set of candidate
11923 // functions for each conversion function declared in an
11924 // accessible base class provided the function is not hidden
11925 // within T by another intervening declaration.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +000011926 const auto &Conversions =
11927 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
11928 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +000011929 NamedDecl *D = *I;
11930 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
11931 if (isa<UsingShadowDecl>(D))
11932 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011933
Douglas Gregor74ba25c2009-10-21 06:18:39 +000011934 // Skip over templated conversion functions; they aren't
11935 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +000011936 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +000011937 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +000011938
John McCall6e9f8f62009-12-03 04:06:58 +000011939 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000011940 if (!Conv->isExplicit()) {
11941 // Strip the reference type (if any) and then the pointer type (if
11942 // any) to get down to what might be a function type.
11943 QualType ConvType = Conv->getConversionType().getNonReferenceType();
11944 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11945 ConvType = ConvPtrType->getPointeeType();
John McCalld14a8642009-11-21 08:51:07 +000011946
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000011947 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
11948 {
11949 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011950 Object.get(), Args, CandidateSet);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000011951 }
11952 }
Douglas Gregorab7897a2008-11-19 22:57:39 +000011953 }
Mike Stump11289f42009-09-09 15:08:12 +000011954
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011955 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11956
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011957 // Perform overload resolution.
11958 OverloadCandidateSet::iterator Best;
John Wiegley01296292011-04-08 18:41:53 +000011959 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall5c32be02010-08-24 20:38:10 +000011960 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011961 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +000011962 // Overload resolution succeeded; we'll build the appropriate call
11963 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011964 break;
11965
11966 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +000011967 if (CandidateSet.empty())
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011968 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley01296292011-04-08 18:41:53 +000011969 << Object.get()->getType() << /*call*/ 1
11970 << Object.get()->getSourceRange();
John McCall02374852010-01-07 02:04:15 +000011971 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011972 Diag(Object.get()->getLocStart(),
John McCall02374852010-01-07 02:04:15 +000011973 diag::err_ovl_no_viable_object_call)
John Wiegley01296292011-04-08 18:41:53 +000011974 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011975 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011976 break;
11977
11978 case OR_Ambiguous:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011979 Diag(Object.get()->getLocStart(),
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011980 diag::err_ovl_ambiguous_object_call)
John Wiegley01296292011-04-08 18:41:53 +000011981 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011982 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011983 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000011984
11985 case OR_Deleted:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011986 Diag(Object.get()->getLocStart(),
Douglas Gregor171c45a2009-02-18 21:56:37 +000011987 diag::err_ovl_deleted_object_call)
11988 << Best->Function->isDeleted()
John Wiegley01296292011-04-08 18:41:53 +000011989 << Object.get()->getType()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000011990 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley01296292011-04-08 18:41:53 +000011991 << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011992 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000011993 break;
Mike Stump11289f42009-09-09 15:08:12 +000011994 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011995
Douglas Gregorb412e172010-07-25 18:17:45 +000011996 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011997 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011998
John McCall4124c492011-10-17 18:40:02 +000011999 UnbridgedCasts.restore();
12000
Craig Topperc3ec1492014-05-26 06:22:03 +000012001 if (Best->Function == nullptr) {
Douglas Gregorab7897a2008-11-19 22:57:39 +000012002 // Since there is no function declaration, this is one of the
12003 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +000012004 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +000012005 = cast<CXXConversionDecl>(
12006 Best->Conversions[0].UserDefined.ConversionFunction);
12007
Craig Topperc3ec1492014-05-26 06:22:03 +000012008 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
12009 Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000012010 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
12011 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000012012 assert(Conv == Best->FoundDecl.getDecl() &&
12013 "Found Decl & conversion-to-functionptr should be same, right?!");
Douglas Gregorab7897a2008-11-19 22:57:39 +000012014 // We selected one of the surrogate functions that converts the
12015 // object parameter to a function pointer. Perform the conversion
12016 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012017
Fariborz Jahanian774cf792009-09-28 18:35:46 +000012018 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +000012019 // and then call it.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012020 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
12021 Conv, HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +000012022 if (Call.isInvalid())
12023 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +000012024 // Record usage of conversion in an implicit cast.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012025 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
12026 CK_UserDefinedConversion, Call.get(),
12027 nullptr, VK_RValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012028
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012029 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +000012030 }
12031
Craig Topperc3ec1492014-05-26 06:22:03 +000012032 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
John McCall49ec2e62010-01-28 01:54:34 +000012033
Douglas Gregorab7897a2008-11-19 22:57:39 +000012034 // We found an overloaded operator(). Build a CXXOperatorCallExpr
12035 // that calls this method, using Object for the implicit object
12036 // parameter and passing along the remaining arguments.
12037 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Nico Weber1fefe412012-11-09 06:06:14 +000012038
12039 // An error diagnostic has already been printed when parsing the declaration.
Nico Weber9512d3f2012-11-09 08:38:04 +000012040 if (Method->isInvalidDecl())
Nico Weber1fefe412012-11-09 06:06:14 +000012041 return ExprError();
12042
Chandler Carruth8e543b32010-12-12 08:17:55 +000012043 const FunctionProtoType *Proto =
12044 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012045
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012046 unsigned NumParams = Proto->getNumParams();
Mike Stump11289f42009-09-09 15:08:12 +000012047
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012048 DeclarationNameInfo OpLocInfo(
12049 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
12050 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Nick Lewycky134af912013-02-07 05:08:22 +000012051 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012052 HadMultipleCandidates,
12053 OpLocInfo.getLoc(),
12054 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000012055 if (NewFn.isInvalid())
12056 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012057
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012058 // Build the full argument list for the method call (the implicit object
12059 // parameter is placed at the beginning of the list).
Ahmed Charlesaf94d562014-03-09 11:34:25 +000012060 std::unique_ptr<Expr * []> MethodArgs(new Expr *[Args.size() + 1]);
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012061 MethodArgs[0] = Object.get();
12062 std::copy(Args.begin(), Args.end(), &MethodArgs[1]);
12063
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012064 // Once we've built TheCall, all of the expressions are properly
12065 // owned.
Alp Toker314cc812014-01-25 16:55:45 +000012066 QualType ResultTy = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000012067 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12068 ResultTy = ResultTy.getNonLValueExprType(Context);
12069
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012070 CXXOperatorCallExpr *TheCall = new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012071 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(),
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012072 llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1),
12073 ResultTy, VK, RParenLoc, false);
12074 MethodArgs.reset();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012075
Alp Toker314cc812014-01-25 16:55:45 +000012076 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
Anders Carlsson3d5829c2009-10-13 21:49:31 +000012077 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012078
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012079 // We may have default arguments. If so, we need to allocate more
12080 // slots in the call for them.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012081 if (Args.size() < NumParams)
12082 TheCall->setNumArgs(Context, NumParams + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012083
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000012084 bool IsError = false;
12085
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012086 // Initialize the implicit object parameter.
John Wiegley01296292011-04-08 18:41:53 +000012087 ExprResult ObjRes =
Craig Topperc3ec1492014-05-26 06:22:03 +000012088 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012089 Best->FoundDecl, Method);
12090 if (ObjRes.isInvalid())
12091 IsError = true;
12092 else
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012093 Object = ObjRes;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012094 TheCall->setArg(0, Object.get());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000012095
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012096 // Check the argument types.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012097 for (unsigned i = 0; i != NumParams; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012098 Expr *Arg;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012099 if (i < Args.size()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012100 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +000012101
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012102 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012103
John McCalldadc5752010-08-24 06:29:42 +000012104 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012105 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000012106 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012107 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +000012108 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012109
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012110 IsError |= InputInit.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012111 Arg = InputInit.getAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012112 } else {
John McCalldadc5752010-08-24 06:29:42 +000012113 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +000012114 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
12115 if (DefArg.isInvalid()) {
12116 IsError = true;
12117 break;
12118 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012119
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012120 Arg = DefArg.getAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012121 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012122
12123 TheCall->setArg(i + 1, Arg);
12124 }
12125
12126 // If this is a variadic call, handle args passed through "...".
12127 if (Proto->isVariadic()) {
12128 // Promote the arguments (C99 6.5.2.2p7).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012129 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
Craig Topperc3ec1492014-05-26 06:22:03 +000012130 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
12131 nullptr);
John Wiegley01296292011-04-08 18:41:53 +000012132 IsError |= Arg.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012133 TheCall->setArg(i + 1, Arg.get());
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012134 }
12135 }
12136
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000012137 if (IsError) return true;
12138
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012139 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000012140
Richard Smith55ce3522012-06-25 20:30:08 +000012141 if (CheckFunctionCall(Method, TheCall, Proto))
Anders Carlssonbc4c1072009-08-16 01:56:34 +000012142 return true;
12143
John McCalle172be52010-08-24 06:09:16 +000012144 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012145}
12146
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012147/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +000012148/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012149/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +000012150ExprResult
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000012151Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
12152 bool *NoArrowOperatorFound) {
Chandler Carruth8e543b32010-12-12 08:17:55 +000012153 assert(Base->getType()->isRecordType() &&
12154 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +000012155
John McCall4124c492011-10-17 18:40:02 +000012156 if (checkPlaceholderForOverload(*this, Base))
12157 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012158
John McCallbc077cf2010-02-08 23:07:23 +000012159 SourceLocation Loc = Base->getExprLoc();
12160
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012161 // C++ [over.ref]p1:
12162 //
12163 // [...] An expression x->m is interpreted as (x.operator->())->m
12164 // for a class object x of type T if T::operator->() exists and if
12165 // the operator is selected as the best match function by the
12166 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +000012167 DeclarationName OpName =
12168 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
Richard Smith100b24a2014-04-17 01:52:14 +000012169 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
Ted Kremenekc23c7e62009-07-29 21:53:49 +000012170 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +000012171
John McCallbc077cf2010-02-08 23:07:23 +000012172 if (RequireCompleteType(Loc, Base->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012173 diag::err_typecheck_incomplete_tag, Base))
Eli Friedman132e70b2009-11-18 01:28:03 +000012174 return ExprError();
12175
John McCall27b18f82009-11-17 02:14:36 +000012176 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
12177 LookupQualifiedName(R, BaseRecord->getDecl());
12178 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +000012179
12180 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +000012181 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +000012182 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +000012183 None, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +000012184 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012185
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012186 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12187
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012188 // Perform overload resolution.
12189 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012190 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012191 case OR_Success:
12192 // Overload resolution succeeded; we'll build the call below.
12193 break;
12194
12195 case OR_No_Viable_Function:
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012196 if (CandidateSet.empty()) {
12197 QualType BaseType = Base->getType();
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000012198 if (NoArrowOperatorFound) {
12199 // Report this specific error to the caller instead of emitting a
12200 // diagnostic, as requested.
12201 *NoArrowOperatorFound = true;
12202 return ExprError();
12203 }
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000012204 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
12205 << BaseType << Base->getSourceRange();
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012206 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000012207 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012208 << FixItHint::CreateReplacement(OpLoc, ".");
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012209 }
12210 } else
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012211 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +000012212 << "operator->" << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012213 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012214 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012215
12216 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000012217 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
12218 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012219 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012220 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000012221
12222 case OR_Deleted:
12223 Diag(OpLoc, diag::err_ovl_deleted_oper)
12224 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012225 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012226 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012227 << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012228 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012229 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012230 }
12231
Craig Topperc3ec1492014-05-26 06:22:03 +000012232 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
John McCalla0296f72010-03-19 07:35:19 +000012233
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012234 // Convert the object parameter.
12235 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000012236 ExprResult BaseResult =
Craig Topperc3ec1492014-05-26 06:22:03 +000012237 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012238 Best->FoundDecl, Method);
12239 if (BaseResult.isInvalid())
Douglas Gregord8061562009-08-06 03:17:00 +000012240 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012241 Base = BaseResult.get();
Douglas Gregor9ecea262008-11-21 03:04:22 +000012242
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012243 // Build the operator call.
Nick Lewycky134af912013-02-07 05:08:22 +000012244 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012245 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000012246 if (FnExpr.isInvalid())
12247 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012248
Alp Toker314cc812014-01-25 16:55:45 +000012249 QualType ResultTy = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000012250 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12251 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +000012252 CXXOperatorCallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012253 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
Lang Hames5de91cc2012-10-02 04:45:10 +000012254 Base, ResultTy, VK, OpLoc, false);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000012255
Alp Toker314cc812014-01-25 16:55:45 +000012256 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000012257 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +000012258
12259 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012260}
12261
Richard Smithbcc22fc2012-03-09 08:00:36 +000012262/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
12263/// a literal operator described by the provided lookup results.
12264ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
12265 DeclarationNameInfo &SuffixInfo,
12266 ArrayRef<Expr*> Args,
12267 SourceLocation LitEndLoc,
12268 TemplateArgumentListInfo *TemplateArgs) {
12269 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smithc67fdd42012-03-07 08:35:16 +000012270
Richard Smith100b24a2014-04-17 01:52:14 +000012271 OverloadCandidateSet CandidateSet(UDSuffixLoc,
12272 OverloadCandidateSet::CSK_Normal);
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000012273 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
12274 /*SuppressUserConversions=*/true);
Richard Smithc67fdd42012-03-07 08:35:16 +000012275
Richard Smithbcc22fc2012-03-09 08:00:36 +000012276 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12277
Richard Smithbcc22fc2012-03-09 08:00:36 +000012278 // Perform overload resolution. This will usually be trivial, but might need
12279 // to perform substitutions for a literal operator template.
12280 OverloadCandidateSet::iterator Best;
12281 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
12282 case OR_Success:
12283 case OR_Deleted:
12284 break;
12285
12286 case OR_No_Viable_Function:
12287 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
12288 << R.getLookupName();
12289 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12290 return ExprError();
12291
12292 case OR_Ambiguous:
12293 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
12294 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
12295 return ExprError();
Richard Smithc67fdd42012-03-07 08:35:16 +000012296 }
12297
Richard Smithbcc22fc2012-03-09 08:00:36 +000012298 FunctionDecl *FD = Best->Function;
Nick Lewycky134af912013-02-07 05:08:22 +000012299 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
12300 HadMultipleCandidates,
Richard Smithbcc22fc2012-03-09 08:00:36 +000012301 SuffixInfo.getLoc(),
12302 SuffixInfo.getInfo());
12303 if (Fn.isInvalid())
12304 return true;
Richard Smithc67fdd42012-03-07 08:35:16 +000012305
12306 // Check the argument types. This should almost always be a no-op, except
12307 // that array-to-pointer decay is applied to string literals.
Richard Smithc67fdd42012-03-07 08:35:16 +000012308 Expr *ConvArgs[2];
Richard Smithe54c3072013-05-05 15:51:06 +000012309 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Richard Smithc67fdd42012-03-07 08:35:16 +000012310 ExprResult InputInit = PerformCopyInitialization(
12311 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
12312 SourceLocation(), Args[ArgIdx]);
12313 if (InputInit.isInvalid())
12314 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012315 ConvArgs[ArgIdx] = InputInit.get();
Richard Smithc67fdd42012-03-07 08:35:16 +000012316 }
12317
Alp Toker314cc812014-01-25 16:55:45 +000012318 QualType ResultTy = FD->getReturnType();
Richard Smithc67fdd42012-03-07 08:35:16 +000012319 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12320 ResultTy = ResultTy.getNonLValueExprType(Context);
12321
Richard Smithc67fdd42012-03-07 08:35:16 +000012322 UserDefinedLiteral *UDL =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012323 new (Context) UserDefinedLiteral(Context, Fn.get(),
Benjamin Kramerc215e762012-08-24 11:54:20 +000012324 llvm::makeArrayRef(ConvArgs, Args.size()),
Richard Smithc67fdd42012-03-07 08:35:16 +000012325 ResultTy, VK, LitEndLoc, UDSuffixLoc);
12326
Alp Toker314cc812014-01-25 16:55:45 +000012327 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
Richard Smithc67fdd42012-03-07 08:35:16 +000012328 return ExprError();
12329
Craig Topperc3ec1492014-05-26 06:22:03 +000012330 if (CheckFunctionCall(FD, UDL, nullptr))
Richard Smithc67fdd42012-03-07 08:35:16 +000012331 return ExprError();
12332
12333 return MaybeBindToTemporary(UDL);
12334}
12335
Sam Panzer0f384432012-08-21 00:52:01 +000012336/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
12337/// given LookupResult is non-empty, it is assumed to describe a member which
12338/// will be invoked. Otherwise, the function will be found via argument
12339/// dependent lookup.
12340/// CallExpr is set to a valid expression and FRS_Success returned on success,
12341/// otherwise CallExpr is set to ExprError() and some non-success value
12342/// is returned.
12343Sema::ForRangeStatus
12344Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
12345 SourceLocation RangeLoc, VarDecl *Decl,
12346 BeginEndFunction BEF,
12347 const DeclarationNameInfo &NameInfo,
12348 LookupResult &MemberLookup,
12349 OverloadCandidateSet *CandidateSet,
12350 Expr *Range, ExprResult *CallExpr) {
12351 CandidateSet->clear();
12352 if (!MemberLookup.empty()) {
12353 ExprResult MemberRef =
12354 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
12355 /*IsPtr=*/false, CXXScopeSpec(),
12356 /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +000012357 /*FirstQualifierInScope=*/nullptr,
Sam Panzer0f384432012-08-21 00:52:01 +000012358 MemberLookup,
Aaron Ballman6924dcd2015-09-01 14:49:24 +000012359 /*TemplateArgs=*/nullptr, S);
Sam Panzer0f384432012-08-21 00:52:01 +000012360 if (MemberRef.isInvalid()) {
12361 *CallExpr = ExprError();
12362 Diag(Range->getLocStart(), diag::note_in_for_range)
12363 << RangeLoc << BEF << Range->getType();
12364 return FRS_DiagnosticIssued;
12365 }
Craig Topperc3ec1492014-05-26 06:22:03 +000012366 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
Sam Panzer0f384432012-08-21 00:52:01 +000012367 if (CallExpr->isInvalid()) {
12368 *CallExpr = ExprError();
12369 Diag(Range->getLocStart(), diag::note_in_for_range)
12370 << RangeLoc << BEF << Range->getType();
12371 return FRS_DiagnosticIssued;
12372 }
12373 } else {
12374 UnresolvedSet<0> FoundNames;
Sam Panzer0f384432012-08-21 00:52:01 +000012375 UnresolvedLookupExpr *Fn =
Craig Topperc3ec1492014-05-26 06:22:03 +000012376 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
Sam Panzer0f384432012-08-21 00:52:01 +000012377 NestedNameSpecifierLoc(), NameInfo,
12378 /*NeedsADL=*/true, /*Overloaded=*/false,
Richard Smithb6626742012-10-18 17:56:02 +000012379 FoundNames.begin(), FoundNames.end());
Sam Panzer0f384432012-08-21 00:52:01 +000012380
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012381 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
Sam Panzer0f384432012-08-21 00:52:01 +000012382 CandidateSet, CallExpr);
12383 if (CandidateSet->empty() || CandidateSetError) {
12384 *CallExpr = ExprError();
12385 return FRS_NoViableFunction;
12386 }
12387 OverloadCandidateSet::iterator Best;
12388 OverloadingResult OverloadResult =
12389 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
12390
12391 if (OverloadResult == OR_No_Viable_Function) {
12392 *CallExpr = ExprError();
12393 return FRS_NoViableFunction;
12394 }
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012395 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
Craig Topperc3ec1492014-05-26 06:22:03 +000012396 Loc, nullptr, CandidateSet, &Best,
Sam Panzer0f384432012-08-21 00:52:01 +000012397 OverloadResult,
12398 /*AllowTypoCorrection=*/false);
12399 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
12400 *CallExpr = ExprError();
12401 Diag(Range->getLocStart(), diag::note_in_for_range)
12402 << RangeLoc << BEF << Range->getType();
12403 return FRS_DiagnosticIssued;
12404 }
12405 }
12406 return FRS_Success;
12407}
12408
12409
Douglas Gregorcd695e52008-11-10 20:40:00 +000012410/// FixOverloadedFunctionReference - E is an expression that refers to
12411/// a C++ overloaded function (possibly with some parentheses and
12412/// perhaps a '&' around it). We have resolved the overloaded function
12413/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +000012414/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +000012415Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +000012416 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +000012417 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000012418 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
12419 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000012420 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012421 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012422
Douglas Gregor51c538b2009-11-20 19:42:02 +000012423 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012424 }
12425
Douglas Gregor51c538b2009-11-20 19:42:02 +000012426 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000012427 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
12428 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012429 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +000012430 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +000012431 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +000012432 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +000012433 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012434 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012435
12436 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +000012437 ICE->getCastKind(),
Craig Topperc3ec1492014-05-26 06:22:03 +000012438 SubExpr, nullptr,
John McCall2536c6d2010-08-25 10:28:54 +000012439 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012440 }
12441
Douglas Gregor51c538b2009-11-20 19:42:02 +000012442 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +000012443 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +000012444 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +000012445 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
12446 if (Method->isStatic()) {
12447 // Do nothing: static member functions aren't any different
12448 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +000012449 } else {
Alp Toker028ed912013-12-06 17:56:43 +000012450 // Fix the subexpression, which really has to be an
John McCalle66edc12009-11-24 19:00:30 +000012451 // UnresolvedLookupExpr holding an overloaded member function
12452 // or template.
John McCall16df1e52010-03-30 21:47:33 +000012453 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12454 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +000012455 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012456 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +000012457
John McCalld14a8642009-11-21 08:51:07 +000012458 assert(isa<DeclRefExpr>(SubExpr)
12459 && "fixed to something other than a decl ref");
12460 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
12461 && "fixed to a member ref with no nested name qualifier");
12462
12463 // We have taken the address of a pointer to member
12464 // function. Perform the computation here so that we get the
12465 // appropriate pointer to member type.
12466 QualType ClassType
12467 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
12468 QualType MemPtrType
12469 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
12470
John McCall7decc9e2010-11-18 06:31:45 +000012471 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
12472 VK_RValue, OK_Ordinary,
12473 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +000012474 }
12475 }
John McCall16df1e52010-03-30 21:47:33 +000012476 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12477 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000012478 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012479 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012480
John McCalle3027922010-08-25 11:45:40 +000012481 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +000012482 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +000012483 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +000012484 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012485 }
John McCalld14a8642009-11-21 08:51:07 +000012486
12487 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +000012488 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000012489 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCalle66edc12009-11-24 19:00:30 +000012490 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +000012491 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
12492 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +000012493 }
12494
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012495 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12496 ULE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000012497 ULE->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012498 Fn,
John McCall113bee02012-03-10 09:33:50 +000012499 /*enclosing*/ false, // FIXME?
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012500 ULE->getNameLoc(),
12501 Fn->getType(),
12502 VK_LValue,
12503 Found.getDecl(),
12504 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000012505 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012506 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
12507 return DRE;
John McCalld14a8642009-11-21 08:51:07 +000012508 }
12509
John McCall10eae182009-11-30 22:42:35 +000012510 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +000012511 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000012512 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCall2d74de92009-12-01 22:10:20 +000012513 if (MemExpr->hasExplicitTemplateArgs()) {
12514 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12515 TemplateArgs = &TemplateArgsBuffer;
12516 }
John McCall6b51f282009-11-23 01:53:49 +000012517
John McCall2d74de92009-12-01 22:10:20 +000012518 Expr *Base;
12519
John McCall7decc9e2010-11-18 06:31:45 +000012520 // If we're filling in a static method where we used to have an
12521 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +000012522 if (MemExpr->isImplicitAccess()) {
12523 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012524 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12525 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000012526 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012527 Fn,
John McCall113bee02012-03-10 09:33:50 +000012528 /*enclosing*/ false,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012529 MemExpr->getMemberLoc(),
12530 Fn->getType(),
12531 VK_LValue,
12532 Found.getDecl(),
12533 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000012534 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012535 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
12536 return DRE;
Douglas Gregorb15af892010-01-07 23:12:05 +000012537 } else {
12538 SourceLocation Loc = MemExpr->getMemberLoc();
12539 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +000012540 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman73a04092012-01-07 04:59:52 +000012541 CheckCXXThisCapture(Loc);
Douglas Gregorb15af892010-01-07 23:12:05 +000012542 Base = new (Context) CXXThisExpr(Loc,
12543 MemExpr->getBaseType(),
12544 /*isImplicit=*/true);
12545 }
John McCall2d74de92009-12-01 22:10:20 +000012546 } else
John McCallc3007a22010-10-26 07:05:15 +000012547 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +000012548
John McCall4adb38c2011-04-27 00:36:17 +000012549 ExprValueKind valueKind;
12550 QualType type;
12551 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
12552 valueKind = VK_LValue;
12553 type = Fn->getType();
12554 } else {
12555 valueKind = VK_RValue;
Yunzhong Gaoeba323a2015-05-01 02:04:32 +000012556 type = Context.BoundMemberTy;
12557 }
12558
12559 MemberExpr *ME = MemberExpr::Create(
12560 Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
12561 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
12562 MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
12563 OK_Ordinary);
12564 ME->setHadMultipleCandidates(true);
12565 MarkMemberReferenced(ME);
12566 return ME;
Douglas Gregor51c538b2009-11-20 19:42:02 +000012567 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012568
John McCallc3007a22010-10-26 07:05:15 +000012569 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregorcd695e52008-11-10 20:40:00 +000012570}
12571
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012572ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +000012573 DeclAccessPair Found,
12574 FunctionDecl *Fn) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012575 return FixOverloadedFunctionReference(E.get(), Found, Fn);
Douglas Gregor3e1e5272009-12-09 23:02:17 +000012576}