blob: 47e3df20d9111fb36ec02aeff13fe8d84b98b318 [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
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000041static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) {
George Burgess IV21081362016-07-24 23:12:40 +000042 return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
43 return P->hasAttr<PassObjectSizeAttr>();
44 });
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000045}
46
Nick Lewycky134af912013-02-07 05:08:22 +000047/// A convenience routine for creating a decayed reference to a function.
John Wiegley01296292011-04-08 18:41:53 +000048static ExprResult
Nick Lewycky134af912013-02-07 05:08:22 +000049CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
50 bool HadMultipleCandidates,
Douglas Gregore9d62932011-07-15 16:25:15 +000051 SourceLocation Loc = SourceLocation(),
52 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
Richard Smith22262ab2013-05-04 06:44:46 +000053 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
Faisal Valid6676412013-06-15 11:54:37 +000054 return ExprError();
55 // If FoundDecl is different from Fn (such as if one is a template
56 // and the other a specialization), make sure DiagnoseUseOfDecl is
57 // called on both.
58 // FIXME: This would be more comprehensively addressed by modifying
59 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
60 // being used.
61 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
Richard Smith22262ab2013-05-04 06:44:46 +000062 return ExprError();
Richard Smith5f4b3882016-10-19 00:14:23 +000063 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
64 S.ResolveExceptionSpec(Loc, FPT);
John McCall113bee02012-03-10 09:33:50 +000065 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000066 VK_LValue, Loc, LocInfo);
67 if (HadMultipleCandidates)
68 DRE->setHadMultipleCandidates(true);
Nick Lewycky134af912013-02-07 05:08:22 +000069
70 S.MarkDeclRefReferenced(DRE);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000071 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
72 CK_FunctionToPointerDecay);
John McCall7decc9e2010-11-18 06:31:45 +000073}
74
John McCall5c32be02010-08-24 20:38:10 +000075static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
76 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +000077 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +000078 bool CStyle,
79 bool AllowObjCWritebackConversion);
Sam Panzer04390a62012-08-16 02:38:47 +000080
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +000081static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
82 QualType &ToType,
83 bool InOverloadResolution,
84 StandardConversionSequence &SCS,
85 bool CStyle);
John McCall5c32be02010-08-24 20:38:10 +000086static OverloadingResult
87IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
88 UserDefinedConversionSequence& User,
89 OverloadCandidateSet& Conversions,
Douglas Gregor4b60a152013-11-07 22:34:54 +000090 bool AllowExplicit,
91 bool AllowObjCConversionOnExplicit);
John McCall5c32be02010-08-24 20:38:10 +000092
93
94static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +000095CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +000096 const StandardConversionSequence& SCS1,
97 const StandardConversionSequence& SCS2);
98
99static ImplicitConversionSequence::CompareKind
100CompareQualificationConversions(Sema &S,
101 const StandardConversionSequence& SCS1,
102 const StandardConversionSequence& SCS2);
103
104static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +0000105CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +0000106 const StandardConversionSequence& SCS1,
107 const StandardConversionSequence& SCS2);
108
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000109/// GetConversionRank - Retrieve the implicit conversion rank
110/// corresponding to the given implicit conversion kind.
Richard Smith17c00b42014-11-12 01:24:00 +0000111ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000112 static const ImplicitConversionRank
113 Rank[(int)ICK_Num_Conversion_Kinds] = {
114 ICR_Exact_Match,
115 ICR_Exact_Match,
116 ICR_Exact_Match,
117 ICR_Exact_Match,
118 ICR_Exact_Match,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000119 ICR_Exact_Match,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000120 ICR_Promotion,
121 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000122 ICR_Promotion,
123 ICR_Conversion,
124 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000125 ICR_Conversion,
126 ICR_Conversion,
127 ICR_Conversion,
128 ICR_Conversion,
129 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000130 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000131 ICR_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000132 ICR_Conversion,
133 ICR_Conversion,
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000134 ICR_Complex_Real_Conversion,
135 ICR_Conversion,
John McCall31168b02011-06-15 23:02:42 +0000136 ICR_Conversion,
George Burgess IV45461812015-10-11 20:13:20 +0000137 ICR_Writeback_Conversion,
138 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
139 // it was omitted by the patch that added
140 // ICK_Zero_Event_Conversion
George Burgess IV2099b542016-09-02 22:59:57 +0000141 ICR_C_Conversion,
142 ICR_C_Conversion_Extension
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000143 };
144 return Rank[(int)Kind];
145}
146
147/// GetImplicitConversionName - Return the name of this kind of
148/// implicit conversion.
Richard Smith17c00b42014-11-12 01:24:00 +0000149static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopescfca1f02009-12-23 17:49:57 +0000150 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000151 "No conversion",
152 "Lvalue-to-rvalue",
153 "Array-to-pointer",
154 "Function-to-pointer",
Richard Smith3c4f8d22016-10-16 17:54:23 +0000155 "Function pointer conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000156 "Qualification",
157 "Integral promotion",
158 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000159 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000160 "Integral conversion",
161 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000162 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000163 "Floating-integral conversion",
164 "Pointer conversion",
165 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000166 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000167 "Compatible-types conversion",
Douglas Gregor46188682010-05-18 22:42:18 +0000168 "Derived-to-base conversion",
169 "Vector conversion",
170 "Vector splat",
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000171 "Complex-real conversion",
172 "Block Pointer conversion",
Sylvestre Ledru55635ce2014-11-17 19:41:49 +0000173 "Transparent Union Conversion",
George Burgess IV45461812015-10-11 20:13:20 +0000174 "Writeback conversion",
175 "OpenCL Zero Event Conversion",
George Burgess IV2099b542016-09-02 22:59:57 +0000176 "C specific type conversion",
177 "Incompatible pointer conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000178 };
179 return Name[Kind];
180}
181
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000182/// StandardConversionSequence - Set the standard conversion
183/// sequence to the identity conversion.
184void StandardConversionSequence::setAsIdentityConversion() {
185 First = ICK_Identity;
186 Second = ICK_Identity;
187 Third = ICK_Identity;
Douglas Gregore489a7d2010-02-28 18:30:25 +0000188 DeprecatedStringLiteralToCharPtr = false;
John McCall31168b02011-06-15 23:02:42 +0000189 QualificationIncludesObjCLifetime = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000190 ReferenceBinding = false;
191 DirectBinding = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +0000192 IsLvalueReference = true;
193 BindsToFunctionLvalue = false;
194 BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +0000195 BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +0000196 ObjCLifetimeConversionBinding = false;
Craig Topperc3ec1492014-05-26 06:22:03 +0000197 CopyConstructor = nullptr;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000198}
199
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000200/// getRank - Retrieve the rank of this standard conversion sequence
201/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
202/// implicit conversions.
203ImplicitConversionRank StandardConversionSequence::getRank() const {
204 ImplicitConversionRank Rank = ICR_Exact_Match;
205 if (GetConversionRank(First) > Rank)
206 Rank = GetConversionRank(First);
207 if (GetConversionRank(Second) > Rank)
208 Rank = GetConversionRank(Second);
209 if (GetConversionRank(Third) > Rank)
210 Rank = GetConversionRank(Third);
211 return Rank;
212}
213
214/// isPointerConversionToBool - Determines whether this conversion is
215/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump11289f42009-09-09 15:08:12 +0000216/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000217/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000218bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000219 // Note that FromType has not necessarily been transformed by the
220 // array-to-pointer or function-to-pointer implicit conversions, so
221 // check for their presence as well as checking whether FromType is
222 // a pointer.
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000223 if (getToType(1)->isBooleanType() &&
John McCall6d1116a2010-06-11 10:04:22 +0000224 (getFromType()->isPointerType() ||
225 getFromType()->isObjCObjectPointerType() ||
226 getFromType()->isBlockPointerType() ||
Anders Carlsson7da7cc52010-11-05 00:12:09 +0000227 getFromType()->isNullPtrType() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000228 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
229 return true;
230
231 return false;
232}
233
Douglas Gregor5c407d92008-10-23 00:40:37 +0000234/// isPointerConversionToVoidPointer - Determines whether this
235/// conversion is a conversion of a pointer to a void pointer. This is
236/// used as part of the ranking of standard conversion sequences (C++
237/// 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000238bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000239StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000240isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall0d1da222010-01-12 00:44:57 +0000241 QualType FromType = getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000242 QualType ToType = getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +0000243
244 // Note that FromType has not necessarily been transformed by the
245 // array-to-pointer implicit conversion, so check for its presence
246 // and redo the conversion to get a pointer.
247 if (First == ICK_Array_To_Pointer)
248 FromType = Context.getArrayDecayedType(FromType);
249
Douglas Gregor5d3d3fa2011-04-15 20:45:44 +0000250 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000251 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000252 return ToPtrType->getPointeeType()->isVoidType();
253
254 return false;
255}
256
Richard Smith66e05fe2012-01-18 05:21:49 +0000257/// Skip any implicit casts which could be either part of a narrowing conversion
258/// or after one in an implicit conversion.
259static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
260 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
261 switch (ICE->getCastKind()) {
262 case CK_NoOp:
263 case CK_IntegralCast:
264 case CK_IntegralToBoolean:
265 case CK_IntegralToFloating:
George Burgess IVdf1ed002016-01-13 01:52:39 +0000266 case CK_BooleanToSignedIntegral:
Richard Smith66e05fe2012-01-18 05:21:49 +0000267 case CK_FloatingToIntegral:
268 case CK_FloatingToBoolean:
269 case CK_FloatingCast:
270 Converted = ICE->getSubExpr();
271 continue;
272
273 default:
274 return Converted;
275 }
276 }
277
278 return Converted;
279}
280
281/// Check if this standard conversion sequence represents a narrowing
282/// conversion, according to C++11 [dcl.init.list]p7.
283///
284/// \param Ctx The AST context.
285/// \param Converted The result of applying this standard conversion sequence.
286/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
287/// value of the expression prior to the narrowing conversion.
Richard Smith5614ca72012-03-23 23:55:39 +0000288/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
289/// type of the expression prior to the narrowing conversion.
Richard Smith66e05fe2012-01-18 05:21:49 +0000290NarrowingKind
Richard Smithf8379a02012-01-18 23:55:52 +0000291StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
292 const Expr *Converted,
Richard Smith5614ca72012-03-23 23:55:39 +0000293 APValue &ConstantValue,
294 QualType &ConstantType) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000295 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
Richard Smith66e05fe2012-01-18 05:21:49 +0000296
297 // C++11 [dcl.init.list]p7:
298 // A narrowing conversion is an implicit conversion ...
299 QualType FromType = getToType(0);
300 QualType ToType = getToType(1);
Richard Smithed638862016-03-28 06:08:37 +0000301
302 // A conversion to an enumeration type is narrowing if the conversion to
303 // the underlying type is narrowing. This only arises for expressions of
304 // the form 'Enum{init}'.
305 if (auto *ET = ToType->getAs<EnumType>())
306 ToType = ET->getDecl()->getIntegerType();
307
Richard Smith66e05fe2012-01-18 05:21:49 +0000308 switch (Second) {
Richard Smith64ecacf2015-02-19 00:39:05 +0000309 // 'bool' is an integral type; dispatch to the right place to handle it.
310 case ICK_Boolean_Conversion:
311 if (FromType->isRealFloatingType())
312 goto FloatingIntegralConversion;
313 if (FromType->isIntegralOrUnscopedEnumerationType())
314 goto IntegralConversion;
315 // Boolean conversions can be from pointers and pointers to members
316 // [conv.bool], and those aren't considered narrowing conversions.
317 return NK_Not_Narrowing;
318
Richard Smith66e05fe2012-01-18 05:21:49 +0000319 // -- from a floating-point type to an integer type, or
320 //
321 // -- from an integer type or unscoped enumeration type to a floating-point
322 // type, except where the source is a constant expression and the actual
323 // value after conversion will fit into the target type and will produce
324 // the original value when converted back to the original type, or
325 case ICK_Floating_Integral:
Richard Smith64ecacf2015-02-19 00:39:05 +0000326 FloatingIntegralConversion:
Richard Smith66e05fe2012-01-18 05:21:49 +0000327 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
328 return NK_Type_Narrowing;
329 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
330 llvm::APSInt IntConstantValue;
331 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
Richard Smith52e624f2016-12-21 21:42:57 +0000332
333 // If it's value-dependent, we can't tell whether it's narrowing.
334 if (Initializer->isValueDependent())
335 return NK_Dependent_Narrowing;
336
Richard Smith66e05fe2012-01-18 05:21:49 +0000337 if (Initializer &&
338 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
339 // Convert the integer to the floating type.
340 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
341 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
342 llvm::APFloat::rmNearestTiesToEven);
343 // And back.
344 llvm::APSInt ConvertedValue = IntConstantValue;
345 bool ignored;
346 Result.convertToInteger(ConvertedValue,
347 llvm::APFloat::rmTowardZero, &ignored);
348 // If the resulting value is different, this was a narrowing conversion.
349 if (IntConstantValue != ConvertedValue) {
350 ConstantValue = APValue(IntConstantValue);
Richard Smith5614ca72012-03-23 23:55:39 +0000351 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000352 return NK_Constant_Narrowing;
353 }
354 } else {
355 // Variables are always narrowings.
356 return NK_Variable_Narrowing;
357 }
358 }
359 return NK_Not_Narrowing;
360
361 // -- from long double to double or float, or from double to float, except
362 // where the source is a constant expression and the actual value after
363 // conversion is within the range of values that can be represented (even
364 // if it cannot be represented exactly), or
365 case ICK_Floating_Conversion:
366 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
367 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
368 // FromType is larger than ToType.
369 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
Richard Smith52e624f2016-12-21 21:42:57 +0000370
371 // If it's value-dependent, we can't tell whether it's narrowing.
372 if (Initializer->isValueDependent())
373 return NK_Dependent_Narrowing;
374
Richard Smith66e05fe2012-01-18 05:21:49 +0000375 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
376 // Constant!
377 assert(ConstantValue.isFloat());
378 llvm::APFloat FloatVal = ConstantValue.getFloat();
379 // Convert the source value into the target type.
380 bool ignored;
381 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
382 Ctx.getFloatTypeSemantics(ToType),
383 llvm::APFloat::rmNearestTiesToEven, &ignored);
384 // If there was no overflow, the source value is within the range of
385 // values that can be represented.
Richard Smith5614ca72012-03-23 23:55:39 +0000386 if (ConvertStatus & llvm::APFloat::opOverflow) {
387 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000388 return NK_Constant_Narrowing;
Richard Smith5614ca72012-03-23 23:55:39 +0000389 }
Richard Smith66e05fe2012-01-18 05:21:49 +0000390 } else {
391 return NK_Variable_Narrowing;
392 }
393 }
394 return NK_Not_Narrowing;
395
396 // -- from an integer type or unscoped enumeration type to an integer type
397 // that cannot represent all the values of the original type, except where
398 // the source is a constant expression and the actual value after
399 // conversion will fit into the target type and will produce the original
400 // value when converted back to the original type.
Richard Smith64ecacf2015-02-19 00:39:05 +0000401 case ICK_Integral_Conversion:
402 IntegralConversion: {
Richard Smith66e05fe2012-01-18 05:21:49 +0000403 assert(FromType->isIntegralOrUnscopedEnumerationType());
404 assert(ToType->isIntegralOrUnscopedEnumerationType());
405 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
406 const unsigned FromWidth = Ctx.getIntWidth(FromType);
407 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
408 const unsigned ToWidth = Ctx.getIntWidth(ToType);
409
410 if (FromWidth > ToWidth ||
Richard Smith25a80d42012-06-13 01:07:41 +0000411 (FromWidth == ToWidth && FromSigned != ToSigned) ||
412 (FromSigned && !ToSigned)) {
Richard Smith66e05fe2012-01-18 05:21:49 +0000413 // Not all values of FromType can be represented in ToType.
414 llvm::APSInt InitializerValue;
415 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
Richard Smith52e624f2016-12-21 21:42:57 +0000416
417 // If it's value-dependent, we can't tell whether it's narrowing.
418 if (Initializer->isValueDependent())
419 return NK_Dependent_Narrowing;
420
Richard Smith25a80d42012-06-13 01:07:41 +0000421 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
422 // Such conversions on variables are always narrowing.
423 return NK_Variable_Narrowing;
Richard Smith72cd8ea2012-06-19 21:28:35 +0000424 }
425 bool Narrowing = false;
426 if (FromWidth < ToWidth) {
Richard Smith25a80d42012-06-13 01:07:41 +0000427 // Negative -> unsigned is narrowing. Otherwise, more bits is never
428 // narrowing.
429 if (InitializerValue.isSigned() && InitializerValue.isNegative())
Richard Smith72cd8ea2012-06-19 21:28:35 +0000430 Narrowing = true;
Richard Smith25a80d42012-06-13 01:07:41 +0000431 } else {
Richard Smith66e05fe2012-01-18 05:21:49 +0000432 // Add a bit to the InitializerValue so we don't have to worry about
433 // signed vs. unsigned comparisons.
434 InitializerValue = InitializerValue.extend(
435 InitializerValue.getBitWidth() + 1);
436 // Convert the initializer to and from the target width and signed-ness.
437 llvm::APSInt ConvertedValue = InitializerValue;
438 ConvertedValue = ConvertedValue.trunc(ToWidth);
439 ConvertedValue.setIsSigned(ToSigned);
440 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
441 ConvertedValue.setIsSigned(InitializerValue.isSigned());
442 // If the result is different, this was a narrowing conversion.
Richard Smith72cd8ea2012-06-19 21:28:35 +0000443 if (ConvertedValue != InitializerValue)
444 Narrowing = true;
445 }
446 if (Narrowing) {
447 ConstantType = Initializer->getType();
448 ConstantValue = APValue(InitializerValue);
449 return NK_Constant_Narrowing;
Richard Smith66e05fe2012-01-18 05:21:49 +0000450 }
451 }
452 return NK_Not_Narrowing;
453 }
454
455 default:
456 // Other kinds of conversions are not narrowings.
457 return NK_Not_Narrowing;
458 }
459}
460
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000461/// dump - Print this standard conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000462/// error. Useful for debugging overloading issues.
Yaron Kerencdae9412016-01-29 19:38:18 +0000463LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000464 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000465 bool PrintedSomething = false;
466 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000467 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000468 PrintedSomething = true;
469 }
470
471 if (Second != ICK_Identity) {
472 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000473 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000474 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000475 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000476
477 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000478 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000479 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000480 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000481 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000482 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000483 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000484 PrintedSomething = true;
485 }
486
487 if (Third != ICK_Identity) {
488 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000489 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000490 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000491 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000492 PrintedSomething = true;
493 }
494
495 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000496 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000497 }
498}
499
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000500/// dump - Print this user-defined conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000501/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000502void UserDefinedConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000503 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000504 if (Before.First || Before.Second || Before.Third) {
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000505 Before.dump();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000506 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000507 }
Sebastian Redl72ef7bc2011-11-01 15:53:09 +0000508 if (ConversionFunction)
509 OS << '\'' << *ConversionFunction << '\'';
510 else
511 OS << "aggregate initialization";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000512 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000513 OS << " -> ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000514 After.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000515 }
516}
517
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000518/// dump - Print this implicit conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000519/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000520void ImplicitConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000521 raw_ostream &OS = llvm::errs();
Richard Smitha93f1022013-09-06 22:30:28 +0000522 if (isStdInitializerListElement())
523 OS << "Worst std::initializer_list element conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000524 switch (ConversionKind) {
525 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000526 OS << "Standard conversion: ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000527 Standard.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000528 break;
529 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000530 OS << "User-defined conversion: ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000531 UserDefined.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000532 break;
533 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000534 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000535 break;
John McCall0d1da222010-01-12 00:44:57 +0000536 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000537 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000538 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000539 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000540 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000541 break;
542 }
543
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000544 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000545}
546
John McCall0d1da222010-01-12 00:44:57 +0000547void AmbiguousConversionSequence::construct() {
548 new (&conversions()) ConversionSet();
549}
550
551void AmbiguousConversionSequence::destruct() {
552 conversions().~ConversionSet();
553}
554
555void
556AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
557 FromTypePtr = O.FromTypePtr;
558 ToTypePtr = O.ToTypePtr;
559 new (&conversions()) ConversionSet(O.conversions());
560}
561
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000562namespace {
Larisse Voufo98b20f12013-07-19 23:00:19 +0000563 // Structure used by DeductionFailureInfo to store
Richard Smith44ecdbd2013-01-31 05:19:49 +0000564 // template argument information.
565 struct DFIArguments {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000566 TemplateArgument FirstArg;
567 TemplateArgument SecondArg;
568 };
Larisse Voufo98b20f12013-07-19 23:00:19 +0000569 // Structure used by DeductionFailureInfo to store
Richard Smith44ecdbd2013-01-31 05:19:49 +0000570 // template parameter and template argument information.
571 struct DFIParamWithArguments : DFIArguments {
572 TemplateParameter Param;
573 };
Richard Smith9b534542015-12-31 02:02:54 +0000574 // Structure used by DeductionFailureInfo to store template argument
575 // information and the index of the problematic call argument.
576 struct DFIDeducedMismatchArgs : DFIArguments {
577 TemplateArgumentList *TemplateArgs;
578 unsigned CallArgIndex;
579 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000580}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000581
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000582/// \brief Convert from Sema's representation of template deduction information
583/// to the form used in overload-candidate information.
Richard Smith17c00b42014-11-12 01:24:00 +0000584DeductionFailureInfo
585clang::MakeDeductionFailureInfo(ASTContext &Context,
586 Sema::TemplateDeductionResult TDK,
587 TemplateDeductionInfo &Info) {
Larisse Voufo98b20f12013-07-19 23:00:19 +0000588 DeductionFailureInfo Result;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000589 Result.Result = static_cast<unsigned>(TDK);
Richard Smith9ca64612012-05-07 09:03:25 +0000590 Result.HasDiagnostic = false;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000591 switch (TDK) {
592 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000593 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000594 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000595 case Sema::TDK_TooManyArguments:
596 case Sema::TDK_TooFewArguments:
Richard Smith9b534542015-12-31 02:02:54 +0000597 case Sema::TDK_MiscellaneousDeductionFailure:
Artem Belevich13e9b4d2016-12-07 19:27:16 +0000598 case Sema::TDK_CUDATargetMismatch:
Richard Smith9b534542015-12-31 02:02:54 +0000599 Result.Data = nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000600 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000601
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000602 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000603 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000604 Result.Data = Info.Param.getOpaqueValue();
605 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000606
Richard Smith9b534542015-12-31 02:02:54 +0000607 case Sema::TDK_DeducedMismatch: {
608 // FIXME: Should allocate from normal heap so that we can free this later.
609 auto *Saved = new (Context) DFIDeducedMismatchArgs;
610 Saved->FirstArg = Info.FirstArg;
611 Saved->SecondArg = Info.SecondArg;
612 Saved->TemplateArgs = Info.take();
613 Saved->CallArgIndex = Info.CallArgIndex;
614 Result.Data = Saved;
615 break;
616 }
617
Richard Smith44ecdbd2013-01-31 05:19:49 +0000618 case Sema::TDK_NonDeducedMismatch: {
619 // FIXME: Should allocate from normal heap so that we can free this later.
620 DFIArguments *Saved = new (Context) DFIArguments;
621 Saved->FirstArg = Info.FirstArg;
622 Saved->SecondArg = Info.SecondArg;
623 Result.Data = Saved;
624 break;
625 }
626
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000627 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000628 case Sema::TDK_Underqualified: {
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000629 // FIXME: Should allocate from normal heap so that we can free this later.
630 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000631 Saved->Param = Info.Param;
632 Saved->FirstArg = Info.FirstArg;
633 Saved->SecondArg = Info.SecondArg;
634 Result.Data = Saved;
635 break;
636 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000637
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000638 case Sema::TDK_SubstitutionFailure:
Douglas Gregord09efd42010-05-08 20:07:26 +0000639 Result.Data = Info.take();
Richard Smith9ca64612012-05-07 09:03:25 +0000640 if (Info.hasSFINAEDiagnostic()) {
641 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
642 SourceLocation(), PartialDiagnostic::NullDiagnostic());
643 Info.takeSFINAEDiagnostic(*Diag);
644 Result.HasDiagnostic = true;
645 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000646 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000647
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000648 case Sema::TDK_FailedOverloadResolution:
Richard Smith8c6eeb92013-01-31 04:03:12 +0000649 Result.Data = Info.Expression;
650 break;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000651 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000652
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000653 return Result;
654}
John McCall0d1da222010-01-12 00:44:57 +0000655
Larisse Voufo98b20f12013-07-19 23:00:19 +0000656void DeductionFailureInfo::Destroy() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000657 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
658 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000659 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000660 case Sema::TDK_InstantiationDepth:
661 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000662 case Sema::TDK_TooManyArguments:
663 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000664 case Sema::TDK_InvalidExplicitArguments:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000665 case Sema::TDK_FailedOverloadResolution:
Artem Belevich13e9b4d2016-12-07 19:27:16 +0000666 case Sema::TDK_CUDATargetMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000667 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000668
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000669 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000670 case Sema::TDK_Underqualified:
Richard Smith9b534542015-12-31 02:02:54 +0000671 case Sema::TDK_DeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000672 case Sema::TDK_NonDeducedMismatch:
Douglas Gregorb02d6b32010-05-08 20:20:05 +0000673 // FIXME: Destroy the data?
Craig Topperc3ec1492014-05-26 06:22:03 +0000674 Data = nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000675 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000676
677 case Sema::TDK_SubstitutionFailure:
Richard Smith9ca64612012-05-07 09:03:25 +0000678 // FIXME: Destroy the template argument list?
Craig Topperc3ec1492014-05-26 06:22:03 +0000679 Data = nullptr;
Richard Smith9ca64612012-05-07 09:03:25 +0000680 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
681 Diag->~PartialDiagnosticAt();
682 HasDiagnostic = false;
683 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000684 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000685
Douglas Gregor461761d2010-05-08 18:20:53 +0000686 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000687 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000688 break;
689 }
690}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000691
Larisse Voufo98b20f12013-07-19 23:00:19 +0000692PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
Richard Smith9ca64612012-05-07 09:03:25 +0000693 if (HasDiagnostic)
694 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
Craig Topperc3ec1492014-05-26 06:22:03 +0000695 return nullptr;
Richard Smith9ca64612012-05-07 09:03:25 +0000696}
697
Larisse Voufo98b20f12013-07-19 23:00:19 +0000698TemplateParameter DeductionFailureInfo::getTemplateParameter() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000699 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
700 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000701 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000702 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000703 case Sema::TDK_TooManyArguments:
704 case Sema::TDK_TooFewArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000705 case Sema::TDK_SubstitutionFailure:
Richard Smith9b534542015-12-31 02:02:54 +0000706 case Sema::TDK_DeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000707 case Sema::TDK_NonDeducedMismatch:
708 case Sema::TDK_FailedOverloadResolution:
Artem Belevich13e9b4d2016-12-07 19:27:16 +0000709 case Sema::TDK_CUDATargetMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000710 return TemplateParameter();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000711
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000712 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000713 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000714 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000715
716 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000717 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000718 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000719
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000720 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000721 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000722 break;
723 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000724
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000725 return TemplateParameter();
726}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000727
Larisse Voufo98b20f12013-07-19 23:00:19 +0000728TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
Douglas Gregord09efd42010-05-08 20:07:26 +0000729 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
Richard Smith44ecdbd2013-01-31 05:19:49 +0000730 case Sema::TDK_Success:
731 case Sema::TDK_Invalid:
732 case Sema::TDK_InstantiationDepth:
733 case Sema::TDK_TooManyArguments:
734 case Sema::TDK_TooFewArguments:
735 case Sema::TDK_Incomplete:
736 case Sema::TDK_InvalidExplicitArguments:
737 case Sema::TDK_Inconsistent:
738 case Sema::TDK_Underqualified:
739 case Sema::TDK_NonDeducedMismatch:
740 case Sema::TDK_FailedOverloadResolution:
Artem Belevich13e9b4d2016-12-07 19:27:16 +0000741 case Sema::TDK_CUDATargetMismatch:
Craig Topperc3ec1492014-05-26 06:22:03 +0000742 return nullptr;
Douglas Gregord09efd42010-05-08 20:07:26 +0000743
Richard Smith9b534542015-12-31 02:02:54 +0000744 case Sema::TDK_DeducedMismatch:
745 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
746
Richard Smith44ecdbd2013-01-31 05:19:49 +0000747 case Sema::TDK_SubstitutionFailure:
748 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000749
Richard Smith44ecdbd2013-01-31 05:19:49 +0000750 // Unhandled
751 case Sema::TDK_MiscellaneousDeductionFailure:
752 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000753 }
754
Craig Topperc3ec1492014-05-26 06:22:03 +0000755 return nullptr;
Douglas Gregord09efd42010-05-08 20:07:26 +0000756}
757
Larisse Voufo98b20f12013-07-19 23:00:19 +0000758const TemplateArgument *DeductionFailureInfo::getFirstArg() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000759 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
760 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000761 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000762 case Sema::TDK_InstantiationDepth:
763 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000764 case Sema::TDK_TooManyArguments:
765 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000766 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000767 case Sema::TDK_SubstitutionFailure:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000768 case Sema::TDK_FailedOverloadResolution:
Artem Belevich13e9b4d2016-12-07 19:27:16 +0000769 case Sema::TDK_CUDATargetMismatch:
Craig Topperc3ec1492014-05-26 06:22:03 +0000770 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000771
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000772 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000773 case Sema::TDK_Underqualified:
Richard Smith9b534542015-12-31 02:02:54 +0000774 case Sema::TDK_DeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000775 case Sema::TDK_NonDeducedMismatch:
776 return &static_cast<DFIArguments*>(Data)->FirstArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000777
Douglas Gregor461761d2010-05-08 18:20:53 +0000778 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000779 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000780 break;
781 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000782
Craig Topperc3ec1492014-05-26 06:22:03 +0000783 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000784}
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000785
Larisse Voufo98b20f12013-07-19 23:00:19 +0000786const TemplateArgument *DeductionFailureInfo::getSecondArg() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000787 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
788 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000789 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000790 case Sema::TDK_InstantiationDepth:
791 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000792 case Sema::TDK_TooManyArguments:
793 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000794 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000795 case Sema::TDK_SubstitutionFailure:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000796 case Sema::TDK_FailedOverloadResolution:
Artem Belevich13e9b4d2016-12-07 19:27:16 +0000797 case Sema::TDK_CUDATargetMismatch:
Craig Topperc3ec1492014-05-26 06:22:03 +0000798 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000799
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000800 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000801 case Sema::TDK_Underqualified:
Richard Smith9b534542015-12-31 02:02:54 +0000802 case Sema::TDK_DeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000803 case Sema::TDK_NonDeducedMismatch:
804 return &static_cast<DFIArguments*>(Data)->SecondArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000805
Douglas Gregor461761d2010-05-08 18:20:53 +0000806 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000807 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000808 break;
809 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000810
Craig Topperc3ec1492014-05-26 06:22:03 +0000811 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000812}
813
Larisse Voufo98b20f12013-07-19 23:00:19 +0000814Expr *DeductionFailureInfo::getExpr() {
Richard Smith8c6eeb92013-01-31 04:03:12 +0000815 if (static_cast<Sema::TemplateDeductionResult>(Result) ==
816 Sema::TDK_FailedOverloadResolution)
817 return static_cast<Expr*>(Data);
818
Craig Topperc3ec1492014-05-26 06:22:03 +0000819 return nullptr;
Richard Smith8c6eeb92013-01-31 04:03:12 +0000820}
821
Richard Smith9b534542015-12-31 02:02:54 +0000822llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
823 if (static_cast<Sema::TemplateDeductionResult>(Result) ==
824 Sema::TDK_DeducedMismatch)
825 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
826
827 return llvm::None;
828}
829
Benjamin Kramer97e59492012-10-09 15:52:25 +0000830void OverloadCandidateSet::destroyCandidates() {
Richard Smith0bf93aa2012-07-18 23:52:59 +0000831 for (iterator i = begin(), e = end(); i != e; ++i) {
Benjamin Kramer02b08432012-01-14 20:16:52 +0000832 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
833 i->Conversions[ii].~ImplicitConversionSequence();
Richard Smith0bf93aa2012-07-18 23:52:59 +0000834 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
835 i->DeductionFailure.Destroy();
836 }
Benjamin Kramer97e59492012-10-09 15:52:25 +0000837}
838
839void OverloadCandidateSet::clear() {
840 destroyCandidates();
George Burgess IVbc7f44c2016-12-02 21:00:12 +0000841 ConversionSequenceAllocator.Reset();
Benjamin Kramer0b9c5092012-01-14 19:31:39 +0000842 NumInlineSequences = 0;
Benjamin Kramerfb761ff2012-01-14 16:31:55 +0000843 Candidates.clear();
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000844 Functions.clear();
845}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000846
John McCall4124c492011-10-17 18:40:02 +0000847namespace {
848 class UnbridgedCastsSet {
849 struct Entry {
850 Expr **Addr;
851 Expr *Saved;
852 };
853 SmallVector<Entry, 2> Entries;
854
855 public:
856 void save(Sema &S, Expr *&E) {
857 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
858 Entry entry = { &E, E };
859 Entries.push_back(entry);
860 E = S.stripARCUnbridgedCast(E);
861 }
862
863 void restore() {
864 for (SmallVectorImpl<Entry>::iterator
865 i = Entries.begin(), e = Entries.end(); i != e; ++i)
866 *i->Addr = i->Saved;
867 }
868 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000869}
John McCall4124c492011-10-17 18:40:02 +0000870
871/// checkPlaceholderForOverload - Do any interesting placeholder-like
872/// preprocessing on the given expression.
873///
874/// \param unbridgedCasts a collection to which to add unbridged casts;
875/// without this, they will be immediately diagnosed as errors
876///
877/// Return true on unrecoverable error.
Craig Topperc3ec1492014-05-26 06:22:03 +0000878static bool
879checkPlaceholderForOverload(Sema &S, Expr *&E,
880 UnbridgedCastsSet *unbridgedCasts = nullptr) {
John McCall4124c492011-10-17 18:40:02 +0000881 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
882 // We can't handle overloaded expressions here because overload
883 // resolution might reasonably tweak them.
884 if (placeholder->getKind() == BuiltinType::Overload) return false;
885
886 // If the context potentially accepts unbridged ARC casts, strip
887 // the unbridged cast and add it to the collection for later restoration.
888 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
889 unbridgedCasts) {
890 unbridgedCasts->save(S, E);
891 return false;
892 }
893
894 // Go ahead and check everything else.
895 ExprResult result = S.CheckPlaceholderExpr(E);
896 if (result.isInvalid())
897 return true;
898
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000899 E = result.get();
John McCall4124c492011-10-17 18:40:02 +0000900 return false;
901 }
902
903 // Nothing to do.
904 return false;
905}
906
907/// checkArgPlaceholdersForOverload - Check a set of call operands for
908/// placeholders.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000909static bool checkArgPlaceholdersForOverload(Sema &S,
910 MultiExprArg Args,
John McCall4124c492011-10-17 18:40:02 +0000911 UnbridgedCastsSet &unbridged) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000912 for (unsigned i = 0, e = Args.size(); i != e; ++i)
913 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
John McCall4124c492011-10-17 18:40:02 +0000914 return true;
915
916 return false;
917}
918
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000919// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000920// overload of the declarations in Old. This routine returns false if
921// New and Old cannot be overloaded, e.g., if New has the same
922// signature as some function in Old (C++ 1.3.10) or if the Old
923// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000924// it does return false, MatchedDecl will point to the decl that New
925// cannot be overloaded with. This decl may be a UsingShadowDecl on
926// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000927//
928// Example: Given the following input:
929//
930// void f(int, float); // #1
931// void f(int, int); // #2
932// int f(int, int); // #3
933//
934// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000935// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000936//
John McCall3d988d92009-12-02 08:47:38 +0000937// When we process #2, Old contains only the FunctionDecl for #1. By
938// comparing the parameter types, we see that #1 and #2 are overloaded
939// (since they have different signatures), so this routine returns
940// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000941//
John McCall3d988d92009-12-02 08:47:38 +0000942// When we process #3, Old is an overload set containing #1 and #2. We
943// compare the signatures of #3 to #1 (they're overloaded, so we do
944// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
945// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000946// signature), IsOverload returns false and MatchedDecl will be set to
947// point to the FunctionDecl for #2.
John McCalle9cccd82010-06-16 08:42:20 +0000948//
949// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
950// into a class by a using declaration. The rules for whether to hide
951// shadow declarations ignore some properties which otherwise figure
952// into a function template's signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000953Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000954Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
955 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000956 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000957 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000958 NamedDecl *OldD = *I;
959
960 bool OldIsUsingDecl = false;
961 if (isa<UsingShadowDecl>(OldD)) {
962 OldIsUsingDecl = true;
963
964 // We can always introduce two using declarations into the same
965 // context, even if they have identical signatures.
966 if (NewIsUsingDecl) continue;
967
968 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
969 }
970
Richard Smithf091e122015-09-15 01:28:55 +0000971 // A using-declaration does not conflict with another declaration
972 // if one of them is hidden.
973 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
974 continue;
975
John McCalle9cccd82010-06-16 08:42:20 +0000976 // If either declaration was introduced by a using declaration,
977 // we'll need to use slightly different rules for matching.
978 // Essentially, these rules are the normal rules, except that
979 // function templates hide function templates with different
980 // return types or template parameter lists.
981 bool UseMemberUsingDeclRules =
John McCallc70fca62013-04-03 21:19:47 +0000982 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
983 !New->getFriendObjectKind();
John McCalle9cccd82010-06-16 08:42:20 +0000984
Alp Tokera2794f92014-01-22 07:29:52 +0000985 if (FunctionDecl *OldF = OldD->getAsFunction()) {
John McCalle9cccd82010-06-16 08:42:20 +0000986 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
987 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
988 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
989 continue;
990 }
991
Alp Tokera2794f92014-01-22 07:29:52 +0000992 if (!isa<FunctionTemplateDecl>(OldD) &&
993 !shouldLinkPossiblyHiddenDecl(*I, New))
Rafael Espindola5bddd6a2013-04-15 12:49:13 +0000994 continue;
995
John McCalldaa3d6b2009-12-09 03:35:25 +0000996 Match = *I;
997 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000998 }
Richard Smith151c4562016-12-20 21:35:28 +0000999 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +00001000 // We can overload with these, which can show up when doing
1001 // redeclaration checks for UsingDecls.
1002 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalla8987a2942010-11-10 03:01:53 +00001003 } else if (isa<TagDecl>(OldD)) {
1004 // We can always overload with tags by hiding them.
Richard Smithd8a9e372016-12-18 21:39:37 +00001005 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +00001006 // Optimistically assume that an unresolved using decl will
1007 // overload; if it doesn't, we'll have to diagnose during
1008 // template instantiation.
Richard Smithd8a9e372016-12-18 21:39:37 +00001009 //
1010 // Exception: if the scope is dependent and this is not a class
1011 // member, the using declaration can only introduce an enumerator.
1012 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1013 Match = *I;
1014 return Ovl_NonFunction;
1015 }
John McCall84d87672009-12-10 09:41:52 +00001016 } else {
John McCall1f82f242009-11-18 22:49:29 +00001017 // (C++ 13p1):
1018 // Only function declarations can be overloaded; object and type
1019 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +00001020 Match = *I;
1021 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +00001022 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001023 }
John McCall1f82f242009-11-18 22:49:29 +00001024
John McCalldaa3d6b2009-12-09 03:35:25 +00001025 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +00001026}
1027
Richard Smithac974a32013-06-30 09:48:50 +00001028bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
Justin Lebarba122ab2016-03-30 23:30:21 +00001029 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
Richard Smithac974a32013-06-30 09:48:50 +00001030 // C++ [basic.start.main]p2: This function shall not be overloaded.
1031 if (New->isMain())
Rafael Espindola576127d2012-12-28 14:21:58 +00001032 return false;
Rafael Espindola7cf35ef2013-01-12 01:47:40 +00001033
David Majnemerc729b0b2013-09-16 22:44:20 +00001034 // MSVCRT user defined entry points cannot be overloaded.
1035 if (New->isMSVCRTEntryPoint())
1036 return false;
1037
John McCall1f82f242009-11-18 22:49:29 +00001038 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1039 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1040
1041 // C++ [temp.fct]p2:
1042 // A function template can be overloaded with other function templates
1043 // and with normal (non-template) functions.
Craig Topperc3ec1492014-05-26 06:22:03 +00001044 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
John McCall1f82f242009-11-18 22:49:29 +00001045 return true;
1046
1047 // Is the function New an overload of the function Old?
Richard Smithac974a32013-06-30 09:48:50 +00001048 QualType OldQType = Context.getCanonicalType(Old->getType());
1049 QualType NewQType = Context.getCanonicalType(New->getType());
John McCall1f82f242009-11-18 22:49:29 +00001050
1051 // Compare the signatures (C++ 1.3.10) of the two functions to
1052 // determine whether they are overloads. If we find any mismatch
1053 // in the signature, they are overloads.
1054
1055 // If either of these functions is a K&R-style function (no
1056 // prototype), then we consider them to have matching signatures.
1057 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1058 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1059 return false;
1060
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001061 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1062 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
John McCall1f82f242009-11-18 22:49:29 +00001063
1064 // The signature of a function includes the types of its
1065 // parameters (C++ 1.3.10), which includes the presence or absence
1066 // of the ellipsis; see C++ DR 357).
1067 if (OldQType != NewQType &&
Alp Toker9cacbab2014-01-20 20:26:09 +00001068 (OldType->getNumParams() != NewType->getNumParams() ||
John McCall1f82f242009-11-18 22:49:29 +00001069 OldType->isVariadic() != NewType->isVariadic() ||
Alp Toker9cacbab2014-01-20 20:26:09 +00001070 !FunctionParamTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +00001071 return true;
1072
1073 // C++ [temp.over.link]p4:
1074 // The signature of a function template consists of its function
1075 // signature, its return type and its template parameter list. The names
1076 // of the template parameters are significant only for establishing the
1077 // relationship between the template parameters and the rest of the
1078 // signature.
1079 //
1080 // We check the return type and template parameter lists for function
1081 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +00001082 //
1083 // However, we don't consider either of these when deciding whether
1084 // a member introduced by a shadow declaration is hidden.
Justin Lebar39fd5292016-03-30 20:41:05 +00001085 if (!UseMemberUsingDeclRules && NewTemplate &&
Richard Smithac974a32013-06-30 09:48:50 +00001086 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1087 OldTemplate->getTemplateParameters(),
1088 false, TPL_TemplateMatch) ||
Alp Toker314cc812014-01-25 16:55:45 +00001089 OldType->getReturnType() != NewType->getReturnType()))
John McCall1f82f242009-11-18 22:49:29 +00001090 return true;
1091
1092 // If the function is a class member, its signature includes the
Douglas Gregorb2f8aa92011-01-26 17:47:49 +00001093 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall1f82f242009-11-18 22:49:29 +00001094 //
1095 // As part of this, also check whether one of the member functions
1096 // is static, in which case they are not overloads (C++
1097 // 13.1p2). While not part of the definition of the signature,
1098 // this check is important to determine whether these functions
1099 // can be overloaded.
Richard Smith574f4f62013-01-14 05:37:29 +00001100 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1101 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
John McCall1f82f242009-11-18 22:49:29 +00001102 if (OldMethod && NewMethod &&
Richard Smith574f4f62013-01-14 05:37:29 +00001103 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1104 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
Justin Lebar39fd5292016-03-30 20:41:05 +00001105 if (!UseMemberUsingDeclRules &&
Richard Smith574f4f62013-01-14 05:37:29 +00001106 (OldMethod->getRefQualifier() == RQ_None ||
1107 NewMethod->getRefQualifier() == RQ_None)) {
1108 // C++0x [over.load]p2:
1109 // - Member function declarations with the same name and the same
1110 // parameter-type-list as well as member function template
1111 // declarations with the same name, the same parameter-type-list, and
1112 // the same template parameter lists cannot be overloaded if any of
1113 // them, but not all, have a ref-qualifier (8.3.5).
Richard Smithac974a32013-06-30 09:48:50 +00001114 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
Richard Smith574f4f62013-01-14 05:37:29 +00001115 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
Richard Smithac974a32013-06-30 09:48:50 +00001116 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
Richard Smith574f4f62013-01-14 05:37:29 +00001117 }
1118 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001119 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001120
Richard Smith574f4f62013-01-14 05:37:29 +00001121 // We may not have applied the implicit const for a constexpr member
1122 // function yet (because we haven't yet resolved whether this is a static
1123 // or non-static member function). Add it now, on the assumption that this
1124 // is a redeclaration of OldMethod.
David Majnemer42350df2013-11-03 23:51:28 +00001125 unsigned OldQuals = OldMethod->getTypeQualifiers();
Richard Smith574f4f62013-01-14 05:37:29 +00001126 unsigned NewQuals = NewMethod->getTypeQualifiers();
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001127 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
Richard Smithe83b1d32013-06-25 18:46:26 +00001128 !isa<CXXConstructorDecl>(NewMethod))
Richard Smith574f4f62013-01-14 05:37:29 +00001129 NewQuals |= Qualifiers::Const;
David Majnemer42350df2013-11-03 23:51:28 +00001130
1131 // We do not allow overloading based off of '__restrict'.
1132 OldQuals &= ~Qualifiers::Restrict;
1133 NewQuals &= ~Qualifiers::Restrict;
1134 if (OldQuals != NewQuals)
Richard Smith574f4f62013-01-14 05:37:29 +00001135 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001136 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001137
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001138 // Though pass_object_size is placed on parameters and takes an argument, we
1139 // consider it to be a function-level modifier for the sake of function
1140 // identity. Either the function has one or more parameters with
1141 // pass_object_size or it doesn't.
1142 if (functionHasPassObjectSizeParams(New) !=
1143 functionHasPassObjectSizeParams(Old))
1144 return true;
1145
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001146 // enable_if attributes are an order-sensitive part of the signature.
1147 for (specific_attr_iterator<EnableIfAttr>
1148 NewI = New->specific_attr_begin<EnableIfAttr>(),
1149 NewE = New->specific_attr_end<EnableIfAttr>(),
1150 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1151 OldE = Old->specific_attr_end<EnableIfAttr>();
1152 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1153 if (NewI == NewE || OldI == OldE)
1154 return true;
1155 llvm::FoldingSetNodeID NewID, OldID;
1156 NewI->getCond()->Profile(NewID, Context, true);
1157 OldI->getCond()->Profile(OldID, Context, true);
Nick Lewyckyd950ae72014-01-21 01:30:30 +00001158 if (NewID != OldID)
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001159 return true;
1160 }
1161
Justin Lebarba122ab2016-03-30 23:30:21 +00001162 if (getLangOpts().CUDA && ConsiderCudaAttrs) {
Justin Lebare060feb2016-10-03 16:48:23 +00001163 // Don't allow overloading of destructors. (In theory we could, but it
1164 // would be a giant change to clang.)
1165 if (isa<CXXDestructorDecl>(New))
1166 return false;
1167
Artem Belevich94a55e82015-09-22 17:22:59 +00001168 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1169 OldTarget = IdentifyCUDATarget(Old);
Artem Belevich13e9b4d2016-12-07 19:27:16 +00001170 if (NewTarget == CFT_InvalidTarget)
Artem Belevich94a55e82015-09-22 17:22:59 +00001171 return false;
1172
1173 assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target.");
1174
Justin Lebar53b000af2016-10-03 16:48:27 +00001175 // Allow overloading of functions with same signature and different CUDA
1176 // target attributes.
Artem Belevich94a55e82015-09-22 17:22:59 +00001177 return NewTarget != OldTarget;
1178 }
1179
John McCall1f82f242009-11-18 22:49:29 +00001180 // The signatures match; this is not an overload.
1181 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001182}
1183
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00001184/// \brief Checks availability of the function depending on the current
1185/// function context. Inside an unavailable function, unavailability is ignored.
1186///
1187/// \returns true if \arg FD is unavailable and current context is inside
1188/// an available function, false otherwise.
1189bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
Duncan P. N. Exon Smith85363922016-03-08 10:28:52 +00001190 if (!FD->isUnavailable())
1191 return false;
1192
1193 // Walk up the context of the caller.
1194 Decl *C = cast<Decl>(CurContext);
1195 do {
1196 if (C->isUnavailable())
1197 return false;
1198 } while ((C = cast_or_null<Decl>(C->getDeclContext())));
1199 return true;
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00001200}
1201
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001202/// \brief Tries a user-defined conversion from From to ToType.
1203///
1204/// Produces an implicit conversion sequence for when a standard conversion
1205/// is not an option. See TryImplicitConversion for more information.
1206static ImplicitConversionSequence
1207TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1208 bool SuppressUserConversions,
1209 bool AllowExplicit,
1210 bool InOverloadResolution,
1211 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001212 bool AllowObjCWritebackConversion,
1213 bool AllowObjCConversionOnExplicit) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001214 ImplicitConversionSequence ICS;
1215
1216 if (SuppressUserConversions) {
1217 // We're not in the case above, so there is no conversion that
1218 // we can perform.
1219 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1220 return ICS;
1221 }
1222
1223 // Attempt user-defined conversion.
Richard Smith100b24a2014-04-17 01:52:14 +00001224 OverloadCandidateSet Conversions(From->getExprLoc(),
1225 OverloadCandidateSet::CSK_Normal);
Richard Smith48372b62015-01-27 03:30:40 +00001226 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1227 Conversions, AllowExplicit,
1228 AllowObjCConversionOnExplicit)) {
1229 case OR_Success:
1230 case OR_Deleted:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001231 ICS.setUserDefined();
1232 // 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
1237 // constructor (i.e., a user-defined conversion function) is
1238 // called for those cases.
1239 if (CXXConstructorDecl *Constructor
1240 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1241 QualType FromCanon
1242 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1243 QualType ToCanon
1244 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1245 if (Constructor->isCopyConstructor() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00001246 (FromCanon == ToCanon ||
1247 S.IsDerivedFrom(From->getLocStart(), FromCanon, ToCanon))) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001248 // Turn this into a "standard" conversion sequence, so that it
1249 // gets ranked with standard conversion sequences.
Richard Smithc2bebe92016-05-11 20:37:46 +00001250 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001251 ICS.setStandard();
1252 ICS.Standard.setAsIdentityConversion();
1253 ICS.Standard.setFromType(From->getType());
1254 ICS.Standard.setAllToTypes(ToType);
1255 ICS.Standard.CopyConstructor = Constructor;
Richard Smithc2bebe92016-05-11 20:37:46 +00001256 ICS.Standard.FoundCopyConstructor = Found;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001257 if (ToCanon != FromCanon)
1258 ICS.Standard.Second = ICK_Derived_To_Base;
1259 }
1260 }
Richard Smith48372b62015-01-27 03:30:40 +00001261 break;
1262
1263 case OR_Ambiguous:
Richard Smith1bbaba82015-01-27 23:23:39 +00001264 ICS.setAmbiguous();
1265 ICS.Ambiguous.setFromType(From->getType());
1266 ICS.Ambiguous.setToType(ToType);
1267 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1268 Cand != Conversions.end(); ++Cand)
1269 if (Cand->Viable)
Richard Smithc2bebe92016-05-11 20:37:46 +00001270 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
Richard Smith1bbaba82015-01-27 23:23:39 +00001271 break;
Richard Smith48372b62015-01-27 03:30:40 +00001272
1273 // Fall through.
1274 case OR_No_Viable_Function:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001275 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Richard Smith48372b62015-01-27 03:30:40 +00001276 break;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001277 }
1278
1279 return ICS;
1280}
1281
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001282/// TryImplicitConversion - Attempt to perform an implicit conversion
1283/// from the given expression (Expr) to the given type (ToType). This
1284/// function returns an implicit conversion sequence that can be used
1285/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001286///
1287/// void f(float f);
1288/// void g(int i) { f(i); }
1289///
1290/// this routine would produce an implicit conversion sequence to
1291/// describe the initialization of f from i, which will be a standard
1292/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1293/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1294//
1295/// Note that this routine only determines how the conversion can be
1296/// performed; it does not actually perform the conversion. As such,
1297/// it will not produce any diagnostics if no conversion is available,
1298/// but will instead return an implicit conversion sequence of kind
1299/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +00001300///
1301/// If @p SuppressUserConversions, then user-defined conversions are
1302/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +00001303/// If @p AllowExplicit, then explicit user-defined conversions are
1304/// permitted.
John McCall31168b02011-06-15 23:02:42 +00001305///
1306/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1307/// writeback conversion, which allows __autoreleasing id* parameters to
1308/// be initialized with __strong id* or __weak id* arguments.
John McCall5c32be02010-08-24 20:38:10 +00001309static ImplicitConversionSequence
1310TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1311 bool SuppressUserConversions,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001312 bool AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001313 bool InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001314 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001315 bool AllowObjCWritebackConversion,
1316 bool AllowObjCConversionOnExplicit) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001317 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +00001318 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001319 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall0d1da222010-01-12 00:44:57 +00001320 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +00001321 return ICS;
1322 }
1323
David Blaikiebbafb8a2012-03-11 07:00:24 +00001324 if (!S.getLangOpts().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +00001325 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +00001326 return ICS;
1327 }
1328
Douglas Gregor836a7e82010-08-11 02:15:33 +00001329 // C++ [over.ics.user]p4:
1330 // A conversion of an expression of class type to the same class
1331 // type is given Exact Match rank, and a conversion of an
1332 // expression of class type to a base class of that type is
1333 // given Conversion rank, in spite of the fact that a copy/move
1334 // constructor (i.e., a user-defined conversion function) is
1335 // called for those cases.
1336 QualType FromType = From->getType();
1337 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00001338 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00001339 S.IsDerivedFrom(From->getLocStart(), FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001340 ICS.setStandard();
1341 ICS.Standard.setAsIdentityConversion();
1342 ICS.Standard.setFromType(FromType);
1343 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001344
Douglas Gregor5ab11652010-04-17 22:01:05 +00001345 // We don't actually check at this point whether there is a valid
1346 // copy/move constructor, since overloading just assumes that it
1347 // exists. When we actually perform initialization, we'll find the
1348 // appropriate constructor to copy the returned object, if needed.
Craig Topperc3ec1492014-05-26 06:22:03 +00001349 ICS.Standard.CopyConstructor = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001350
Douglas Gregor5ab11652010-04-17 22:01:05 +00001351 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +00001352 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +00001353 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001354
Douglas Gregor836a7e82010-08-11 02:15:33 +00001355 return ICS;
1356 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001357
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001358 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1359 AllowExplicit, InOverloadResolution, CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001360 AllowObjCWritebackConversion,
1361 AllowObjCConversionOnExplicit);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001362}
1363
John McCall31168b02011-06-15 23:02:42 +00001364ImplicitConversionSequence
1365Sema::TryImplicitConversion(Expr *From, QualType ToType,
1366 bool SuppressUserConversions,
1367 bool AllowExplicit,
1368 bool InOverloadResolution,
1369 bool CStyle,
1370 bool AllowObjCWritebackConversion) {
Richard Smith17c00b42014-11-12 01:24:00 +00001371 return ::TryImplicitConversion(*this, From, ToType,
1372 SuppressUserConversions, AllowExplicit,
1373 InOverloadResolution, CStyle,
1374 AllowObjCWritebackConversion,
1375 /*AllowObjCConversionOnExplicit=*/false);
John McCall5c32be02010-08-24 20:38:10 +00001376}
1377
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001378/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley01296292011-04-08 18:41:53 +00001379/// expression From to the type ToType. Returns the
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001380/// converted expression. Flavor is the kind of conversion we're
1381/// performing, used in the error message. If @p AllowExplicit,
1382/// explicit user-defined conversions are permitted.
John Wiegley01296292011-04-08 18:41:53 +00001383ExprResult
1384Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redlcc152642011-10-16 18:19:06 +00001385 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001386 ImplicitConversionSequence ICS;
Sebastian Redlcc152642011-10-16 18:19:06 +00001387 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001388}
1389
John Wiegley01296292011-04-08 18:41:53 +00001390ExprResult
1391Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001392 AssignmentAction Action, bool AllowExplicit,
Sebastian Redlcc152642011-10-16 18:19:06 +00001393 ImplicitConversionSequence& ICS) {
John McCall526ab472011-10-25 17:37:35 +00001394 if (checkPlaceholderForOverload(*this, From))
1395 return ExprError();
1396
John McCall31168b02011-06-15 23:02:42 +00001397 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1398 bool AllowObjCWritebackConversion
David Blaikiebbafb8a2012-03-11 07:00:24 +00001399 = getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001400 (Action == AA_Passing || Action == AA_Sending);
Fariborz Jahanian381edf52013-12-16 22:54:37 +00001401 if (getLangOpts().ObjC1)
1402 CheckObjCBridgeRelatedConversions(From->getLocStart(),
1403 ToType, From->getType(), From);
Richard Smith17c00b42014-11-12 01:24:00 +00001404 ICS = ::TryImplicitConversion(*this, From, ToType,
1405 /*SuppressUserConversions=*/false,
1406 AllowExplicit,
1407 /*InOverloadResolution=*/false,
1408 /*CStyle=*/false,
1409 AllowObjCWritebackConversion,
1410 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001411 return PerformImplicitConversion(From, ToType, ICS, Action);
1412}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001413
1414/// \brief Determine whether the conversion from FromType to ToType is a valid
Richard Smith3c4f8d22016-10-16 17:54:23 +00001415/// conversion that strips "noexcept" or "noreturn" off the nested function
1416/// type.
1417bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
Chandler Carruth53e61b02011-06-18 01:19:03 +00001418 QualType &ResultTy) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001419 if (Context.hasSameUnqualifiedType(FromType, ToType))
1420 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001421
John McCall991eb4b2010-12-21 00:44:39 +00001422 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
Richard Smith3c4f8d22016-10-16 17:54:23 +00001423 // or F(t noexcept) -> F(t)
John McCall991eb4b2010-12-21 00:44:39 +00001424 // where F adds one of the following at most once:
1425 // - a pointer
1426 // - a member pointer
1427 // - a block pointer
Richard Smitheb7ef2e2016-10-20 21:53:09 +00001428 // Changes here need matching changes in FindCompositePointerType.
John McCall991eb4b2010-12-21 00:44:39 +00001429 CanQualType CanTo = Context.getCanonicalType(ToType);
1430 CanQualType CanFrom = Context.getCanonicalType(FromType);
1431 Type::TypeClass TyClass = CanTo->getTypeClass();
1432 if (TyClass != CanFrom->getTypeClass()) return false;
1433 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1434 if (TyClass == Type::Pointer) {
1435 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1436 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1437 } else if (TyClass == Type::BlockPointer) {
1438 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1439 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1440 } else if (TyClass == Type::MemberPointer) {
Richard Smitheb7ef2e2016-10-20 21:53:09 +00001441 auto ToMPT = CanTo.getAs<MemberPointerType>();
1442 auto FromMPT = CanFrom.getAs<MemberPointerType>();
1443 // A function pointer conversion cannot change the class of the function.
1444 if (ToMPT->getClass() != FromMPT->getClass())
1445 return false;
1446 CanTo = ToMPT->getPointeeType();
1447 CanFrom = FromMPT->getPointeeType();
John McCall991eb4b2010-12-21 00:44:39 +00001448 } else {
1449 return false;
1450 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001451
John McCall991eb4b2010-12-21 00:44:39 +00001452 TyClass = CanTo->getTypeClass();
1453 if (TyClass != CanFrom->getTypeClass()) return false;
1454 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1455 return false;
1456 }
1457
Richard Smith3c4f8d22016-10-16 17:54:23 +00001458 const auto *FromFn = cast<FunctionType>(CanFrom);
1459 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
John McCall991eb4b2010-12-21 00:44:39 +00001460
Richard Smith6f427402016-10-20 00:01:36 +00001461 const auto *ToFn = cast<FunctionType>(CanTo);
Richard Smith3c4f8d22016-10-16 17:54:23 +00001462 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1463
1464 bool Changed = false;
1465
1466 // Drop 'noreturn' if not present in target type.
1467 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1468 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1469 Changed = true;
1470 }
1471
1472 // Drop 'noexcept' if not present in target type.
1473 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
Richard Smith6f427402016-10-20 00:01:36 +00001474 const auto *ToFPT = cast<FunctionProtoType>(ToFn);
Richard Smith3c4f8d22016-10-16 17:54:23 +00001475 if (FromFPT->isNothrow(Context) && !ToFPT->isNothrow(Context)) {
1476 FromFn = cast<FunctionType>(
1477 Context.getFunctionType(FromFPT->getReturnType(),
1478 FromFPT->getParamTypes(),
1479 FromFPT->getExtProtoInfo().withExceptionSpec(
1480 FunctionProtoType::ExceptionSpecInfo()))
1481 .getTypePtr());
1482 Changed = true;
1483 }
1484 }
1485
1486 if (!Changed)
1487 return false;
1488
John McCall991eb4b2010-12-21 00:44:39 +00001489 assert(QualType(FromFn, 0).isCanonical());
1490 if (QualType(FromFn, 0) != CanTo) return false;
1491
1492 ResultTy = ToType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001493 return true;
1494}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001495
Douglas Gregor46188682010-05-18 22:42:18 +00001496/// \brief Determine whether the conversion from FromType to ToType is a valid
1497/// vector conversion.
1498///
1499/// \param ICK Will be set to the vector conversion kind, if this is a vector
1500/// conversion.
John McCall9b595db2014-02-04 23:58:19 +00001501static bool IsVectorConversion(Sema &S, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001502 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregor46188682010-05-18 22:42:18 +00001503 // We need at least one of these types to be a vector type to have a vector
1504 // conversion.
1505 if (!ToType->isVectorType() && !FromType->isVectorType())
1506 return false;
1507
1508 // Identical types require no conversions.
John McCall9b595db2014-02-04 23:58:19 +00001509 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor46188682010-05-18 22:42:18 +00001510 return false;
1511
1512 // There are no conversions between extended vector types, only identity.
1513 if (ToType->isExtVectorType()) {
1514 // There are no conversions between extended vector types other than the
1515 // identity conversion.
1516 if (FromType->isExtVectorType())
1517 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001518
Douglas Gregor46188682010-05-18 22:42:18 +00001519 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +00001520 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +00001521 ICK = ICK_Vector_Splat;
1522 return true;
1523 }
1524 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001525
1526 // We can perform the conversion between vector types in the following cases:
1527 // 1)vector types are equivalent AltiVec and GCC vector types
1528 // 2)lax vector conversions are permitted and the vector types are of the
1529 // same size
1530 if (ToType->isVectorType() && FromType->isVectorType()) {
John McCall9b595db2014-02-04 23:58:19 +00001531 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1532 S.isLaxVectorConversion(FromType, ToType)) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001533 ICK = ICK_Vector_Conversion;
1534 return true;
1535 }
Douglas Gregor46188682010-05-18 22:42:18 +00001536 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001537
Douglas Gregor46188682010-05-18 22:42:18 +00001538 return false;
1539}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001540
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001541static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1542 bool InOverloadResolution,
1543 StandardConversionSequence &SCS,
1544 bool CStyle);
George Burgess IV45461812015-10-11 20:13:20 +00001545
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001546/// IsStandardConversion - Determines whether there is a standard
1547/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1548/// expression From to the type ToType. Standard conversion sequences
1549/// only consider non-class types; for conversions that involve class
1550/// types, use TryImplicitConversion. If a conversion exists, SCS will
1551/// contain the standard conversion sequence required to perform this
1552/// conversion and this routine will return true. Otherwise, this
1553/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +00001554static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1555 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +00001556 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +00001557 bool CStyle,
1558 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001559 QualType FromType = From->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001560
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001561 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +00001562 SCS.setAsIdentityConversion();
Douglas Gregor47d3f272008-12-19 17:40:08 +00001563 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +00001564 SCS.setFromType(FromType);
Craig Topperc3ec1492014-05-26 06:22:03 +00001565 SCS.CopyConstructor = nullptr;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001566
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001567 // There are no standard conversions for class types in C++, so
George Burgess IV45461812015-10-11 20:13:20 +00001568 // abort early. When overloading in C, however, we do permit them.
1569 if (S.getLangOpts().CPlusPlus &&
1570 (FromType->isRecordType() || ToType->isRecordType()))
1571 return false;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001572
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001573 // The first conversion can be an lvalue-to-rvalue conversion,
1574 // array-to-pointer conversion, or function-to-pointer conversion
1575 // (C++ 4p1).
1576
John McCall5c32be02010-08-24 20:38:10 +00001577 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001578 DeclAccessPair AccessPair;
1579 if (FunctionDecl *Fn
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001580 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall5c32be02010-08-24 20:38:10 +00001581 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001582 // We were able to resolve the address of the overloaded function,
1583 // so we can convert to the type of that function.
1584 FromType = Fn->getType();
Ehsan Akhgaric3ad3ba2014-07-22 20:20:14 +00001585 SCS.setFromType(FromType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00001586
1587 // we can sometimes resolve &foo<int> regardless of ToType, so check
1588 // if the type matches (identity) or we are converting to bool
1589 if (!S.Context.hasSameUnqualifiedType(
1590 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1591 QualType resultTy;
1592 // if the function type matches except for [[noreturn]], it's ok
Richard Smith3c4f8d22016-10-16 17:54:23 +00001593 if (!S.IsFunctionConversion(FromType,
Douglas Gregorb491ed32011-02-19 21:32:49 +00001594 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1595 // otherwise, only a boolean conversion is standard
1596 if (!ToType->isBooleanType())
1597 return false;
Douglas Gregor980fb162010-04-29 18:24:40 +00001598 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001599
Chandler Carruthffce2452011-03-29 08:08:18 +00001600 // Check if the "from" expression is taking the address of an overloaded
1601 // function and recompute the FromType accordingly. Take advantage of the
1602 // fact that non-static member functions *must* have such an address-of
1603 // expression.
1604 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1605 if (Method && !Method->isStatic()) {
1606 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1607 "Non-unary operator on non-static member address");
1608 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1609 == UO_AddrOf &&
1610 "Non-address-of operator on non-static member address");
1611 const Type *ClassType
1612 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1613 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruth7750f762011-03-29 18:38:10 +00001614 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1615 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1616 UO_AddrOf &&
Chandler Carruthffce2452011-03-29 08:08:18 +00001617 "Non-address-of operator for overloaded function expression");
1618 FromType = S.Context.getPointerType(FromType);
1619 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001620
Douglas Gregor980fb162010-04-29 18:24:40 +00001621 // Check that we've computed the proper type after overload resolution.
Richard Smith9095e5b2016-11-01 01:31:23 +00001622 // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't
1623 // be calling it from within an NDEBUG block.
Chandler Carruthffce2452011-03-29 08:08:18 +00001624 assert(S.Context.hasSameType(
1625 FromType,
1626 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001627 } else {
1628 return false;
1629 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001630 }
John McCall154a2fd2011-08-30 00:57:29 +00001631 // Lvalue-to-rvalue conversion (C++11 4.1):
1632 // A glvalue (3.10) of a non-function, non-array type T can
1633 // be converted to a prvalue.
1634 bool argIsLValue = From->isGLValue();
John McCall086a4642010-11-24 05:12:34 +00001635 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001636 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001637 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001638 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001639
Douglas Gregorc79862f2012-04-12 17:51:55 +00001640 // C11 6.3.2.1p2:
1641 // ... if the lvalue has atomic type, the value has the non-atomic version
1642 // of the type of the lvalue ...
1643 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1644 FromType = Atomic->getValueType();
1645
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001646 // If T is a non-class type, the type of the rvalue is the
1647 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001648 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1649 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001650 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001651 } else if (FromType->isArrayType()) {
1652 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001653 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001654
1655 // An lvalue or rvalue of type "array of N T" or "array of unknown
1656 // bound of T" can be converted to an rvalue of type "pointer to
1657 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001658 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001659
John McCall5c32be02010-08-24 20:38:10 +00001660 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00001661 // This conversion is deprecated in C++03 (D.4)
Douglas Gregore489a7d2010-02-28 18:30:25 +00001662 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001663
1664 // For the purpose of ranking in overload resolution
1665 // (13.3.3.1.1), this conversion is considered an
1666 // array-to-pointer conversion followed by a qualification
1667 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001668 SCS.Second = ICK_Identity;
1669 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001670 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001671 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001672 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001673 }
John McCall086a4642010-11-24 05:12:34 +00001674 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001675 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001676 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001677
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001678 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1679 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1680 if (!S.checkAddressOfFunctionIsAvailable(FD))
1681 return false;
1682
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001683 // An lvalue of function type T can be converted to an rvalue of
1684 // type "pointer to T." The result is a pointer to the
1685 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001686 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001687 } else {
1688 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001689 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001690 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001691 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001692
1693 // The second conversion can be an integral promotion, floating
1694 // point promotion, integral conversion, floating point conversion,
1695 // floating-integral conversion, pointer conversion,
1696 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001697 // For overloading in C, this can also be a "compatible-type"
1698 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001699 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001700 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001701 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001702 // The unqualified versions of the types are the same: there's no
1703 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001704 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001705 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001706 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001707 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001708 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001709 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001710 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001711 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001712 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001713 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001714 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001715 SCS.Second = ICK_Complex_Promotion;
1716 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001717 } else if (ToType->isBooleanType() &&
1718 (FromType->isArithmeticType() ||
1719 FromType->isAnyPointerType() ||
1720 FromType->isBlockPointerType() ||
1721 FromType->isMemberPointerType() ||
1722 FromType->isNullPtrType())) {
1723 // Boolean conversions (C++ 4.12).
1724 SCS.Second = ICK_Boolean_Conversion;
1725 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001726 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001727 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001728 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001729 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001730 FromType = ToType.getUnqualifiedType();
Richard Smithb8a98242013-05-10 20:29:50 +00001731 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001732 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001733 SCS.Second = ICK_Complex_Conversion;
1734 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001735 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1736 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001737 // Complex-real conversions (C99 6.3.1.7)
1738 SCS.Second = ICK_Complex_Real;
1739 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001740 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001741 // FIXME: disable conversions between long double and __float128 if
1742 // their representation is different until there is back end support
1743 // We of course allow this conversion if long double is really double.
1744 if (&S.Context.getFloatTypeSemantics(FromType) !=
1745 &S.Context.getFloatTypeSemantics(ToType)) {
1746 bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1747 ToType == S.Context.LongDoubleTy) ||
1748 (FromType == S.Context.LongDoubleTy &&
1749 ToType == S.Context.Float128Ty));
1750 if (Float128AndLongDouble &&
1751 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) !=
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001752 &llvm::APFloat::IEEEdouble()))
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001753 return false;
1754 }
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001755 // Floating point conversions (C++ 4.8).
1756 SCS.Second = ICK_Floating_Conversion;
1757 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001758 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001759 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001760 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001761 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001762 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001763 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001764 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001765 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCall31168b02011-06-15 23:02:42 +00001766 SCS.Second = ICK_Block_Pointer_Conversion;
1767 } else if (AllowObjCWritebackConversion &&
1768 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1769 SCS.Second = ICK_Writeback_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001770 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1771 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001772 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001773 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001774 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregoraec25842011-04-26 23:16:46 +00001775 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001776 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall5c32be02010-08-24 20:38:10 +00001777 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001778 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001779 SCS.Second = ICK_Pointer_Member;
John McCall9b595db2014-02-04 23:58:19 +00001780 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001781 SCS.Second = SecondICK;
1782 FromType = ToType.getUnqualifiedType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001783 } else if (!S.getLangOpts().CPlusPlus &&
John McCall5c32be02010-08-24 20:38:10 +00001784 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001785 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001786 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001787 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001788 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1789 InOverloadResolution,
1790 SCS, CStyle)) {
1791 SCS.Second = ICK_TransparentUnionConversion;
1792 FromType = ToType;
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001793 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1794 CStyle)) {
1795 // tryAtomicConversion has updated the standard conversion sequence
Douglas Gregorc79862f2012-04-12 17:51:55 +00001796 // appropriately.
1797 return true;
George Burgess IV45461812015-10-11 20:13:20 +00001798 } else if (ToType->isEventT() &&
Guy Benyei259f9f42013-02-07 16:05:33 +00001799 From->isIntegerConstantExpr(S.getASTContext()) &&
George Burgess IV45461812015-10-11 20:13:20 +00001800 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
Guy Benyei259f9f42013-02-07 16:05:33 +00001801 SCS.Second = ICK_Zero_Event_Conversion;
1802 FromType = ToType;
Egor Churaev89831422016-12-23 14:55:49 +00001803 } else if (ToType->isQueueT() &&
1804 From->isIntegerConstantExpr(S.getASTContext()) &&
1805 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1806 SCS.Second = ICK_Zero_Queue_Conversion;
1807 FromType = ToType;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001808 } else {
1809 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001810 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001811 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001812 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001813
Richard Smitheb7ef2e2016-10-20 21:53:09 +00001814 // The third conversion can be a function pointer conversion or a
1815 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
John McCall31168b02011-06-15 23:02:42 +00001816 bool ObjCLifetimeConversion;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00001817 if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1818 // Function pointer conversions (removing 'noexcept') including removal of
1819 // 'noreturn' (Clang extension).
1820 SCS.Third = ICK_Function_Conversion;
1821 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1822 ObjCLifetimeConversion)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001823 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001824 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001825 FromType = ToType;
1826 } else {
1827 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001828 SCS.Third = ICK_Identity;
Richard Smith9c37e662016-10-20 17:57:33 +00001829 }
Richard Smitheb7ef2e2016-10-20 21:53:09 +00001830
1831 // C++ [over.best.ics]p6:
1832 // [...] Any difference in top-level cv-qualification is
1833 // subsumed by the initialization itself and does not constitute
1834 // a conversion. [...]
1835 QualType CanonFrom = S.Context.getCanonicalType(FromType);
1836 QualType CanonTo = S.Context.getCanonicalType(ToType);
1837 if (CanonFrom.getLocalUnqualifiedType()
1838 == CanonTo.getLocalUnqualifiedType() &&
1839 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1840 FromType = ToType;
1841 CanonFrom = CanonTo;
1842 }
1843
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001844 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001845
George Burgess IV45461812015-10-11 20:13:20 +00001846 if (CanonFrom == CanonTo)
1847 return true;
1848
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001849 // If we have not converted the argument type to the parameter type,
George Burgess IV45461812015-10-11 20:13:20 +00001850 // this is a bad conversion sequence, unless we're resolving an overload in C.
1851 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001852 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001853
George Burgess IV45461812015-10-11 20:13:20 +00001854 ExprResult ER = ExprResult{From};
George Burgess IV2099b542016-09-02 22:59:57 +00001855 Sema::AssignConvertType Conv =
1856 S.CheckSingleAssignmentConstraints(ToType, ER,
1857 /*Diagnose=*/false,
1858 /*DiagnoseCFAudited=*/false,
1859 /*ConvertRHS=*/false);
George Burgess IV6098fd12016-09-03 00:28:25 +00001860 ImplicitConversionKind SecondConv;
George Burgess IV2099b542016-09-02 22:59:57 +00001861 switch (Conv) {
1862 case Sema::Compatible:
George Burgess IV6098fd12016-09-03 00:28:25 +00001863 SecondConv = ICK_C_Only_Conversion;
George Burgess IV2099b542016-09-02 22:59:57 +00001864 break;
1865 // For our purposes, discarding qualifiers is just as bad as using an
1866 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
1867 // qualifiers, as well.
1868 case Sema::CompatiblePointerDiscardsQualifiers:
1869 case Sema::IncompatiblePointer:
1870 case Sema::IncompatiblePointerSign:
George Burgess IV6098fd12016-09-03 00:28:25 +00001871 SecondConv = ICK_Incompatible_Pointer_Conversion;
George Burgess IV2099b542016-09-02 22:59:57 +00001872 break;
1873 default:
George Burgess IV45461812015-10-11 20:13:20 +00001874 return false;
George Burgess IV2099b542016-09-02 22:59:57 +00001875 }
George Burgess IV45461812015-10-11 20:13:20 +00001876
George Burgess IV6098fd12016-09-03 00:28:25 +00001877 // First can only be an lvalue conversion, so we pretend that this was the
1878 // second conversion. First should already be valid from earlier in the
1879 // function.
1880 SCS.Second = SecondConv;
1881 SCS.setToType(1, ToType);
1882
1883 // Third is Identity, because Second should rank us worse than any other
1884 // conversion. This could also be ICK_Qualification, but it's simpler to just
1885 // lump everything in with the second conversion, and we don't gain anything
1886 // from making this ICK_Qualification.
1887 SCS.Third = ICK_Identity;
1888 SCS.setToType(2, ToType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001889 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001890}
George Burgess IV2099b542016-09-02 22:59:57 +00001891
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001892static bool
1893IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1894 QualType &ToType,
1895 bool InOverloadResolution,
1896 StandardConversionSequence &SCS,
1897 bool CStyle) {
1898
1899 const RecordType *UT = ToType->getAsUnionType();
1900 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1901 return false;
1902 // The field to initialize within the transparent union.
1903 RecordDecl *UD = UT->getDecl();
1904 // It's compatible if the expression matches any of the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001905 for (const auto *it : UD->fields()) {
John McCall31168b02011-06-15 23:02:42 +00001906 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1907 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001908 ToType = it->getType();
1909 return true;
1910 }
1911 }
1912 return false;
1913}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001914
1915/// IsIntegralPromotion - Determines whether the conversion from the
1916/// expression From (whose potentially-adjusted type is FromType) to
1917/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1918/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001919bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001920 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001921 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001922 if (!To) {
1923 return false;
1924 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001925
1926 // An rvalue of type char, signed char, unsigned char, short int, or
1927 // unsigned short int can be converted to an rvalue of type int if
1928 // int can represent all the values of the source type; otherwise,
1929 // the source rvalue can be converted to an rvalue of type unsigned
1930 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001931 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1932 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001933 if (// We can promote any signed, promotable integer type to an int
1934 (FromType->isSignedIntegerType() ||
1935 // We can promote any unsigned integer type whose size is
1936 // less than int to an int.
Benjamin Kramer5ff67472016-04-11 08:26:13 +00001937 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001938 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001939 }
1940
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001941 return To->getKind() == BuiltinType::UInt;
1942 }
1943
Richard Smithb9c5a602012-09-13 21:18:54 +00001944 // C++11 [conv.prom]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001945 // A prvalue of an unscoped enumeration type whose underlying type is not
1946 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1947 // following types that can represent all the values of the enumeration
1948 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1949 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001950 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001951 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001952 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001953 // with lowest integer conversion rank (4.13) greater than the rank of long
1954 // long in which all the values of the enumeration can be represented. If
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001955 // there are two such extended types, the signed one is chosen.
Richard Smithb9c5a602012-09-13 21:18:54 +00001956 // C++11 [conv.prom]p4:
1957 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1958 // can be converted to a prvalue of its underlying type. Moreover, if
1959 // integral promotion can be applied to its underlying type, a prvalue of an
1960 // unscoped enumeration type whose underlying type is fixed can also be
1961 // converted to a prvalue of the promoted underlying type.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001962 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1963 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1964 // provided for a scoped enumeration.
1965 if (FromEnumType->getDecl()->isScoped())
1966 return false;
1967
Richard Smithb9c5a602012-09-13 21:18:54 +00001968 // We can perform an integral promotion to the underlying type of the enum,
Richard Smithac8c1752015-03-28 00:31:40 +00001969 // even if that's not the promoted type. Note that the check for promoting
1970 // the underlying type is based on the type alone, and does not consider
1971 // the bitfield-ness of the actual source expression.
Richard Smithb9c5a602012-09-13 21:18:54 +00001972 if (FromEnumType->getDecl()->isFixed()) {
1973 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1974 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
Richard Smithac8c1752015-03-28 00:31:40 +00001975 IsIntegralPromotion(nullptr, Underlying, ToType);
Richard Smithb9c5a602012-09-13 21:18:54 +00001976 }
1977
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001978 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001979 if (ToType->isIntegerType() &&
Richard Smithdb0ac552015-12-18 22:40:25 +00001980 isCompleteType(From->getLocStart(), FromType))
Richard Smith88f4bba2015-03-26 00:16:07 +00001981 return Context.hasSameUnqualifiedType(
1982 ToType, FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001983 }
John McCall56774992009-12-09 09:09:27 +00001984
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001985 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001986 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1987 // to an rvalue a prvalue of the first of the following types that can
1988 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001989 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001990 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001991 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001992 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001993 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001994 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001995 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001996 // Determine whether the type we're converting from is signed or
1997 // unsigned.
David Majnemerfa01a582011-07-22 21:09:04 +00001998 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001999 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002000
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002001 // The types we'll try to promote to, in the appropriate
2002 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00002003 QualType PromoteTypes[6] = {
2004 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00002005 Context.LongTy, Context.UnsignedLongTy ,
2006 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002007 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00002008 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002009 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2010 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00002011 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002012 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2013 // We found the type that we can promote to. If this is the
2014 // type we wanted, we have a promotion. Otherwise, no
2015 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002016 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002017 }
2018 }
2019 }
2020
2021 // An rvalue for an integral bit-field (9.6) can be converted to an
2022 // rvalue of type int if int can represent all the values of the
2023 // bit-field; otherwise, it can be converted to unsigned int if
2024 // unsigned int can represent all the values of the bit-field. If
2025 // the bit-field is larger yet, no integral promotion applies to
2026 // it. If the bit-field has an enumerated type, it is treated as any
2027 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00002028 // FIXME: We should delay checking of bit-fields until we actually perform the
2029 // conversion.
Richard Smith88f4bba2015-03-26 00:16:07 +00002030 if (From) {
John McCalld25db7e2013-05-06 21:39:12 +00002031 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
Richard Smith88f4bba2015-03-26 00:16:07 +00002032 llvm::APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00002033 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00002034 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
Richard Smith88f4bba2015-03-26 00:16:07 +00002035 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
Douglas Gregor71235ec2009-05-02 02:18:30 +00002036 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00002037
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00002038 // Are we promoting to an int from a bitfield that fits in an int?
2039 if (BitWidth < ToSize ||
2040 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
2041 return To->getKind() == BuiltinType::Int;
2042 }
Mike Stump11289f42009-09-09 15:08:12 +00002043
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00002044 // Are we promoting to an unsigned int from an unsigned bitfield
2045 // that fits into an unsigned int?
2046 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
2047 return To->getKind() == BuiltinType::UInt;
2048 }
Mike Stump11289f42009-09-09 15:08:12 +00002049
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00002050 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002051 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002052 }
Richard Smith88f4bba2015-03-26 00:16:07 +00002053 }
Mike Stump11289f42009-09-09 15:08:12 +00002054
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002055 // An rvalue of type bool can be converted to an rvalue of type int,
2056 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002057 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002058 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002059 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002060
2061 return false;
2062}
2063
2064/// IsFloatingPointPromotion - Determines whether the conversion from
2065/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2066/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00002067bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00002068 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2069 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002070 /// An rvalue of type float can be converted to an rvalue of type
2071 /// double. (C++ 4.6p1).
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002072 if (FromBuiltin->getKind() == BuiltinType::Float &&
2073 ToBuiltin->getKind() == BuiltinType::Double)
2074 return true;
2075
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002076 // C99 6.3.1.5p1:
2077 // When a float is promoted to double or long double, or a
2078 // double is promoted to long double [...].
David Blaikiebbafb8a2012-03-11 07:00:24 +00002079 if (!getLangOpts().CPlusPlus &&
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002080 (FromBuiltin->getKind() == BuiltinType::Float ||
2081 FromBuiltin->getKind() == BuiltinType::Double) &&
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002082 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2083 ToBuiltin->getKind() == BuiltinType::Float128))
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002084 return true;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002085
2086 // Half can be promoted to float.
Joey Goulydd7f4562013-01-23 11:56:20 +00002087 if (!getLangOpts().NativeHalfType &&
2088 FromBuiltin->getKind() == BuiltinType::Half &&
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002089 ToBuiltin->getKind() == BuiltinType::Float)
2090 return true;
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002091 }
2092
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002093 return false;
2094}
2095
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002096/// \brief Determine if a conversion is a complex promotion.
2097///
2098/// A complex promotion is defined as a complex -> complex conversion
2099/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00002100/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002101bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00002102 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002103 if (!FromComplex)
2104 return false;
2105
John McCall9dd450b2009-09-21 23:43:11 +00002106 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002107 if (!ToComplex)
2108 return false;
2109
2110 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00002111 ToComplex->getElementType()) ||
Craig Topperc3ec1492014-05-26 06:22:03 +00002112 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00002113 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002114}
2115
Douglas Gregor237f96c2008-11-26 23:31:11 +00002116/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2117/// the pointer type FromPtr to a pointer to type ToPointee, with the
2118/// same type qualifiers as FromPtr has on its pointee type. ToType,
2119/// if non-empty, will be a pointer to ToType that may or may not have
2120/// the right set of qualifiers on its pointee.
John McCall31168b02011-06-15 23:02:42 +00002121///
Mike Stump11289f42009-09-09 15:08:12 +00002122static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002123BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002124 QualType ToPointee, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002125 ASTContext &Context,
2126 bool StripObjCLifetime = false) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002127 assert((FromPtr->getTypeClass() == Type::Pointer ||
2128 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2129 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002130
John McCall31168b02011-06-15 23:02:42 +00002131 /// Conversions to 'id' subsume cv-qualifier conversions.
2132 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00002133 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002134
2135 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002136 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00002137 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00002138 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00002139
John McCall31168b02011-06-15 23:02:42 +00002140 if (StripObjCLifetime)
2141 Quals.removeObjCLifetime();
2142
Mike Stump11289f42009-09-09 15:08:12 +00002143 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002144 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00002145 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00002146 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00002147 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002148
2149 // Build a pointer to ToPointee. It has the right qualifiers
2150 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002151 if (isa<ObjCObjectPointerType>(ToType))
2152 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00002153 return Context.getPointerType(ToPointee);
2154 }
2155
2156 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002157 QualType QualifiedCanonToPointee
2158 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002159
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002160 if (isa<ObjCObjectPointerType>(ToType))
2161 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2162 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002163}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002164
Mike Stump11289f42009-09-09 15:08:12 +00002165static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00002166 bool InOverloadResolution,
2167 ASTContext &Context) {
2168 // Handle value-dependent integral null pointer constants correctly.
2169 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2170 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00002171 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00002172 return !InOverloadResolution;
2173
Douglas Gregor56751b52009-09-25 04:25:58 +00002174 return Expr->isNullPointerConstant(Context,
2175 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2176 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00002177}
Mike Stump11289f42009-09-09 15:08:12 +00002178
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002179/// IsPointerConversion - Determines whether the conversion of the
2180/// expression From, which has the (possibly adjusted) type FromType,
2181/// can be converted to the type ToType via a pointer conversion (C++
2182/// 4.10). If so, returns true and places the converted type (that
2183/// might differ from ToType in its cv-qualifiers at some level) into
2184/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00002185///
Douglas Gregora29dc052008-11-27 01:19:21 +00002186/// This routine also supports conversions to and from block pointers
2187/// and conversions with Objective-C's 'id', 'id<protocols...>', and
2188/// pointers to interfaces. FIXME: Once we've determined the
2189/// appropriate overloading rules for Objective-C, we may want to
2190/// split the Objective-C checks into a different routine; however,
2191/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00002192/// conversions, so for now they live here. IncompatibleObjC will be
2193/// set if the conversion is an allowed Objective-C conversion that
2194/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002195bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00002196 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00002197 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00002198 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00002199 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00002200 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2201 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00002202 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00002203
Mike Stump11289f42009-09-09 15:08:12 +00002204 // Conversion from a null pointer constant to any Objective-C pointer type.
2205 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002206 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00002207 ConvertedType = ToType;
2208 return true;
2209 }
2210
Douglas Gregor231d1c62008-11-27 00:15:41 +00002211 // Blocks: Block pointers can be converted to void*.
2212 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002213 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00002214 ConvertedType = ToType;
2215 return true;
2216 }
2217 // Blocks: A null pointer constant can be converted to a block
2218 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00002219 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002220 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00002221 ConvertedType = ToType;
2222 return true;
2223 }
2224
Sebastian Redl576fd422009-05-10 18:38:11 +00002225 // If the left-hand-side is nullptr_t, the right side can be a null
2226 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00002227 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002228 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00002229 ConvertedType = ToType;
2230 return true;
2231 }
2232
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002233 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002234 if (!ToTypePtr)
2235 return false;
2236
2237 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00002238 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002239 ConvertedType = ToType;
2240 return true;
2241 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002242
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002243 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002244 // , including objective-c pointers.
2245 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00002246 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002247 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002248 ConvertedType = BuildSimilarlyQualifiedPointerType(
2249 FromType->getAs<ObjCObjectPointerType>(),
2250 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002251 ToType, Context);
2252 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002253 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002254 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002255 if (!FromTypePtr)
2256 return false;
2257
2258 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002259
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002260 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-08-18 21:25:30 +00002261 // pointer conversion, so don't do all of the work below.
2262 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2263 return false;
2264
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002265 // An rvalue of type "pointer to cv T," where T is an object type,
2266 // can be converted to an rvalue of type "pointer to cv void" (C++
2267 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00002268 if (FromPointeeType->isIncompleteOrObjectType() &&
2269 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002270 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002271 ToPointeeType,
John McCall31168b02011-06-15 23:02:42 +00002272 ToType, Context,
2273 /*StripObjCLifetime=*/true);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002274 return true;
2275 }
2276
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002277 // MSVC allows implicit function to void* type conversion.
David Majnemer6bf02822015-10-31 08:42:14 +00002278 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002279 ToPointeeType->isVoidType()) {
2280 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2281 ToPointeeType,
2282 ToType, Context);
2283 return true;
2284 }
2285
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002286 // When we're overloading in C, we allow a special kind of pointer
2287 // conversion for compatible-but-not-identical pointee types.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002288 if (!getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002289 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002290 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002291 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00002292 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002293 return true;
2294 }
2295
Douglas Gregor5c407d92008-10-23 00:40:37 +00002296 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002297 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00002298 // An rvalue of type "pointer to cv D," where D is a class type,
2299 // can be converted to an rvalue of type "pointer to cv B," where
2300 // B is a base class (clause 10) of D. If B is an inaccessible
2301 // (clause 11) or ambiguous (10.2) base class of D, a program that
2302 // necessitates this conversion is ill-formed. The result of the
2303 // conversion is a pointer to the base class sub-object of the
2304 // derived class object. The null pointer value is converted to
2305 // the null pointer value of the destination type.
2306 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00002307 // Note that we do not check for ambiguity or inaccessibility
2308 // here. That is handled by CheckPointerConversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002309 if (getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002310 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00002311 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00002312 IsDerivedFrom(From->getLocStart(), FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002313 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002314 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002315 ToType, Context);
2316 return true;
2317 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002318
Fariborz Jahanianbc2ee932011-04-14 20:33:36 +00002319 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2320 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2321 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2322 ToPointeeType,
2323 ToType, Context);
2324 return true;
2325 }
2326
Douglas Gregora119f102008-12-19 19:13:09 +00002327 return false;
2328}
Douglas Gregoraec25842011-04-26 23:16:46 +00002329
2330/// \brief Adopt the given qualifiers for the given type.
2331static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2332 Qualifiers TQs = T.getQualifiers();
2333
2334 // Check whether qualifiers already match.
2335 if (TQs == Qs)
2336 return T;
2337
2338 if (Qs.compatiblyIncludes(TQs))
2339 return Context.getQualifiedType(T, Qs);
2340
2341 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2342}
Douglas Gregora119f102008-12-19 19:13:09 +00002343
2344/// isObjCPointerConversion - Determines whether this is an
2345/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2346/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00002347bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00002348 QualType& ConvertedType,
2349 bool &IncompatibleObjC) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002350 if (!getLangOpts().ObjC1)
Douglas Gregora119f102008-12-19 19:13:09 +00002351 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002352
Douglas Gregoraec25842011-04-26 23:16:46 +00002353 // The set of qualifiers on the type we're converting from.
2354 Qualifiers FromQualifiers = FromType.getQualifiers();
2355
Steve Naroff7cae42b2009-07-10 23:34:53 +00002356 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00002357 const ObjCObjectPointerType* ToObjCPtr =
2358 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00002359 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00002360 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002361
Steve Naroff7cae42b2009-07-10 23:34:53 +00002362 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002363 // If the pointee types are the same (ignoring qualifications),
2364 // then this is not a pointer conversion.
2365 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2366 FromObjCPtr->getPointeeType()))
2367 return false;
2368
Douglas Gregorab209d82015-07-07 03:58:42 +00002369 // Conversion between Objective-C pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00002370 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002371 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2372 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002373 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002374 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2375 FromObjCPtr->getPointeeType()))
2376 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002377 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002378 ToObjCPtr->getPointeeType(),
2379 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002380 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002381 return true;
2382 }
2383
2384 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2385 // Okay: this is some kind of implicit downcast of Objective-C
2386 // interfaces, which is permitted. However, we're going to
2387 // complain about it.
2388 IncompatibleObjC = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002389 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002390 ToObjCPtr->getPointeeType(),
2391 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002392 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002393 return true;
2394 }
Mike Stump11289f42009-09-09 15:08:12 +00002395 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00002396 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00002397 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002398 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002399 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002400 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002401 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002402 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002403 // to a block pointer type.
2404 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002405 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002406 return true;
2407 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002408 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002409 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002410 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002411 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002412 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002413 // pointer to any object.
Douglas Gregoraec25842011-04-26 23:16:46 +00002414 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002415 return true;
2416 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002417 else
Douglas Gregora119f102008-12-19 19:13:09 +00002418 return false;
2419
Douglas Gregor033f56d2008-12-23 00:53:59 +00002420 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002421 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002422 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00002423 else if (const BlockPointerType *FromBlockPtr =
2424 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00002425 FromPointeeType = FromBlockPtr->getPointeeType();
2426 else
Douglas Gregora119f102008-12-19 19:13:09 +00002427 return false;
2428
Douglas Gregora119f102008-12-19 19:13:09 +00002429 // If we have pointers to pointers, recursively check whether this
2430 // is an Objective-C conversion.
2431 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2432 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2433 IncompatibleObjC)) {
2434 // We always complain about this conversion.
2435 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002436 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002437 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002438 return true;
2439 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002440 // Allow conversion of pointee being objective-c pointer to another one;
2441 // as in I* to id.
2442 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2443 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2444 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2445 IncompatibleObjC)) {
John McCall31168b02011-06-15 23:02:42 +00002446
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002447 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002448 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002449 return true;
2450 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002451
Douglas Gregor033f56d2008-12-23 00:53:59 +00002452 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00002453 // differences in the argument and result types are in Objective-C
2454 // pointer conversions. If so, we permit the conversion (but
2455 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00002456 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002457 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002458 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002459 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002460 if (FromFunctionType && ToFunctionType) {
2461 // If the function types are exactly the same, this isn't an
2462 // Objective-C pointer conversion.
2463 if (Context.getCanonicalType(FromPointeeType)
2464 == Context.getCanonicalType(ToPointeeType))
2465 return false;
2466
2467 // Perform the quick checks that will tell us whether these
2468 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002469 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Douglas Gregora119f102008-12-19 19:13:09 +00002470 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2471 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2472 return false;
2473
2474 bool HasObjCConversion = false;
Alp Toker314cc812014-01-25 16:55:45 +00002475 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2476 Context.getCanonicalType(ToFunctionType->getReturnType())) {
Douglas Gregora119f102008-12-19 19:13:09 +00002477 // Okay, the types match exactly. Nothing to do.
Alp Toker314cc812014-01-25 16:55:45 +00002478 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2479 ToFunctionType->getReturnType(),
Douglas Gregora119f102008-12-19 19:13:09 +00002480 ConvertedType, IncompatibleObjC)) {
2481 // Okay, we have an Objective-C pointer conversion.
2482 HasObjCConversion = true;
2483 } else {
2484 // Function types are too different. Abort.
2485 return false;
2486 }
Mike Stump11289f42009-09-09 15:08:12 +00002487
Douglas Gregora119f102008-12-19 19:13:09 +00002488 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002489 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Douglas Gregora119f102008-12-19 19:13:09 +00002490 ArgIdx != NumArgs; ++ArgIdx) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002491 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2492 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Douglas Gregora119f102008-12-19 19:13:09 +00002493 if (Context.getCanonicalType(FromArgType)
2494 == Context.getCanonicalType(ToArgType)) {
2495 // Okay, the types match exactly. Nothing to do.
2496 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2497 ConvertedType, IncompatibleObjC)) {
2498 // Okay, we have an Objective-C pointer conversion.
2499 HasObjCConversion = true;
2500 } else {
2501 // Argument types are too different. Abort.
2502 return false;
2503 }
2504 }
2505
2506 if (HasObjCConversion) {
2507 // We had an Objective-C conversion. Allow this pointer
2508 // conversion, but complain about it.
Douglas Gregoraec25842011-04-26 23:16:46 +00002509 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002510 IncompatibleObjC = true;
2511 return true;
2512 }
2513 }
2514
Sebastian Redl72b597d2009-01-25 19:43:20 +00002515 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002516}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002517
John McCall31168b02011-06-15 23:02:42 +00002518/// \brief Determine whether this is an Objective-C writeback conversion,
2519/// used for parameter passing when performing automatic reference counting.
2520///
2521/// \param FromType The type we're converting form.
2522///
2523/// \param ToType The type we're converting to.
2524///
2525/// \param ConvertedType The type that will be produced after applying
2526/// this conversion.
2527bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2528 QualType &ConvertedType) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002529 if (!getLangOpts().ObjCAutoRefCount ||
John McCall31168b02011-06-15 23:02:42 +00002530 Context.hasSameUnqualifiedType(FromType, ToType))
2531 return false;
2532
2533 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2534 QualType ToPointee;
2535 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2536 ToPointee = ToPointer->getPointeeType();
2537 else
2538 return false;
2539
2540 Qualifiers ToQuals = ToPointee.getQualifiers();
2541 if (!ToPointee->isObjCLifetimeType() ||
2542 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall18ce25e2012-02-08 00:46:36 +00002543 !ToQuals.withoutObjCLifetime().empty())
John McCall31168b02011-06-15 23:02:42 +00002544 return false;
2545
2546 // Argument must be a pointer to __strong to __weak.
2547 QualType FromPointee;
2548 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2549 FromPointee = FromPointer->getPointeeType();
2550 else
2551 return false;
2552
2553 Qualifiers FromQuals = FromPointee.getQualifiers();
2554 if (!FromPointee->isObjCLifetimeType() ||
2555 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2556 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2557 return false;
2558
2559 // Make sure that we have compatible qualifiers.
2560 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2561 if (!ToQuals.compatiblyIncludes(FromQuals))
2562 return false;
2563
2564 // Remove qualifiers from the pointee type we're converting from; they
2565 // aren't used in the compatibility check belong, and we'll be adding back
2566 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2567 FromPointee = FromPointee.getUnqualifiedType();
2568
2569 // The unqualified form of the pointee types must be compatible.
2570 ToPointee = ToPointee.getUnqualifiedType();
2571 bool IncompatibleObjC;
2572 if (Context.typesAreCompatible(FromPointee, ToPointee))
2573 FromPointee = ToPointee;
2574 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2575 IncompatibleObjC))
2576 return false;
2577
2578 /// \brief Construct the type we're converting to, which is a pointer to
2579 /// __autoreleasing pointee.
2580 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2581 ConvertedType = Context.getPointerType(FromPointee);
2582 return true;
2583}
2584
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002585bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2586 QualType& ConvertedType) {
2587 QualType ToPointeeType;
2588 if (const BlockPointerType *ToBlockPtr =
2589 ToType->getAs<BlockPointerType>())
2590 ToPointeeType = ToBlockPtr->getPointeeType();
2591 else
2592 return false;
2593
2594 QualType FromPointeeType;
2595 if (const BlockPointerType *FromBlockPtr =
2596 FromType->getAs<BlockPointerType>())
2597 FromPointeeType = FromBlockPtr->getPointeeType();
2598 else
2599 return false;
2600 // We have pointer to blocks, check whether the only
2601 // differences in the argument and result types are in Objective-C
2602 // pointer conversions. If so, we permit the conversion.
2603
2604 const FunctionProtoType *FromFunctionType
2605 = FromPointeeType->getAs<FunctionProtoType>();
2606 const FunctionProtoType *ToFunctionType
2607 = ToPointeeType->getAs<FunctionProtoType>();
2608
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002609 if (!FromFunctionType || !ToFunctionType)
2610 return false;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002611
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002612 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002613 return true;
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002614
2615 // Perform the quick checks that will tell us whether these
2616 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002617 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002618 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2619 return false;
2620
2621 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2622 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2623 if (FromEInfo != ToEInfo)
2624 return false;
2625
2626 bool IncompatibleObjC = false;
Alp Toker314cc812014-01-25 16:55:45 +00002627 if (Context.hasSameType(FromFunctionType->getReturnType(),
2628 ToFunctionType->getReturnType())) {
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002629 // Okay, the types match exactly. Nothing to do.
2630 } else {
Alp Toker314cc812014-01-25 16:55:45 +00002631 QualType RHS = FromFunctionType->getReturnType();
2632 QualType LHS = ToFunctionType->getReturnType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002633 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002634 !RHS.hasQualifiers() && LHS.hasQualifiers())
2635 LHS = LHS.getUnqualifiedType();
2636
2637 if (Context.hasSameType(RHS,LHS)) {
2638 // OK exact match.
2639 } else if (isObjCPointerConversion(RHS, LHS,
2640 ConvertedType, IncompatibleObjC)) {
2641 if (IncompatibleObjC)
2642 return false;
2643 // Okay, we have an Objective-C pointer conversion.
2644 }
2645 else
2646 return false;
2647 }
2648
2649 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002650 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002651 ArgIdx != NumArgs; ++ArgIdx) {
2652 IncompatibleObjC = false;
Alp Toker9cacbab2014-01-20 20:26:09 +00002653 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2654 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002655 if (Context.hasSameType(FromArgType, ToArgType)) {
2656 // Okay, the types match exactly. Nothing to do.
2657 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2658 ConvertedType, IncompatibleObjC)) {
2659 if (IncompatibleObjC)
2660 return false;
2661 // Okay, we have an Objective-C pointer conversion.
2662 } else
2663 // Argument types are too different. Abort.
2664 return false;
2665 }
John McCall18afab72016-03-01 00:49:02 +00002666 if (!Context.doFunctionTypesMatchOnExtParameterInfos(FromFunctionType,
2667 ToFunctionType))
Fariborz Jahanian97676972011-09-28 21:52:05 +00002668 return false;
Fariborz Jahanian600ba202011-09-28 20:22:05 +00002669
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002670 ConvertedType = ToType;
2671 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002672}
2673
Richard Trieucaff2472011-11-23 22:32:32 +00002674enum {
2675 ft_default,
2676 ft_different_class,
2677 ft_parameter_arity,
2678 ft_parameter_mismatch,
2679 ft_return_type,
Richard Smith3c4f8d22016-10-16 17:54:23 +00002680 ft_qualifer_mismatch,
2681 ft_noexcept
Richard Trieucaff2472011-11-23 22:32:32 +00002682};
2683
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002684/// Attempts to get the FunctionProtoType from a Type. Handles
2685/// MemberFunctionPointers properly.
2686static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2687 if (auto *FPT = FromType->getAs<FunctionProtoType>())
2688 return FPT;
2689
2690 if (auto *MPT = FromType->getAs<MemberPointerType>())
2691 return MPT->getPointeeType()->getAs<FunctionProtoType>();
2692
2693 return nullptr;
2694}
2695
Richard Trieucaff2472011-11-23 22:32:32 +00002696/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2697/// function types. Catches different number of parameter, mismatch in
2698/// parameter types, and different return types.
2699void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2700 QualType FromType, QualType ToType) {
Richard Trieu96ed5b62011-12-13 23:19:45 +00002701 // If either type is not valid, include no extra info.
2702 if (FromType.isNull() || ToType.isNull()) {
2703 PDiag << ft_default;
2704 return;
2705 }
2706
Richard Trieucaff2472011-11-23 22:32:32 +00002707 // Get the function type from the pointers.
2708 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2709 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2710 *ToMember = ToType->getAs<MemberPointerType>();
Richard Trieu9098c9f2014-05-22 01:39:16 +00002711 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
Richard Trieucaff2472011-11-23 22:32:32 +00002712 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2713 << QualType(FromMember->getClass(), 0);
2714 return;
2715 }
2716 FromType = FromMember->getPointeeType();
2717 ToType = ToMember->getPointeeType();
Richard Trieucaff2472011-11-23 22:32:32 +00002718 }
2719
Richard Trieu96ed5b62011-12-13 23:19:45 +00002720 if (FromType->isPointerType())
2721 FromType = FromType->getPointeeType();
2722 if (ToType->isPointerType())
2723 ToType = ToType->getPointeeType();
2724
2725 // Remove references.
Richard Trieucaff2472011-11-23 22:32:32 +00002726 FromType = FromType.getNonReferenceType();
2727 ToType = ToType.getNonReferenceType();
2728
Richard Trieucaff2472011-11-23 22:32:32 +00002729 // Don't print extra info for non-specialized template functions.
2730 if (FromType->isInstantiationDependentType() &&
2731 !FromType->getAs<TemplateSpecializationType>()) {
2732 PDiag << ft_default;
2733 return;
2734 }
2735
Richard Trieu96ed5b62011-12-13 23:19:45 +00002736 // No extra info for same types.
2737 if (Context.hasSameType(FromType, ToType)) {
2738 PDiag << ft_default;
2739 return;
2740 }
2741
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002742 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2743 *ToFunction = tryGetFunctionProtoType(ToType);
Richard Trieucaff2472011-11-23 22:32:32 +00002744
2745 // Both types need to be function types.
2746 if (!FromFunction || !ToFunction) {
2747 PDiag << ft_default;
2748 return;
2749 }
2750
Alp Toker9cacbab2014-01-20 20:26:09 +00002751 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2752 PDiag << ft_parameter_arity << ToFunction->getNumParams()
2753 << FromFunction->getNumParams();
Richard Trieucaff2472011-11-23 22:32:32 +00002754 return;
2755 }
2756
2757 // Handle different parameter types.
2758 unsigned ArgPos;
Alp Toker9cacbab2014-01-20 20:26:09 +00002759 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
Richard Trieucaff2472011-11-23 22:32:32 +00002760 PDiag << ft_parameter_mismatch << ArgPos + 1
Alp Toker9cacbab2014-01-20 20:26:09 +00002761 << ToFunction->getParamType(ArgPos)
2762 << FromFunction->getParamType(ArgPos);
Richard Trieucaff2472011-11-23 22:32:32 +00002763 return;
2764 }
2765
2766 // Handle different return type.
Alp Toker314cc812014-01-25 16:55:45 +00002767 if (!Context.hasSameType(FromFunction->getReturnType(),
2768 ToFunction->getReturnType())) {
2769 PDiag << ft_return_type << ToFunction->getReturnType()
2770 << FromFunction->getReturnType();
Richard Trieucaff2472011-11-23 22:32:32 +00002771 return;
2772 }
2773
2774 unsigned FromQuals = FromFunction->getTypeQuals(),
2775 ToQuals = ToFunction->getTypeQuals();
2776 if (FromQuals != ToQuals) {
2777 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2778 return;
2779 }
2780
Richard Smith3c4f8d22016-10-16 17:54:23 +00002781 // Handle exception specification differences on canonical type (in C++17
2782 // onwards).
2783 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2784 ->isNothrow(Context) !=
2785 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2786 ->isNothrow(Context)) {
2787 PDiag << ft_noexcept;
2788 return;
2789 }
2790
Richard Trieucaff2472011-11-23 22:32:32 +00002791 // Unable to find a difference, so add no extra info.
2792 PDiag << ft_default;
2793}
2794
Alp Toker9cacbab2014-01-20 20:26:09 +00002795/// FunctionParamTypesAreEqual - This routine checks two function proto types
Douglas Gregor2039ca02011-12-15 17:15:07 +00002796/// for equality of their argument types. Caller has already checked that
Eli Friedman5f508952013-06-18 22:41:37 +00002797/// they have same number of arguments. If the parameters are different,
2798/// ArgPos will have the parameter index of the first different parameter.
Alp Toker9cacbab2014-01-20 20:26:09 +00002799bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2800 const FunctionProtoType *NewType,
2801 unsigned *ArgPos) {
2802 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2803 N = NewType->param_type_begin(),
2804 E = OldType->param_type_end();
2805 O && (O != E); ++O, ++N) {
Richard Trieu4b03d982013-08-09 21:42:32 +00002806 if (!Context.hasSameType(O->getUnqualifiedType(),
2807 N->getUnqualifiedType())) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002808 if (ArgPos)
2809 *ArgPos = O - OldType->param_type_begin();
Larisse Voufo4154f462013-08-06 03:57:41 +00002810 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002811 }
2812 }
2813 return true;
2814}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002815
Douglas Gregor39c16d42008-10-24 04:54:22 +00002816/// CheckPointerConversion - Check the pointer conversion from the
2817/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00002818/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00002819/// conversions for which IsPointerConversion has already returned
2820/// true. It returns true and produces a diagnostic if there was an
2821/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002822bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002823 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002824 CXXCastPath& BasePath,
George Burgess IV60bc9722016-01-13 23:36:34 +00002825 bool IgnoreBaseAccess,
2826 bool Diagnose) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002827 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00002828 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002829
John McCall8cb679e2010-11-15 09:13:47 +00002830 Kind = CK_BitCast;
2831
George Burgess IV60bc9722016-01-13 23:36:34 +00002832 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
Argyrios Kyrtzidis3e3305d2014-02-02 05:26:43 +00002833 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
George Burgess IV60bc9722016-01-13 23:36:34 +00002834 Expr::NPCK_ZeroExpression) {
David Blaikie1c7c8f72012-08-08 17:33:31 +00002835 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2836 DiagRuntimeBehavior(From->getExprLoc(), From,
2837 PDiag(diag::warn_impcast_bool_to_null_pointer)
2838 << ToType << From->getSourceRange());
2839 else if (!isUnevaluatedContext())
2840 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2841 << ToType << From->getSourceRange();
2842 }
John McCall9320b872011-09-09 05:25:32 +00002843 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2844 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002845 QualType FromPointeeType = FromPtrType->getPointeeType(),
2846 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00002847
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002848 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2849 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002850 // We must have a derived-to-base conversion. Check an
2851 // ambiguous or inaccessible conversion.
George Burgess IV60bc9722016-01-13 23:36:34 +00002852 unsigned InaccessibleID = 0;
2853 unsigned AmbigiousID = 0;
2854 if (Diagnose) {
2855 InaccessibleID = diag::err_upcast_to_inaccessible_base;
2856 AmbigiousID = diag::err_ambiguous_derived_to_base_conv;
2857 }
2858 if (CheckDerivedToBaseConversion(
2859 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID,
2860 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
2861 &BasePath, IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002862 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002863
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002864 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00002865 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002866 }
David Majnemer6bf02822015-10-31 08:42:14 +00002867
George Burgess IV60bc9722016-01-13 23:36:34 +00002868 if (Diagnose && !IsCStyleOrFunctionalCast &&
2869 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
David Majnemer6bf02822015-10-31 08:42:14 +00002870 assert(getLangOpts().MSVCCompat &&
2871 "this should only be possible with MSVCCompat!");
2872 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
2873 << From->getSourceRange();
2874 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00002875 }
John McCall9320b872011-09-09 05:25:32 +00002876 } else if (const ObjCObjectPointerType *ToPtrType =
2877 ToType->getAs<ObjCObjectPointerType>()) {
2878 if (const ObjCObjectPointerType *FromPtrType =
2879 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002880 // Objective-C++ conversions are always okay.
2881 // FIXME: We should have a different class of conversions for the
2882 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00002883 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002884 return false;
John McCall9320b872011-09-09 05:25:32 +00002885 } else if (FromType->isBlockPointerType()) {
2886 Kind = CK_BlockPointerToObjCPointerCast;
2887 } else {
2888 Kind = CK_CPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00002889 }
John McCall9320b872011-09-09 05:25:32 +00002890 } else if (ToType->isBlockPointerType()) {
2891 if (!FromType->isBlockPointerType())
2892 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002893 }
John McCall8cb679e2010-11-15 09:13:47 +00002894
2895 // We shouldn't fall into this case unless it's valid for other
2896 // reasons.
2897 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2898 Kind = CK_NullToPointer;
2899
Douglas Gregor39c16d42008-10-24 04:54:22 +00002900 return false;
2901}
2902
Sebastian Redl72b597d2009-01-25 19:43:20 +00002903/// IsMemberPointerConversion - Determines whether the conversion of the
2904/// expression From, which has the (possibly adjusted) type FromType, can be
2905/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2906/// If so, returns true and places the converted type (that might differ from
2907/// ToType in its cv-qualifiers at some level) into ConvertedType.
2908bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002909 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00002910 bool InOverloadResolution,
2911 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002912 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002913 if (!ToTypePtr)
2914 return false;
2915
2916 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00002917 if (From->isNullPointerConstant(Context,
2918 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2919 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002920 ConvertedType = ToType;
2921 return true;
2922 }
2923
2924 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002925 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002926 if (!FromTypePtr)
2927 return false;
2928
2929 // A pointer to member of B can be converted to a pointer to member of D,
2930 // where D is derived from B (C++ 4.11p2).
2931 QualType FromClass(FromTypePtr->getClass(), 0);
2932 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002933
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002934 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00002935 IsDerivedFrom(From->getLocStart(), ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002936 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2937 ToClass.getTypePtr());
2938 return true;
2939 }
2940
2941 return false;
2942}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002943
Sebastian Redl72b597d2009-01-25 19:43:20 +00002944/// CheckMemberPointerConversion - Check the member pointer conversion from the
2945/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002946/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002947/// for which IsMemberPointerConversion has already returned true. It returns
2948/// true and produces a diagnostic if there was an error, or returns false
2949/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002950bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002951 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002952 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002953 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002954 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002955 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00002956 if (!FromPtrType) {
2957 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002958 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00002959 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00002960 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00002961 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00002962 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00002963 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00002964
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002965 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00002966 assert(ToPtrType && "No member pointer cast has a target type "
2967 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002968
Sebastian Redled8f2002009-01-28 18:33:18 +00002969 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2970 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002971
Sebastian Redled8f2002009-01-28 18:33:18 +00002972 // FIXME: What about dependent types?
2973 assert(FromClass->isRecordType() && "Pointer into non-class.");
2974 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002975
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002976 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002977 /*DetectVirtual=*/true);
Richard Smith0f59cb32015-12-18 21:45:41 +00002978 bool DerivationOkay =
2979 IsDerivedFrom(From->getLocStart(), ToClass, FromClass, Paths);
Sebastian Redled8f2002009-01-28 18:33:18 +00002980 assert(DerivationOkay &&
2981 "Should not have been called if derivation isn't OK.");
2982 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002983
Sebastian Redled8f2002009-01-28 18:33:18 +00002984 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2985 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002986 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2987 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2988 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2989 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002990 }
Sebastian Redled8f2002009-01-28 18:33:18 +00002991
Douglas Gregor89ee6822009-02-28 01:32:25 +00002992 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002993 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2994 << FromClass << ToClass << QualType(VBase, 0)
2995 << From->getSourceRange();
2996 return true;
2997 }
2998
John McCall5b0829a2010-02-10 09:31:12 +00002999 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00003000 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3001 Paths.front(),
3002 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00003003
Anders Carlssond7923c62009-08-22 23:33:40 +00003004 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00003005 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00003006 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00003007 return false;
3008}
3009
Douglas Gregorc9f019a2013-11-08 02:04:24 +00003010/// Determine whether the lifetime conversion between the two given
3011/// qualifiers sets is nontrivial.
3012static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3013 Qualifiers ToQuals) {
3014 // Converting anything to const __unsafe_unretained is trivial.
3015 if (ToQuals.hasConst() &&
3016 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3017 return false;
3018
3019 return true;
3020}
3021
Douglas Gregor9a657932008-10-21 23:43:52 +00003022/// IsQualificationConversion - Determines whether the conversion from
3023/// an rvalue of type FromType to ToType is a qualification conversion
3024/// (C++ 4.4).
John McCall31168b02011-06-15 23:02:42 +00003025///
3026/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3027/// when the qualification conversion involves a change in the Objective-C
3028/// object lifetime.
Mike Stump11289f42009-09-09 15:08:12 +00003029bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003030Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00003031 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor9a657932008-10-21 23:43:52 +00003032 FromType = Context.getCanonicalType(FromType);
3033 ToType = Context.getCanonicalType(ToType);
John McCall31168b02011-06-15 23:02:42 +00003034 ObjCLifetimeConversion = false;
3035
Douglas Gregor9a657932008-10-21 23:43:52 +00003036 // If FromType and ToType are the same type, this is not a
3037 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00003038 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00003039 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00003040
Douglas Gregor9a657932008-10-21 23:43:52 +00003041 // (C++ 4.4p4):
3042 // A conversion can add cv-qualifiers at levels other than the first
3043 // in multi-level pointers, subject to the following rules: [...]
3044 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00003045 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003046 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00003047 // Within each iteration of the loop, we check the qualifiers to
3048 // determine if this still looks like a qualification
3049 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003050 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00003051 // until there are no more pointers or pointers-to-members left to
3052 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003053 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00003054
Douglas Gregor90609aa2011-04-25 18:40:17 +00003055 Qualifiers FromQuals = FromType.getQualifiers();
3056 Qualifiers ToQuals = ToType.getQualifiers();
Andrey Bokhanko45d41322016-05-11 18:38:21 +00003057
3058 // Ignore __unaligned qualifier if this type is void.
3059 if (ToType.getUnqualifiedType()->isVoidType())
3060 FromQuals.removeUnaligned();
Douglas Gregor90609aa2011-04-25 18:40:17 +00003061
John McCall31168b02011-06-15 23:02:42 +00003062 // Objective-C ARC:
3063 // Check Objective-C lifetime conversions.
3064 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
3065 UnwrappedAnyPointer) {
3066 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00003067 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3068 ObjCLifetimeConversion = true;
John McCall31168b02011-06-15 23:02:42 +00003069 FromQuals.removeObjCLifetime();
3070 ToQuals.removeObjCLifetime();
3071 } else {
3072 // Qualification conversions cannot cast between different
3073 // Objective-C lifetime qualifiers.
3074 return false;
3075 }
3076 }
3077
Douglas Gregorf30053d2011-05-08 06:09:53 +00003078 // Allow addition/removal of GC attributes but not changing GC attributes.
3079 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3080 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3081 FromQuals.removeObjCGCAttr();
3082 ToQuals.removeObjCGCAttr();
3083 }
3084
Douglas Gregor9a657932008-10-21 23:43:52 +00003085 // -- for every j > 0, if const is in cv 1,j then const is in cv
3086 // 2,j, and similarly for volatile.
Douglas Gregor90609aa2011-04-25 18:40:17 +00003087 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor9a657932008-10-21 23:43:52 +00003088 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003089
Douglas Gregor9a657932008-10-21 23:43:52 +00003090 // -- if the cv 1,j and cv 2,j are different, then const is in
3091 // every cv for 0 < k < j.
Douglas Gregor90609aa2011-04-25 18:40:17 +00003092 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003093 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00003094 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003095
Douglas Gregor9a657932008-10-21 23:43:52 +00003096 // Keep track of whether all prior cv-qualifiers in the "to" type
3097 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00003098 PreviousToQualsIncludeConst
Douglas Gregor90609aa2011-04-25 18:40:17 +00003099 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003100 }
Douglas Gregor9a657932008-10-21 23:43:52 +00003101
3102 // We are left with FromType and ToType being the pointee types
3103 // after unwrapping the original FromType and ToType the same number
3104 // of types. If we unwrapped any pointers, and if FromType and
3105 // ToType have the same unqualified type (since we checked
3106 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003107 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00003108}
3109
Douglas Gregorc79862f2012-04-12 17:51:55 +00003110/// \brief - Determine whether this is a conversion from a scalar type to an
3111/// atomic type.
3112///
3113/// If successful, updates \c SCS's second and third steps in the conversion
3114/// sequence to finish the conversion.
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00003115static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3116 bool InOverloadResolution,
3117 StandardConversionSequence &SCS,
3118 bool CStyle) {
Douglas Gregorc79862f2012-04-12 17:51:55 +00003119 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3120 if (!ToAtomic)
3121 return false;
3122
3123 StandardConversionSequence InnerSCS;
3124 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3125 InOverloadResolution, InnerSCS,
3126 CStyle, /*AllowObjCWritebackConversion=*/false))
3127 return false;
3128
3129 SCS.Second = InnerSCS.Second;
3130 SCS.setToType(1, InnerSCS.getToType(1));
3131 SCS.Third = InnerSCS.Third;
3132 SCS.QualificationIncludesObjCLifetime
3133 = InnerSCS.QualificationIncludesObjCLifetime;
3134 SCS.setToType(2, InnerSCS.getToType(2));
3135 return true;
3136}
3137
Sebastian Redle5417162012-03-27 18:33:03 +00003138static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3139 CXXConstructorDecl *Constructor,
3140 QualType Type) {
3141 const FunctionProtoType *CtorType =
3142 Constructor->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00003143 if (CtorType->getNumParams() > 0) {
3144 QualType FirstArg = CtorType->getParamType(0);
Sebastian Redle5417162012-03-27 18:33:03 +00003145 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3146 return true;
3147 }
3148 return false;
3149}
3150
Sebastian Redl82ace982012-02-11 23:51:08 +00003151static OverloadingResult
3152IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3153 CXXRecordDecl *To,
3154 UserDefinedConversionSequence &User,
3155 OverloadCandidateSet &CandidateSet,
3156 bool AllowExplicit) {
Richard Smithc2bebe92016-05-11 20:37:46 +00003157 for (auto *D : S.LookupConstructors(To)) {
3158 auto Info = getConstructorInfo(D);
Richard Smith5179eb72016-06-28 19:03:57 +00003159 if (!Info)
Richard Smithc2bebe92016-05-11 20:37:46 +00003160 continue;
Sebastian Redl82ace982012-02-11 23:51:08 +00003161
Richard Smithc2bebe92016-05-11 20:37:46 +00003162 bool Usable = !Info.Constructor->isInvalidDecl() &&
3163 S.isInitListConstructor(Info.Constructor) &&
3164 (AllowExplicit || !Info.Constructor->isExplicit());
Sebastian Redl82ace982012-02-11 23:51:08 +00003165 if (Usable) {
Sebastian Redle5417162012-03-27 18:33:03 +00003166 // If the first argument is (a reference to) the target type,
3167 // suppress conversions.
Richard Smithc2bebe92016-05-11 20:37:46 +00003168 bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3169 S.Context, Info.Constructor, ToType);
3170 if (Info.ConstructorTmpl)
3171 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3172 /*ExplicitArgs*/ nullptr, From,
3173 CandidateSet, SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00003174 else
Richard Smithc2bebe92016-05-11 20:37:46 +00003175 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3176 CandidateSet, SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00003177 }
3178 }
3179
3180 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3181
3182 OverloadCandidateSet::iterator Best;
Fariborz Jahaniandcf06f42015-04-14 17:21:58 +00003183 switch (auto Result =
3184 CandidateSet.BestViableFunction(S, From->getLocStart(),
3185 Best, true)) {
3186 case OR_Deleted:
Sebastian Redl82ace982012-02-11 23:51:08 +00003187 case OR_Success: {
3188 // Record the standard conversion we used and the conversion function.
3189 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Sebastian Redl82ace982012-02-11 23:51:08 +00003190 QualType ThisType = Constructor->getThisType(S.Context);
3191 // Initializer lists don't have conversions as such.
3192 User.Before.setAsIdentityConversion();
3193 User.HadMultipleCandidates = HadMultipleCandidates;
3194 User.ConversionFunction = Constructor;
3195 User.FoundConversionFunction = Best->FoundDecl;
3196 User.After.setAsIdentityConversion();
3197 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3198 User.After.setAllToTypes(ToType);
Fariborz Jahaniandcf06f42015-04-14 17:21:58 +00003199 return Result;
Sebastian Redl82ace982012-02-11 23:51:08 +00003200 }
3201
3202 case OR_No_Viable_Function:
3203 return OR_No_Viable_Function;
Sebastian Redl82ace982012-02-11 23:51:08 +00003204 case OR_Ambiguous:
3205 return OR_Ambiguous;
3206 }
3207
3208 llvm_unreachable("Invalid OverloadResult!");
3209}
3210
Douglas Gregor576e98c2009-01-30 23:27:23 +00003211/// Determines whether there is a user-defined conversion sequence
3212/// (C++ [over.ics.user]) that converts expression From to the type
3213/// ToType. If such a conversion exists, User will contain the
3214/// user-defined conversion sequence that performs such a conversion
3215/// and this routine will return true. Otherwise, this routine returns
3216/// false and User is unspecified.
3217///
Douglas Gregor576e98c2009-01-30 23:27:23 +00003218/// \param AllowExplicit true if the conversion should consider C++0x
3219/// "explicit" conversion functions as well as non-explicit conversion
3220/// functions (C++0x [class.conv.fct]p2).
Douglas Gregor4b60a152013-11-07 22:34:54 +00003221///
3222/// \param AllowObjCConversionOnExplicit true if the conversion should
3223/// allow an extra Objective-C pointer conversion on uses of explicit
3224/// constructors. Requires \c AllowExplicit to also be set.
John McCall5c32be02010-08-24 20:38:10 +00003225static OverloadingResult
3226IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl82ace982012-02-11 23:51:08 +00003227 UserDefinedConversionSequence &User,
3228 OverloadCandidateSet &CandidateSet,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003229 bool AllowExplicit,
3230 bool AllowObjCConversionOnExplicit) {
Douglas Gregor2ee1d992013-11-08 01:20:25 +00003231 assert(AllowExplicit || !AllowObjCConversionOnExplicit);
Douglas Gregor4b60a152013-11-07 22:34:54 +00003232
Douglas Gregor5ab11652010-04-17 22:01:05 +00003233 // Whether we will only visit constructors.
3234 bool ConstructorsOnly = false;
3235
3236 // If the type we are conversion to is a class type, enumerate its
3237 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003238 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00003239 // C++ [over.match.ctor]p1:
3240 // When objects of class type are direct-initialized (8.5), or
3241 // copy-initialized from an expression of the same or a
3242 // derived class type (8.5), overload resolution selects the
3243 // constructor. [...] For copy-initialization, the candidate
3244 // functions are all the converting constructors (12.3.1) of
3245 // that class. The argument list is the expression-list within
3246 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00003247 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00003248 (From->getType()->getAs<RecordType>() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00003249 S.IsDerivedFrom(From->getLocStart(), From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00003250 ConstructorsOnly = true;
3251
Richard Smithdb0ac552015-12-18 22:40:25 +00003252 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003253 // We're not going to find any constructors.
3254 } else if (CXXRecordDecl *ToRecordDecl
3255 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003256
3257 Expr **Args = &From;
3258 unsigned NumArgs = 1;
3259 bool ListInitializing = false;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003260 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003261 // But first, see if there is an init-list-constructor that will work.
Sebastian Redl82ace982012-02-11 23:51:08 +00003262 OverloadingResult Result = IsInitializerListConstructorConversion(
3263 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3264 if (Result != OR_No_Viable_Function)
3265 return Result;
3266 // Never mind.
3267 CandidateSet.clear();
3268
3269 // If we're list-initializing, we pass the individual elements as
3270 // arguments, not the entire list.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003271 Args = InitList->getInits();
3272 NumArgs = InitList->getNumInits();
3273 ListInitializing = true;
3274 }
3275
Richard Smithc2bebe92016-05-11 20:37:46 +00003276 for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3277 auto Info = getConstructorInfo(D);
Richard Smith5179eb72016-06-28 19:03:57 +00003278 if (!Info)
Richard Smithc2bebe92016-05-11 20:37:46 +00003279 continue;
John McCalla0296f72010-03-19 07:35:19 +00003280
Richard Smithc2bebe92016-05-11 20:37:46 +00003281 bool Usable = !Info.Constructor->isInvalidDecl();
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003282 if (ListInitializing)
Richard Smithc2bebe92016-05-11 20:37:46 +00003283 Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit());
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003284 else
Richard Smithc2bebe92016-05-11 20:37:46 +00003285 Usable = Usable &&
3286 Info.Constructor->isConvertingConstructor(AllowExplicit);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003287 if (Usable) {
Sebastian Redld9170b02012-03-20 21:24:14 +00003288 bool SuppressUserConversions = !ConstructorsOnly;
3289 if (SuppressUserConversions && ListInitializing) {
3290 SuppressUserConversions = false;
3291 if (NumArgs == 1) {
3292 // If the first argument is (a reference to) the target type,
3293 // suppress conversions.
Sebastian Redle5417162012-03-27 18:33:03 +00003294 SuppressUserConversions = isFirstArgumentCompatibleWithType(
Richard Smithc2bebe92016-05-11 20:37:46 +00003295 S.Context, Info.Constructor, ToType);
Sebastian Redld9170b02012-03-20 21:24:14 +00003296 }
3297 }
Richard Smithc2bebe92016-05-11 20:37:46 +00003298 if (Info.ConstructorTmpl)
3299 S.AddTemplateOverloadCandidate(
3300 Info.ConstructorTmpl, Info.FoundDecl,
3301 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3302 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003303 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00003304 // Allow one user-defined conversion when user specifies a
3305 // From->ToType conversion via an static cast (c-style, etc).
Richard Smithc2bebe92016-05-11 20:37:46 +00003306 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003307 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003308 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003309 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00003310 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003311 }
3312 }
3313
Douglas Gregor5ab11652010-04-17 22:01:05 +00003314 // Enumerate conversion functions, if we're allowed to.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003315 if (ConstructorsOnly || isa<InitListExpr>(From)) {
Richard Smithdb0ac552015-12-18 22:40:25 +00003316 } else if (!S.isCompleteType(From->getLocStart(), From->getType())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003317 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00003318 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00003319 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00003320 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003321 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3322 // Add all of the conversion functions as candidates.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00003323 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3324 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00003325 DeclAccessPair FoundDecl = I.getPair();
3326 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003327 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3328 if (isa<UsingShadowDecl>(D))
3329 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3330
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003331 CXXConversionDecl *Conv;
3332 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00003333 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3334 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003335 else
John McCallda4458e2010-03-31 01:36:47 +00003336 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003337
3338 if (AllowExplicit || !Conv->isExplicit()) {
3339 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00003340 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3341 ActingContext, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003342 CandidateSet,
3343 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003344 else
John McCall5c32be02010-08-24 20:38:10 +00003345 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003346 From, ToType, CandidateSet,
3347 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003348 }
3349 }
3350 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00003351 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003352
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003353 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3354
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003355 OverloadCandidateSet::iterator Best;
Richard Smith48372b62015-01-27 03:30:40 +00003356 switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(),
3357 Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00003358 case OR_Success:
Richard Smith48372b62015-01-27 03:30:40 +00003359 case OR_Deleted:
John McCall5c32be02010-08-24 20:38:10 +00003360 // Record the standard conversion we used and the conversion function.
3361 if (CXXConstructorDecl *Constructor
3362 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3363 // C++ [over.ics.user]p1:
3364 // If the user-defined conversion is specified by a
3365 // constructor (12.3.1), the initial standard conversion
3366 // sequence converts the source type to the type required by
3367 // the argument of the constructor.
3368 //
3369 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003370 if (isa<InitListExpr>(From)) {
3371 // Initializer lists don't have conversions as such.
3372 User.Before.setAsIdentityConversion();
3373 } else {
3374 if (Best->Conversions[0].isEllipsis())
3375 User.EllipsisConversion = true;
3376 else {
3377 User.Before = Best->Conversions[0].Standard;
3378 User.EllipsisConversion = false;
3379 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003380 }
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003381 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003382 User.ConversionFunction = Constructor;
John McCall30909032011-09-21 08:36:56 +00003383 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003384 User.After.setAsIdentityConversion();
3385 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3386 User.After.setAllToTypes(ToType);
Richard Smith48372b62015-01-27 03:30:40 +00003387 return Result;
David Blaikie8a40f702012-01-17 06:56:22 +00003388 }
3389 if (CXXConversionDecl *Conversion
John McCall5c32be02010-08-24 20:38:10 +00003390 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3391 // C++ [over.ics.user]p1:
3392 //
3393 // [...] If the user-defined conversion is specified by a
3394 // conversion function (12.3.2), the initial standard
3395 // conversion sequence converts the source type to the
3396 // implicit object parameter of the conversion function.
3397 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003398 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003399 User.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00003400 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003401 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00003402
John McCall5c32be02010-08-24 20:38:10 +00003403 // C++ [over.ics.user]p2:
3404 // The second standard conversion sequence converts the
3405 // result of the user-defined conversion to the target type
3406 // for the sequence. Since an implicit conversion sequence
3407 // is an initialization, the special rules for
3408 // initialization by user-defined conversion apply when
3409 // selecting the best user-defined conversion for a
3410 // user-defined conversion sequence (see 13.3.3 and
3411 // 13.3.3.1).
3412 User.After = Best->FinalConversion;
Richard Smith48372b62015-01-27 03:30:40 +00003413 return Result;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003414 }
David Blaikie8a40f702012-01-17 06:56:22 +00003415 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003416
John McCall5c32be02010-08-24 20:38:10 +00003417 case OR_No_Viable_Function:
3418 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003419
John McCall5c32be02010-08-24 20:38:10 +00003420 case OR_Ambiguous:
3421 return OR_Ambiguous;
3422 }
3423
David Blaikie8a40f702012-01-17 06:56:22 +00003424 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003425}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003426
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003427bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00003428Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003429 ImplicitConversionSequence ICS;
Richard Smith100b24a2014-04-17 01:52:14 +00003430 OverloadCandidateSet CandidateSet(From->getExprLoc(),
3431 OverloadCandidateSet::CSK_Normal);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003432 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00003433 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003434 CandidateSet, false, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00003435 if (OvResult == OR_Ambiguous)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003436 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3437 << From->getType() << ToType << From->getSourceRange();
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003438 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
Larisse Voufo70bb43a2013-06-27 03:36:30 +00003439 if (!RequireCompleteType(From->getLocStart(), ToType,
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003440 diag::err_typecheck_nonviable_condition_incomplete,
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003441 From->getType(), From->getSourceRange()))
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003442 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
Nick Lewycky08426e22015-08-25 22:18:46 +00003443 << false << From->getType() << From->getSourceRange() << ToType;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003444 } else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003445 return false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003446 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003447 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003448}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003449
Douglas Gregor2837aa22012-02-22 17:32:19 +00003450/// \brief Compare the user-defined conversion functions or constructors
3451/// of two user-defined conversion sequences to determine whether any ordering
3452/// is possible.
3453static ImplicitConversionSequence::CompareKind
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003454compareConversionFunctions(Sema &S, FunctionDecl *Function1,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003455 FunctionDecl *Function2) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003456 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
Douglas Gregor2837aa22012-02-22 17:32:19 +00003457 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003458
Douglas Gregor2837aa22012-02-22 17:32:19 +00003459 // Objective-C++:
3460 // If both conversion functions are implicitly-declared conversions from
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003461 // a lambda closure type to a function pointer and a block pointer,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003462 // respectively, always prefer the conversion to a function pointer,
3463 // because the function pointer is more lightweight and is more likely
3464 // to keep code working.
Ted Kremenek8d265c22014-04-01 07:23:18 +00003465 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003466 if (!Conv1)
3467 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003468
Douglas Gregor2837aa22012-02-22 17:32:19 +00003469 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3470 if (!Conv2)
3471 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003472
Douglas Gregor2837aa22012-02-22 17:32:19 +00003473 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3474 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3475 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3476 if (Block1 != Block2)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003477 return Block1 ? ImplicitConversionSequence::Worse
3478 : ImplicitConversionSequence::Better;
Douglas Gregor2837aa22012-02-22 17:32:19 +00003479 }
3480
3481 return ImplicitConversionSequence::Indistinguishable;
3482}
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003483
3484static bool hasDeprecatedStringLiteralToCharPtrConversion(
3485 const ImplicitConversionSequence &ICS) {
3486 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3487 (ICS.isUserDefined() &&
3488 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3489}
3490
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003491/// CompareImplicitConversionSequences - Compare two implicit
3492/// conversion sequences to determine whether one is better than the
3493/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00003494static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +00003495CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +00003496 const ImplicitConversionSequence& ICS1,
3497 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003498{
3499 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3500 // conversion sequences (as defined in 13.3.3.1)
3501 // -- a standard conversion sequence (13.3.3.1.1) is a better
3502 // conversion sequence than a user-defined conversion sequence or
3503 // an ellipsis conversion sequence, and
3504 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3505 // conversion sequence than an ellipsis conversion sequence
3506 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00003507 //
John McCall0d1da222010-01-12 00:44:57 +00003508 // C++0x [over.best.ics]p10:
3509 // For the purpose of ranking implicit conversion sequences as
3510 // described in 13.3.3.2, the ambiguous conversion sequence is
3511 // treated as a user-defined sequence that is indistinguishable
3512 // from any other user-defined conversion sequence.
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003513
3514 // String literal to 'char *' conversion has been deprecated in C++03. It has
3515 // been removed from C++11. We still accept this conversion, if it happens at
3516 // the best viable function. Otherwise, this conversion is considered worse
3517 // than ellipsis conversion. Consider this as an extension; this is not in the
3518 // standard. For example:
3519 //
3520 // int &f(...); // #1
3521 // void f(char*); // #2
3522 // void g() { int &r = f("foo"); }
3523 //
3524 // In C++03, we pick #2 as the best viable function.
3525 // In C++11, we pick #1 as the best viable function, because ellipsis
3526 // conversion is better than string-literal to char* conversion (since there
3527 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3528 // convert arguments, #2 would be the best viable function in C++11.
3529 // If the best viable function has this conversion, a warning will be issued
3530 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3531
3532 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3533 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3534 hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3535 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3536 ? ImplicitConversionSequence::Worse
3537 : ImplicitConversionSequence::Better;
3538
Douglas Gregor5ab11652010-04-17 22:01:05 +00003539 if (ICS1.getKindRank() < ICS2.getKindRank())
3540 return ImplicitConversionSequence::Better;
David Blaikie8a40f702012-01-17 06:56:22 +00003541 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor5ab11652010-04-17 22:01:05 +00003542 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003543
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00003544 // The following checks require both conversion sequences to be of
3545 // the same kind.
3546 if (ICS1.getKind() != ICS2.getKind())
3547 return ImplicitConversionSequence::Indistinguishable;
3548
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003549 ImplicitConversionSequence::CompareKind Result =
3550 ImplicitConversionSequence::Indistinguishable;
3551
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003552 // Two implicit conversion sequences of the same form are
3553 // indistinguishable conversion sequences unless one of the
3554 // following rules apply: (C++ 13.3.3.2p3):
Larisse Voufo19d08672015-01-27 18:47:05 +00003555
3556 // List-initialization sequence L1 is a better conversion sequence than
3557 // list-initialization sequence L2 if:
3558 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3559 // if not that,
NAKAMURA Takumib01d86b2015-02-25 11:02:00 +00003560 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
Larisse Voufo19d08672015-01-27 18:47:05 +00003561 // and N1 is smaller than N2.,
3562 // even if one of the other rules in this paragraph would otherwise apply.
3563 if (!ICS1.isBad()) {
3564 if (ICS1.isStdInitializerListElement() &&
3565 !ICS2.isStdInitializerListElement())
3566 return ImplicitConversionSequence::Better;
3567 if (!ICS1.isStdInitializerListElement() &&
3568 ICS2.isStdInitializerListElement())
3569 return ImplicitConversionSequence::Worse;
3570 }
3571
John McCall0d1da222010-01-12 00:44:57 +00003572 if (ICS1.isStandard())
Larisse Voufo19d08672015-01-27 18:47:05 +00003573 // Standard conversion sequence S1 is a better conversion sequence than
3574 // standard conversion sequence S2 if [...]
Richard Smith0f59cb32015-12-18 21:45:41 +00003575 Result = CompareStandardConversionSequences(S, Loc,
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003576 ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00003577 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003578 // User-defined conversion sequence U1 is a better conversion
3579 // sequence than another user-defined conversion sequence U2 if
3580 // they contain the same user-defined conversion function or
3581 // constructor and if the second standard conversion sequence of
3582 // U1 is better than the second standard conversion sequence of
3583 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00003584 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003585 ICS2.UserDefined.ConversionFunction)
Richard Smith0f59cb32015-12-18 21:45:41 +00003586 Result = CompareStandardConversionSequences(S, Loc,
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003587 ICS1.UserDefined.After,
3588 ICS2.UserDefined.After);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003589 else
3590 Result = compareConversionFunctions(S,
3591 ICS1.UserDefined.ConversionFunction,
3592 ICS2.UserDefined.ConversionFunction);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003593 }
3594
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003595 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003596}
3597
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003598static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3599 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3600 Qualifiers Quals;
3601 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003602 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003603 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003604
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003605 return Context.hasSameUnqualifiedType(T1, T2);
3606}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003607
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003608// Per 13.3.3.2p3, compare the given standard conversion sequences to
3609// determine if one is a proper subset of the other.
3610static ImplicitConversionSequence::CompareKind
3611compareStandardConversionSubsets(ASTContext &Context,
3612 const StandardConversionSequence& SCS1,
3613 const StandardConversionSequence& SCS2) {
3614 ImplicitConversionSequence::CompareKind Result
3615 = ImplicitConversionSequence::Indistinguishable;
3616
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003617 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00003618 // any non-identity conversion sequence
Douglas Gregor377c1092011-06-05 06:15:20 +00003619 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3620 return ImplicitConversionSequence::Better;
3621 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3622 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003623
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003624 if (SCS1.Second != SCS2.Second) {
3625 if (SCS1.Second == ICK_Identity)
3626 Result = ImplicitConversionSequence::Better;
3627 else if (SCS2.Second == ICK_Identity)
3628 Result = ImplicitConversionSequence::Worse;
3629 else
3630 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003631 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003632 return ImplicitConversionSequence::Indistinguishable;
3633
3634 if (SCS1.Third == SCS2.Third) {
3635 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3636 : ImplicitConversionSequence::Indistinguishable;
3637 }
3638
3639 if (SCS1.Third == ICK_Identity)
3640 return Result == ImplicitConversionSequence::Worse
3641 ? ImplicitConversionSequence::Indistinguishable
3642 : ImplicitConversionSequence::Better;
3643
3644 if (SCS2.Third == ICK_Identity)
3645 return Result == ImplicitConversionSequence::Better
3646 ? ImplicitConversionSequence::Indistinguishable
3647 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003648
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003649 return ImplicitConversionSequence::Indistinguishable;
3650}
3651
Douglas Gregore696ebb2011-01-26 14:52:12 +00003652/// \brief Determine whether one of the given reference bindings is better
3653/// than the other based on what kind of bindings they are.
Richard Smith19172c42014-07-14 02:28:44 +00003654static bool
3655isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3656 const StandardConversionSequence &SCS2) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003657 // C++0x [over.ics.rank]p3b4:
3658 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3659 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003660 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00003661 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003662 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00003663 // reference*.
3664 //
3665 // FIXME: Rvalue references. We're going rogue with the above edits,
3666 // because the semantics in the current C++0x working paper (N3225 at the
3667 // time of this writing) break the standard definition of std::forward
3668 // and std::reference_wrapper when dealing with references to functions.
3669 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00003670 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3671 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3672 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003673
Douglas Gregore696ebb2011-01-26 14:52:12 +00003674 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3675 SCS2.IsLvalueReference) ||
3676 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
Richard Smith19172c42014-07-14 02:28:44 +00003677 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
Douglas Gregore696ebb2011-01-26 14:52:12 +00003678}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003679
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003680/// CompareStandardConversionSequences - Compare two standard
3681/// conversion sequences to determine whether one is better than the
3682/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00003683static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +00003684CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +00003685 const StandardConversionSequence& SCS1,
3686 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003687{
3688 // Standard conversion sequence S1 is a better conversion sequence
3689 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3690
3691 // -- S1 is a proper subsequence of S2 (comparing the conversion
3692 // sequences in the canonical form defined by 13.3.3.1.1,
3693 // excluding any Lvalue Transformation; the identity conversion
3694 // sequence is considered to be a subsequence of any
3695 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003696 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00003697 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003698 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003699
3700 // -- the rank of S1 is better than the rank of S2 (by the rules
3701 // defined below), or, if not that,
3702 ImplicitConversionRank Rank1 = SCS1.getRank();
3703 ImplicitConversionRank Rank2 = SCS2.getRank();
3704 if (Rank1 < Rank2)
3705 return ImplicitConversionSequence::Better;
3706 else if (Rank2 < Rank1)
3707 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003708
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003709 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3710 // are indistinguishable unless one of the following rules
3711 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00003712
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003713 // A conversion that is not a conversion of a pointer, or
3714 // pointer to member, to bool is better than another conversion
3715 // that is such a conversion.
3716 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3717 return SCS2.isPointerConversionToBool()
3718 ? ImplicitConversionSequence::Better
3719 : ImplicitConversionSequence::Worse;
3720
Douglas Gregor5c407d92008-10-23 00:40:37 +00003721 // C++ [over.ics.rank]p4b2:
3722 //
3723 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003724 // conversion of B* to A* is better than conversion of B* to
3725 // void*, and conversion of A* to void* is better than conversion
3726 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00003727 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003728 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00003729 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003730 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003731 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3732 // Exactly one of the conversion sequences is a conversion to
3733 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003734 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3735 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003736 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3737 // Neither conversion sequence converts to a void pointer; compare
3738 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003739 if (ImplicitConversionSequence::CompareKind DerivedCK
Richard Smith0f59cb32015-12-18 21:45:41 +00003740 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003741 return DerivedCK;
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003742 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3743 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003744 // Both conversion sequences are conversions to void
3745 // pointers. Compare the source types to determine if there's an
3746 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00003747 QualType FromType1 = SCS1.getFromType();
3748 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003749
3750 // Adjust the types we're converting from via the array-to-pointer
3751 // conversion, if we need to.
3752 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003753 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003754 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003755 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003756
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003757 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3758 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003759
Richard Smith0f59cb32015-12-18 21:45:41 +00003760 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003761 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00003762 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003763 return ImplicitConversionSequence::Worse;
3764
3765 // Objective-C++: If one interface is more specific than the
3766 // other, it is the better one.
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003767 const ObjCObjectPointerType* FromObjCPtr1
3768 = FromType1->getAs<ObjCObjectPointerType>();
3769 const ObjCObjectPointerType* FromObjCPtr2
3770 = FromType2->getAs<ObjCObjectPointerType>();
3771 if (FromObjCPtr1 && FromObjCPtr2) {
3772 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3773 FromObjCPtr2);
3774 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3775 FromObjCPtr1);
3776 if (AssignLeft != AssignRight) {
3777 return AssignLeft? ImplicitConversionSequence::Better
3778 : ImplicitConversionSequence::Worse;
3779 }
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003780 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003781 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003782
3783 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3784 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00003785 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00003786 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003787 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003788
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003789 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003790 // Check for a better reference binding based on the kind of bindings.
3791 if (isBetterReferenceBindingKind(SCS1, SCS2))
3792 return ImplicitConversionSequence::Better;
3793 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3794 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003795
Sebastian Redlb28b4072009-03-22 23:49:27 +00003796 // C++ [over.ics.rank]p3b4:
3797 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3798 // which the references refer are the same type except for
3799 // top-level cv-qualifiers, and the type to which the reference
3800 // initialized by S2 refers is more cv-qualified than the type
3801 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003802 QualType T1 = SCS1.getToType(2);
3803 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003804 T1 = S.Context.getCanonicalType(T1);
3805 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003806 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003807 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3808 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003809 if (UnqualT1 == UnqualT2) {
John McCall31168b02011-06-15 23:02:42 +00003810 // Objective-C++ ARC: If the references refer to objects with different
3811 // lifetimes, prefer bindings that don't change lifetime.
3812 if (SCS1.ObjCLifetimeConversionBinding !=
3813 SCS2.ObjCLifetimeConversionBinding) {
3814 return SCS1.ObjCLifetimeConversionBinding
3815 ? ImplicitConversionSequence::Worse
3816 : ImplicitConversionSequence::Better;
3817 }
3818
Chandler Carruth8e543b32010-12-12 08:17:55 +00003819 // If the type is an array type, promote the element qualifiers to the
3820 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003821 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003822 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003823 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003824 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003825 if (T2.isMoreQualifiedThan(T1))
3826 return ImplicitConversionSequence::Better;
3827 else if (T1.isMoreQualifiedThan(T2))
John McCall31168b02011-06-15 23:02:42 +00003828 return ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003829 }
3830 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003831
Francois Pichet08d2fa02011-09-18 21:37:37 +00003832 // In Microsoft mode, prefer an integral conversion to a
3833 // floating-to-integral conversion if the integral conversion
3834 // is between types of the same size.
3835 // For example:
3836 // void f(float);
3837 // void f(int);
3838 // int main {
3839 // long a;
3840 // f(a);
3841 // }
3842 // Here, MSVC will call f(int) instead of generating a compile error
3843 // as clang will do in standard mode.
Alp Tokerbfa39342014-01-14 12:51:41 +00003844 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3845 SCS2.Second == ICK_Floating_Integral &&
Francois Pichet08d2fa02011-09-18 21:37:37 +00003846 S.Context.getTypeSize(SCS1.getFromType()) ==
Alp Tokerbfa39342014-01-14 12:51:41 +00003847 S.Context.getTypeSize(SCS1.getToType(2)))
Francois Pichet08d2fa02011-09-18 21:37:37 +00003848 return ImplicitConversionSequence::Better;
3849
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003850 return ImplicitConversionSequence::Indistinguishable;
3851}
3852
3853/// CompareQualificationConversions - Compares two standard conversion
3854/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00003855/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
Richard Smith17c00b42014-11-12 01:24:00 +00003856static ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003857CompareQualificationConversions(Sema &S,
3858 const StandardConversionSequence& SCS1,
3859 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00003860 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003861 // -- S1 and S2 differ only in their qualification conversion and
3862 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3863 // cv-qualification signature of type T1 is a proper subset of
3864 // the cv-qualification signature of type T2, and S1 is not the
3865 // deprecated string literal array-to-pointer conversion (4.2).
3866 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3867 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3868 return ImplicitConversionSequence::Indistinguishable;
3869
3870 // FIXME: the example in the standard doesn't use a qualification
3871 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003872 QualType T1 = SCS1.getToType(2);
3873 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003874 T1 = S.Context.getCanonicalType(T1);
3875 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003876 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003877 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3878 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003879
3880 // If the types are the same, we won't learn anything by unwrapped
3881 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003882 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003883 return ImplicitConversionSequence::Indistinguishable;
3884
Chandler Carruth607f38e2009-12-29 07:16:59 +00003885 // If the type is an array type, promote the element qualifiers to the type
3886 // for comparison.
3887 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003888 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003889 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003890 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003891
Mike Stump11289f42009-09-09 15:08:12 +00003892 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003893 = ImplicitConversionSequence::Indistinguishable;
John McCall31168b02011-06-15 23:02:42 +00003894
3895 // Objective-C++ ARC:
3896 // Prefer qualification conversions not involving a change in lifetime
3897 // to qualification conversions that do not change lifetime.
3898 if (SCS1.QualificationIncludesObjCLifetime !=
3899 SCS2.QualificationIncludesObjCLifetime) {
3900 Result = SCS1.QualificationIncludesObjCLifetime
3901 ? ImplicitConversionSequence::Worse
3902 : ImplicitConversionSequence::Better;
3903 }
3904
John McCall5c32be02010-08-24 20:38:10 +00003905 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003906 // Within each iteration of the loop, we check the qualifiers to
3907 // determine if this still looks like a qualification
3908 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003909 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003910 // until there are no more pointers or pointers-to-members left
3911 // to unwrap. This essentially mimics what
3912 // IsQualificationConversion does, but here we're checking for a
3913 // strict subset of qualifiers.
3914 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3915 // The qualifiers are the same, so this doesn't tell us anything
3916 // about how the sequences rank.
3917 ;
3918 else if (T2.isMoreQualifiedThan(T1)) {
3919 // T1 has fewer qualifiers, so it could be the better sequence.
3920 if (Result == ImplicitConversionSequence::Worse)
3921 // Neither has qualifiers that are a subset of the other's
3922 // qualifiers.
3923 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003924
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003925 Result = ImplicitConversionSequence::Better;
3926 } else if (T1.isMoreQualifiedThan(T2)) {
3927 // T2 has fewer qualifiers, so it could be the better sequence.
3928 if (Result == ImplicitConversionSequence::Better)
3929 // Neither has qualifiers that are a subset of the other's
3930 // qualifiers.
3931 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003932
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003933 Result = ImplicitConversionSequence::Worse;
3934 } else {
3935 // Qualifiers are disjoint.
3936 return ImplicitConversionSequence::Indistinguishable;
3937 }
3938
3939 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00003940 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003941 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003942 }
3943
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003944 // Check that the winning standard conversion sequence isn't using
3945 // the deprecated string literal array to pointer conversion.
3946 switch (Result) {
3947 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003948 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003949 Result = ImplicitConversionSequence::Indistinguishable;
3950 break;
3951
3952 case ImplicitConversionSequence::Indistinguishable:
3953 break;
3954
3955 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003956 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003957 Result = ImplicitConversionSequence::Indistinguishable;
3958 break;
3959 }
3960
3961 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003962}
3963
Douglas Gregor5c407d92008-10-23 00:40:37 +00003964/// CompareDerivedToBaseConversions - Compares two standard conversion
3965/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00003966/// various kinds of derived-to-base conversions (C++
3967/// [over.ics.rank]p4b3). As part of these checks, we also look at
3968/// conversions between Objective-C interface types.
Richard Smith17c00b42014-11-12 01:24:00 +00003969static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +00003970CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +00003971 const StandardConversionSequence& SCS1,
3972 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00003973 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003974 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00003975 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003976 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003977
3978 // Adjust the types we're converting from via the array-to-pointer
3979 // conversion, if we need to.
3980 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003981 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003982 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003983 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003984
3985 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00003986 FromType1 = S.Context.getCanonicalType(FromType1);
3987 ToType1 = S.Context.getCanonicalType(ToType1);
3988 FromType2 = S.Context.getCanonicalType(FromType2);
3989 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003990
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003991 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00003992 //
3993 // If class B is derived directly or indirectly from class A and
3994 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00003995 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003996 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00003997 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00003998 SCS2.Second == ICK_Pointer_Conversion &&
3999 /*FIXME: Remove if Objective-C id conversions get their own rank*/
4000 FromType1->isPointerType() && FromType2->isPointerType() &&
4001 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00004002 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004003 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00004004 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004005 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00004006 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004007 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00004008 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004009 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00004010
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004011 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00004012 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004013 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00004014 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004015 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00004016 return ImplicitConversionSequence::Worse;
4017 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004018
4019 // -- conversion of B* to A* is better than conversion of C* to A*,
4020 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004021 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004022 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004023 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004024 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00004025 }
4026 } else if (SCS1.Second == ICK_Pointer_Conversion &&
4027 SCS2.Second == ICK_Pointer_Conversion) {
4028 const ObjCObjectPointerType *FromPtr1
4029 = FromType1->getAs<ObjCObjectPointerType>();
4030 const ObjCObjectPointerType *FromPtr2
4031 = FromType2->getAs<ObjCObjectPointerType>();
4032 const ObjCObjectPointerType *ToPtr1
4033 = ToType1->getAs<ObjCObjectPointerType>();
4034 const ObjCObjectPointerType *ToPtr2
4035 = ToType2->getAs<ObjCObjectPointerType>();
4036
4037 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4038 // Apply the same conversion ranking rules for Objective-C pointer types
4039 // that we do for C++ pointers to class types. However, we employ the
4040 // Objective-C pseudo-subtyping relationship used for assignment of
4041 // Objective-C pointer types.
4042 bool FromAssignLeft
4043 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4044 bool FromAssignRight
4045 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4046 bool ToAssignLeft
4047 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4048 bool ToAssignRight
4049 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4050
4051 // A conversion to an a non-id object pointer type or qualified 'id'
4052 // type is better than a conversion to 'id'.
4053 if (ToPtr1->isObjCIdType() &&
4054 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4055 return ImplicitConversionSequence::Worse;
4056 if (ToPtr2->isObjCIdType() &&
4057 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4058 return ImplicitConversionSequence::Better;
4059
4060 // A conversion to a non-id object pointer type is better than a
4061 // conversion to a qualified 'id' type
4062 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4063 return ImplicitConversionSequence::Worse;
4064 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4065 return ImplicitConversionSequence::Better;
4066
4067 // A conversion to an a non-Class object pointer type or qualified 'Class'
4068 // type is better than a conversion to 'Class'.
4069 if (ToPtr1->isObjCClassType() &&
4070 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4071 return ImplicitConversionSequence::Worse;
4072 if (ToPtr2->isObjCClassType() &&
4073 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4074 return ImplicitConversionSequence::Better;
4075
4076 // A conversion to a non-Class object pointer type is better than a
4077 // conversion to a qualified 'Class' type.
4078 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4079 return ImplicitConversionSequence::Worse;
4080 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4081 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00004082
Douglas Gregor058d3de2011-01-31 18:51:41 +00004083 // -- "conversion of C* to B* is better than conversion of C* to A*,"
4084 if (S.Context.hasSameType(FromType1, FromType2) &&
4085 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4086 (ToAssignLeft != ToAssignRight))
4087 return ToAssignLeft? ImplicitConversionSequence::Worse
4088 : ImplicitConversionSequence::Better;
4089
4090 // -- "conversion of B* to A* is better than conversion of C* to A*,"
4091 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4092 (FromAssignLeft != FromAssignRight))
4093 return FromAssignLeft? ImplicitConversionSequence::Better
4094 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004095 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00004096 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00004097
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00004098 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004099 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4100 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4101 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004102 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004103 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004104 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004105 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004106 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004107 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004108 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004109 ToType2->getAs<MemberPointerType>();
4110 const Type *FromPointeeType1 = FromMemPointer1->getClass();
4111 const Type *ToPointeeType1 = ToMemPointer1->getClass();
4112 const Type *FromPointeeType2 = FromMemPointer2->getClass();
4113 const Type *ToPointeeType2 = ToMemPointer2->getClass();
4114 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4115 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4116 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4117 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00004118 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004119 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004120 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004121 return ImplicitConversionSequence::Worse;
Richard Smith0f59cb32015-12-18 21:45:41 +00004122 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004123 return ImplicitConversionSequence::Better;
4124 }
4125 // conversion of B::* to C::* is better than conversion of A::* to C::*
4126 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004127 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004128 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004129 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004130 return ImplicitConversionSequence::Worse;
4131 }
4132 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004133
Douglas Gregor5ab11652010-04-17 22:01:05 +00004134 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00004135 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00004136 // -- binding of an expression of type C to a reference of type
4137 // B& is better than binding an expression of type C to a
4138 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00004139 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4140 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004141 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004142 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004143 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004144 return ImplicitConversionSequence::Worse;
4145 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004146
Douglas Gregor2fe98832008-11-03 19:09:14 +00004147 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00004148 // -- binding of an expression of type B to a reference of type
4149 // A& is better than binding an expression of type C to a
4150 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00004151 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4152 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004153 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004154 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004155 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004156 return ImplicitConversionSequence::Worse;
4157 }
4158 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004159
Douglas Gregor5c407d92008-10-23 00:40:37 +00004160 return ImplicitConversionSequence::Indistinguishable;
4161}
4162
Douglas Gregor45bb4832013-03-26 23:36:30 +00004163/// \brief Determine whether the given type is valid, e.g., it is not an invalid
4164/// C++ class.
4165static bool isTypeValid(QualType T) {
4166 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4167 return !Record->isInvalidDecl();
4168
4169 return true;
4170}
4171
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004172/// CompareReferenceRelationship - Compare the two types T1 and T2 to
4173/// determine whether they are reference-related,
4174/// reference-compatible, reference-compatible with added
4175/// qualification, or incompatible, for use in C++ initialization by
4176/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4177/// type, and the first type (T1) is the pointee type of the reference
4178/// type being initialized.
4179Sema::ReferenceCompareResult
4180Sema::CompareReferenceRelationship(SourceLocation Loc,
4181 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004182 bool &DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004183 bool &ObjCConversion,
4184 bool &ObjCLifetimeConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004185 assert(!OrigT1->isReferenceType() &&
4186 "T1 must be the pointee type of the reference type");
4187 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4188
4189 QualType T1 = Context.getCanonicalType(OrigT1);
4190 QualType T2 = Context.getCanonicalType(OrigT2);
4191 Qualifiers T1Quals, T2Quals;
4192 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4193 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4194
4195 // C++ [dcl.init.ref]p4:
4196 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4197 // reference-related to "cv2 T2" if T1 is the same type as T2, or
4198 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004199 DerivedToBase = false;
4200 ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004201 ObjCLifetimeConversion = false;
Richard Smith1be59c52016-10-22 01:32:19 +00004202 QualType ConvertedT2;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004203 if (UnqualT1 == UnqualT2) {
4204 // Nothing to do.
Richard Smithdb0ac552015-12-18 22:40:25 +00004205 } else if (isCompleteType(Loc, OrigT2) &&
Douglas Gregor45bb4832013-03-26 23:36:30 +00004206 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00004207 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004208 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004209 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4210 UnqualT2->isObjCObjectOrInterfaceType() &&
4211 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4212 ObjCConversion = true;
Richard Smith1be59c52016-10-22 01:32:19 +00004213 else if (UnqualT2->isFunctionType() &&
4214 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2))
4215 // C++1z [dcl.init.ref]p4:
4216 // cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept
4217 // function" and T1 is "function"
4218 //
4219 // We extend this to also apply to 'noreturn', so allow any function
4220 // conversion between function types.
4221 return Ref_Compatible;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004222 else
4223 return Ref_Incompatible;
4224
4225 // At this point, we know that T1 and T2 are reference-related (at
4226 // least).
4227
4228 // If the type is an array type, promote the element qualifiers to the type
4229 // for comparison.
4230 if (isa<ArrayType>(T1) && T1Quals)
4231 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4232 if (isa<ArrayType>(T2) && T2Quals)
4233 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4234
4235 // C++ [dcl.init.ref]p4:
4236 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4237 // reference-related to T2 and cv1 is the same cv-qualification
4238 // as, or greater cv-qualification than, cv2. For purposes of
4239 // overload resolution, cases for which cv1 is greater
4240 // cv-qualification than cv2 are identified as
4241 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregord517d552011-04-28 17:56:11 +00004242 //
4243 // Note that we also require equivalence of Objective-C GC and address-space
4244 // qualifiers when performing these computations, so that e.g., an int in
4245 // address space 1 is not reference-compatible with an int in address
4246 // space 2.
John McCall31168b02011-06-15 23:02:42 +00004247 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4248 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00004249 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4250 ObjCLifetimeConversion = true;
4251
John McCall31168b02011-06-15 23:02:42 +00004252 T1Quals.removeObjCLifetime();
4253 T2Quals.removeObjCLifetime();
John McCall31168b02011-06-15 23:02:42 +00004254 }
4255
Andrey Bokhanko45d41322016-05-11 18:38:21 +00004256 // MS compiler ignores __unaligned qualifier for references; do the same.
4257 T1Quals.removeUnaligned();
4258 T2Quals.removeUnaligned();
4259
Richard Smithce766292016-10-21 23:01:55 +00004260 if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004261 return Ref_Compatible;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004262 else
4263 return Ref_Related;
4264}
4265
Douglas Gregor836a7e82010-08-11 02:15:33 +00004266/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00004267/// with DeclType. Return true if something definite is found.
4268static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00004269FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4270 QualType DeclType, SourceLocation DeclLoc,
4271 Expr *Init, QualType T2, bool AllowRvalues,
4272 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004273 assert(T2->isRecordType() && "Can only find conversions of record types.");
4274 CXXRecordDecl *T2RecordDecl
4275 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4276
Richard Smith100b24a2014-04-17 01:52:14 +00004277 OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal);
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004278 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4279 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004280 NamedDecl *D = *I;
4281 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4282 if (isa<UsingShadowDecl>(D))
4283 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4284
4285 FunctionTemplateDecl *ConvTemplate
4286 = dyn_cast<FunctionTemplateDecl>(D);
4287 CXXConversionDecl *Conv;
4288 if (ConvTemplate)
4289 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4290 else
4291 Conv = cast<CXXConversionDecl>(D);
4292
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004293 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00004294 // explicit conversions, skip it.
4295 if (!AllowExplicit && Conv->isExplicit())
4296 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004297
Douglas Gregor836a7e82010-08-11 02:15:33 +00004298 if (AllowRvalues) {
4299 bool DerivedToBase = false;
4300 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004301 bool ObjCLifetimeConversion = false;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004302
4303 // If we are initializing an rvalue reference, don't permit conversion
4304 // functions that return lvalues.
4305 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4306 const ReferenceType *RefType
4307 = Conv->getConversionType()->getAs<LValueReferenceType>();
4308 if (RefType && !RefType->getPointeeType()->isFunctionType())
4309 continue;
4310 }
4311
Douglas Gregor836a7e82010-08-11 02:15:33 +00004312 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00004313 S.CompareReferenceRelationship(
4314 DeclLoc,
4315 Conv->getConversionType().getNonReferenceType()
4316 .getUnqualifiedType(),
4317 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCall31168b02011-06-15 23:02:42 +00004318 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth8e543b32010-12-12 08:17:55 +00004319 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00004320 continue;
4321 } else {
4322 // If the conversion function doesn't return a reference type,
4323 // it can't be considered for this conversion. An rvalue reference
4324 // is only acceptable if its referencee is a function type.
4325
4326 const ReferenceType *RefType =
4327 Conv->getConversionType()->getAs<ReferenceType>();
4328 if (!RefType ||
4329 (!RefType->isLValueReferenceType() &&
4330 !RefType->getPointeeType()->isFunctionType()))
4331 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00004332 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004333
Douglas Gregor836a7e82010-08-11 02:15:33 +00004334 if (ConvTemplate)
4335 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004336 Init, DeclType, CandidateSet,
4337 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor836a7e82010-08-11 02:15:33 +00004338 else
4339 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004340 DeclType, CandidateSet,
4341 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redld92badf2010-06-30 18:13:39 +00004342 }
4343
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004344 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4345
Sebastian Redld92badf2010-06-30 18:13:39 +00004346 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00004347 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004348 case OR_Success:
4349 // C++ [over.ics.ref]p1:
4350 //
4351 // [...] If the parameter binds directly to the result of
4352 // applying a conversion function to the argument
4353 // expression, the implicit conversion sequence is a
4354 // user-defined conversion sequence (13.3.3.1.2), with the
4355 // second standard conversion sequence either an identity
4356 // conversion or, if the conversion function returns an
4357 // entity of a type that is a derived class of the parameter
4358 // type, a derived-to-base Conversion.
4359 if (!Best->FinalConversion.DirectBinding)
4360 return false;
4361
4362 ICS.setUserDefined();
4363 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4364 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004365 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redld92badf2010-06-30 18:13:39 +00004366 ICS.UserDefined.ConversionFunction = Best->Function;
John McCall30909032011-09-21 08:36:56 +00004367 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redld92badf2010-06-30 18:13:39 +00004368 ICS.UserDefined.EllipsisConversion = false;
4369 assert(ICS.UserDefined.After.ReferenceBinding &&
4370 ICS.UserDefined.After.DirectBinding &&
4371 "Expected a direct reference binding!");
4372 return true;
4373
4374 case OR_Ambiguous:
4375 ICS.setAmbiguous();
4376 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4377 Cand != CandidateSet.end(); ++Cand)
4378 if (Cand->Viable)
Richard Smithc2bebe92016-05-11 20:37:46 +00004379 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
Sebastian Redld92badf2010-06-30 18:13:39 +00004380 return true;
4381
4382 case OR_No_Viable_Function:
4383 case OR_Deleted:
4384 // There was no suitable conversion, or we found a deleted
4385 // conversion; continue with other checks.
4386 return false;
4387 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004388
David Blaikie8a40f702012-01-17 06:56:22 +00004389 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redld92badf2010-06-30 18:13:39 +00004390}
4391
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004392/// \brief Compute an implicit conversion sequence for reference
4393/// initialization.
4394static ImplicitConversionSequence
Sebastian Redldf888642011-12-03 14:54:30 +00004395TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004396 SourceLocation DeclLoc,
4397 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00004398 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004399 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4400
4401 // Most paths end in a failed conversion.
4402 ImplicitConversionSequence ICS;
4403 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4404
4405 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4406 QualType T2 = Init->getType();
4407
4408 // If the initializer is the address of an overloaded function, try
4409 // to resolve the overloaded function. If all goes well, T2 is the
4410 // type of the resulting function.
4411 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4412 DeclAccessPair Found;
4413 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4414 false, Found))
4415 T2 = Fn->getType();
4416 }
4417
4418 // Compute some basic properties of the types and the initializer.
4419 bool isRValRef = DeclType->isRValueReferenceType();
4420 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004421 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004422 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00004423 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004424 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004425 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004426 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004427
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004428
Sebastian Redld92badf2010-06-30 18:13:39 +00004429 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00004430 // A reference to type "cv1 T1" is initialized by an expression
4431 // of type "cv2 T2" as follows:
4432
Sebastian Redld92badf2010-06-30 18:13:39 +00004433 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00004434 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004435 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4436 // reference-compatible with "cv2 T2," or
4437 //
4438 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
Richard Smithce766292016-10-21 23:01:55 +00004439 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004440 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00004441 // When a parameter of reference type binds directly (8.5.3)
4442 // to an argument expression, the implicit conversion sequence
4443 // is the identity conversion, unless the argument expression
4444 // has a type that is a derived class of the parameter type,
4445 // in which case the implicit conversion sequence is a
4446 // derived-to-base Conversion (13.3.3.1).
4447 ICS.setStandard();
4448 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004449 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4450 : ObjCConversion? ICK_Compatible_Conversion
4451 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00004452 ICS.Standard.Third = ICK_Identity;
4453 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4454 ICS.Standard.setToType(0, T2);
4455 ICS.Standard.setToType(1, T1);
4456 ICS.Standard.setToType(2, T1);
4457 ICS.Standard.ReferenceBinding = true;
4458 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004459 ICS.Standard.IsLvalueReference = !isRValRef;
4460 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4461 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004462 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004463 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Craig Topperc3ec1492014-05-26 06:22:03 +00004464 ICS.Standard.CopyConstructor = nullptr;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004465 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004466
Sebastian Redld92badf2010-06-30 18:13:39 +00004467 // Nothing more to do: the inaccessibility/ambiguity check for
4468 // derived-to-base conversions is suppressed when we're
4469 // computing the implicit conversion sequence (C++
4470 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004471 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00004472 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004473
Sebastian Redld92badf2010-06-30 18:13:39 +00004474 // -- has a class type (i.e., T2 is a class type), where T1 is
4475 // not reference-related to T2, and can be implicitly
4476 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4477 // is reference-compatible with "cv3 T3" 92) (this
4478 // conversion is selected by enumerating the applicable
4479 // conversion functions (13.3.1.6) and choosing the best
4480 // one through overload resolution (13.3)),
4481 if (!SuppressUserConversions && T2->isRecordType() &&
Richard Smithdb0ac552015-12-18 22:40:25 +00004482 S.isCompleteType(DeclLoc, T2) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00004483 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00004484 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4485 Init, T2, /*AllowRvalues=*/false,
4486 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00004487 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004488 }
4489 }
4490
Sebastian Redld92badf2010-06-30 18:13:39 +00004491 // -- Otherwise, the reference shall be an lvalue reference to a
4492 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00004493 // shall be an rvalue reference.
Richard Smithce4f6082012-05-24 04:29:20 +00004494 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004495 return ICS;
4496
Douglas Gregorf143cd52011-01-24 16:14:37 +00004497 // -- If the initializer expression
4498 //
4499 // -- is an xvalue, class prvalue, array prvalue or function
John McCall31168b02011-06-15 23:02:42 +00004500 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Richard Smithce766292016-10-21 23:01:55 +00004501 if (RefRelationship == Sema::Ref_Compatible &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004502 (InitCategory.isXValue() ||
Richard Smithce766292016-10-21 23:01:55 +00004503 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4504 (InitCategory.isLValue() && T2->isFunctionType()))) {
Douglas Gregorf143cd52011-01-24 16:14:37 +00004505 ICS.setStandard();
4506 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004507 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004508 : ObjCConversion? ICK_Compatible_Conversion
4509 : ICK_Identity;
4510 ICS.Standard.Third = ICK_Identity;
4511 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4512 ICS.Standard.setToType(0, T2);
4513 ICS.Standard.setToType(1, T1);
4514 ICS.Standard.setToType(2, T1);
4515 ICS.Standard.ReferenceBinding = true;
4516 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4517 // binding unless we're binding to a class prvalue.
4518 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4519 // allow the use of rvalue references in C++98/03 for the benefit of
4520 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004521 ICS.Standard.DirectBinding =
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004522 S.getLangOpts().CPlusPlus11 ||
Richard Smithb94afe12014-07-14 19:54:05 +00004523 !(InitCategory.isPRValue() || T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00004524 ICS.Standard.IsLvalueReference = !isRValRef;
4525 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004526 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00004527 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004528 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Craig Topperc3ec1492014-05-26 06:22:03 +00004529 ICS.Standard.CopyConstructor = nullptr;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004530 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004531 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00004532 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004533
Douglas Gregorf143cd52011-01-24 16:14:37 +00004534 // -- has a class type (i.e., T2 is a class type), where T1 is not
4535 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004536 // an xvalue, class prvalue, or function lvalue of type
4537 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00004538 // "cv3 T3",
4539 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004540 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00004541 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004542 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004543 // class subobject).
4544 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
Richard Smithdb0ac552015-12-18 22:40:25 +00004545 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004546 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4547 Init, T2, /*AllowRvalues=*/true,
4548 AllowExplicit)) {
4549 // In the second case, if the reference is an rvalue reference
4550 // and the second standard conversion sequence of the
4551 // user-defined conversion sequence includes an lvalue-to-rvalue
4552 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004553 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004554 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4555 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4556
Douglas Gregor95273c32011-01-21 16:36:05 +00004557 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00004558 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004559
Richard Smith19172c42014-07-14 02:28:44 +00004560 // A temporary of function type cannot be created; don't even try.
4561 if (T1->isFunctionType())
4562 return ICS;
4563
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004564 // -- Otherwise, a temporary of type "cv1 T1" is created and
4565 // initialized from the initializer expression using the
4566 // rules for a non-reference copy initialization (8.5). The
4567 // reference is then bound to the temporary. If T1 is
4568 // reference-related to T2, cv1 must be the same
4569 // cv-qualification as, or greater cv-qualification than,
4570 // cv2; otherwise, the program is ill-formed.
4571 if (RefRelationship == Sema::Ref_Related) {
4572 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4573 // we would be reference-compatible or reference-compatible with
4574 // added qualification. But that wasn't the case, so the reference
4575 // initialization fails.
John McCall31168b02011-06-15 23:02:42 +00004576 //
4577 // Note that we only want to check address spaces and cvr-qualifiers here.
Andrey Bokhanko45d41322016-05-11 18:38:21 +00004578 // ObjC GC, lifetime and unaligned qualifiers aren't important.
John McCall31168b02011-06-15 23:02:42 +00004579 Qualifiers T1Quals = T1.getQualifiers();
4580 Qualifiers T2Quals = T2.getQualifiers();
4581 T1Quals.removeObjCGCAttr();
4582 T1Quals.removeObjCLifetime();
4583 T2Quals.removeObjCGCAttr();
4584 T2Quals.removeObjCLifetime();
Andrey Bokhanko45d41322016-05-11 18:38:21 +00004585 // MS compiler ignores __unaligned qualifier for references; do the same.
4586 T1Quals.removeUnaligned();
4587 T2Quals.removeUnaligned();
John McCall31168b02011-06-15 23:02:42 +00004588 if (!T1Quals.compatiblyIncludes(T2Quals))
4589 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004590 }
4591
4592 // If at least one of the types is a class type, the types are not
4593 // related, and we aren't allowed any user conversions, the
4594 // reference binding fails. This case is important for breaking
4595 // recursion, since TryImplicitConversion below will attempt to
4596 // create a temporary through the use of a copy constructor.
4597 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4598 (T1->isRecordType() || T2->isRecordType()))
4599 return ICS;
4600
Douglas Gregorcba72b12011-01-21 05:18:22 +00004601 // If T1 is reference-related to T2 and the reference is an rvalue
4602 // reference, the initializer expression shall not be an lvalue.
4603 if (RefRelationship >= Sema::Ref_Related &&
4604 isRValRef && Init->Classify(S.Context).isLValue())
4605 return ICS;
4606
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004607 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004608 // When a parameter of reference type is not bound directly to
4609 // an argument expression, the conversion sequence is the one
4610 // required to convert the argument expression to the
4611 // underlying type of the reference according to
4612 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4613 // to copy-initializing a temporary of the underlying type with
4614 // the argument expression. Any difference in top-level
4615 // cv-qualification is subsumed by the initialization itself
4616 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00004617 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4618 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004619 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004620 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004621 /*AllowObjCWritebackConversion=*/false,
4622 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004623
4624 // Of course, that's still a reference binding.
4625 if (ICS.isStandard()) {
4626 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004627 ICS.Standard.IsLvalueReference = !isRValRef;
Richard Smith19172c42014-07-14 02:28:44 +00004628 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004629 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004630 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004631 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004632 } else if (ICS.isUserDefined()) {
Richard Smith19172c42014-07-14 02:28:44 +00004633 const ReferenceType *LValRefType =
4634 ICS.UserDefined.ConversionFunction->getReturnType()
4635 ->getAs<LValueReferenceType>();
4636
4637 // C++ [over.ics.ref]p3:
4638 // Except for an implicit object parameter, for which see 13.3.1, a
4639 // standard conversion sequence cannot be formed if it requires [...]
4640 // binding an rvalue reference to an lvalue other than a function
4641 // lvalue.
4642 // Note that the function case is not possible here.
4643 if (DeclType->isRValueReferenceType() && LValRefType) {
4644 // FIXME: This is the wrong BadConversionSequence. The problem is binding
4645 // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4646 // reference to an rvalue!
4647 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4648 return ICS;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004649 }
Richard Smith19172c42014-07-14 02:28:44 +00004650
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004651 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004652 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
Richard Smith19172c42014-07-14 02:28:44 +00004653 ICS.UserDefined.After.BindsToFunctionLvalue = false;
4654 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004655 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4656 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004657 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00004658
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004659 return ICS;
4660}
4661
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004662static ImplicitConversionSequence
4663TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4664 bool SuppressUserConversions,
4665 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004666 bool AllowObjCWritebackConversion,
4667 bool AllowExplicit = false);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004668
4669/// TryListConversion - Try to copy-initialize a value of type ToType from the
4670/// initializer list From.
4671static ImplicitConversionSequence
4672TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4673 bool SuppressUserConversions,
4674 bool InOverloadResolution,
4675 bool AllowObjCWritebackConversion) {
4676 // C++11 [over.ics.list]p1:
4677 // When an argument is an initializer list, it is not an expression and
4678 // special rules apply for converting it to a parameter type.
4679
4680 ImplicitConversionSequence Result;
4681 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4682
Sebastian Redl09edce02012-01-23 22:09:39 +00004683 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004684 // initialized from init lists.
Richard Smithdb0ac552015-12-18 22:40:25 +00004685 if (!S.isCompleteType(From->getLocStart(), ToType))
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004686 return Result;
4687
Larisse Voufo19d08672015-01-27 18:47:05 +00004688 // Per DR1467:
4689 // If the parameter type is a class X and the initializer list has a single
4690 // element of type cv U, where U is X or a class derived from X, the
4691 // implicit conversion sequence is the one required to convert the element
4692 // to the parameter type.
4693 //
4694 // Otherwise, if the parameter type is a character array [... ]
4695 // and the initializer list has a single element that is an
4696 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4697 // implicit conversion sequence is the identity conversion.
4698 if (From->getNumInits() == 1) {
4699 if (ToType->isRecordType()) {
4700 QualType InitType = From->getInit(0)->getType();
4701 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00004702 S.IsDerivedFrom(From->getLocStart(), InitType, ToType))
Larisse Voufo19d08672015-01-27 18:47:05 +00004703 return TryCopyInitialization(S, From->getInit(0), ToType,
4704 SuppressUserConversions,
4705 InOverloadResolution,
4706 AllowObjCWritebackConversion);
4707 }
Richard Smith1bbaba82015-01-27 23:23:39 +00004708 // FIXME: Check the other conditions here: array of character type,
4709 // initializer is a string literal.
4710 if (ToType->isArrayType()) {
Larisse Voufo19d08672015-01-27 18:47:05 +00004711 InitializedEntity Entity =
4712 InitializedEntity::InitializeParameter(S.Context, ToType,
4713 /*Consumed=*/false);
4714 if (S.CanPerformCopyInitialization(Entity, From)) {
4715 Result.setStandard();
4716 Result.Standard.setAsIdentityConversion();
4717 Result.Standard.setFromType(ToType);
4718 Result.Standard.setAllToTypes(ToType);
4719 return Result;
4720 }
4721 }
4722 }
4723
4724 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004725 // C++11 [over.ics.list]p2:
4726 // If the parameter type is std::initializer_list<X> or "array of X" and
4727 // all the elements can be implicitly converted to X, the implicit
4728 // conversion sequence is the worst conversion necessary to convert an
4729 // element of the list to X.
Larisse Voufo19d08672015-01-27 18:47:05 +00004730 //
4731 // C++14 [over.ics.list]p3:
NAKAMURA Takumib01d86b2015-02-25 11:02:00 +00004732 // Otherwise, if the parameter type is "array of N X", if the initializer
Larisse Voufo19d08672015-01-27 18:47:05 +00004733 // list has exactly N elements or if it has fewer than N elements and X is
4734 // default-constructible, and if all the elements of the initializer list
4735 // can be implicitly converted to X, the implicit conversion sequence is
4736 // the worst conversion necessary to convert an element of the list to X.
Richard Smith1bbaba82015-01-27 23:23:39 +00004737 //
4738 // FIXME: We're missing a lot of these checks.
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004739 bool toStdInitializerList = false;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004740 QualType X;
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004741 if (ToType->isArrayType())
Richard Smith0db1ea52012-12-09 06:48:56 +00004742 X = S.Context.getAsArrayType(ToType)->getElementType();
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004743 else
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004744 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004745 if (!X.isNull()) {
4746 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4747 Expr *Init = From->getInit(i);
4748 ImplicitConversionSequence ICS =
4749 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4750 InOverloadResolution,
4751 AllowObjCWritebackConversion);
4752 // If a single element isn't convertible, fail.
4753 if (ICS.isBad()) {
4754 Result = ICS;
4755 break;
4756 }
4757 // Otherwise, look for the worst conversion.
4758 if (Result.isBad() ||
Richard Smith0f59cb32015-12-18 21:45:41 +00004759 CompareImplicitConversionSequences(S, From->getLocStart(), ICS,
4760 Result) ==
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004761 ImplicitConversionSequence::Worse)
4762 Result = ICS;
4763 }
Douglas Gregor0f5c1c02012-04-04 23:09:20 +00004764
4765 // For an empty list, we won't have computed any conversion sequence.
4766 // Introduce the identity conversion sequence.
4767 if (From->getNumInits() == 0) {
4768 Result.setStandard();
4769 Result.Standard.setAsIdentityConversion();
4770 Result.Standard.setFromType(ToType);
4771 Result.Standard.setAllToTypes(ToType);
4772 }
4773
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004774 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004775 return Result;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004776 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004777
Larisse Voufo19d08672015-01-27 18:47:05 +00004778 // C++14 [over.ics.list]p4:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004779 // C++11 [over.ics.list]p3:
4780 // Otherwise, if the parameter is a non-aggregate class X and overload
4781 // resolution chooses a single best constructor [...] the implicit
4782 // conversion sequence is a user-defined conversion sequence. If multiple
4783 // constructors are viable but none is better than the others, the
4784 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004785 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4786 // This function can deal with initializer lists.
Richard Smitha93f1022013-09-06 22:30:28 +00004787 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4788 /*AllowExplicit=*/false,
4789 InOverloadResolution, /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004790 AllowObjCWritebackConversion,
4791 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004792 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004793
Larisse Voufo19d08672015-01-27 18:47:05 +00004794 // C++14 [over.ics.list]p5:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004795 // C++11 [over.ics.list]p4:
4796 // Otherwise, if the parameter has an aggregate type which can be
4797 // initialized from the initializer list [...] the implicit conversion
4798 // sequence is a user-defined conversion sequence.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004799 if (ToType->isAggregateType()) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004800 // Type is an aggregate, argument is an init list. At this point it comes
4801 // down to checking whether the initialization works.
4802 // FIXME: Find out whether this parameter is consumed or not.
Richard Smithb8c0f552016-12-09 18:49:13 +00004803 // FIXME: Expose SemaInit's aggregate initialization code so that we don't
4804 // need to call into the initialization code here; overload resolution
4805 // should not be doing that.
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004806 InitializedEntity Entity =
4807 InitializedEntity::InitializeParameter(S.Context, ToType,
4808 /*Consumed=*/false);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004809 if (S.CanPerformCopyInitialization(Entity, From)) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004810 Result.setUserDefined();
4811 Result.UserDefined.Before.setAsIdentityConversion();
4812 // Initializer lists don't have a type.
4813 Result.UserDefined.Before.setFromType(QualType());
4814 Result.UserDefined.Before.setAllToTypes(QualType());
4815
4816 Result.UserDefined.After.setAsIdentityConversion();
4817 Result.UserDefined.After.setFromType(ToType);
4818 Result.UserDefined.After.setAllToTypes(ToType);
Craig Topperc3ec1492014-05-26 06:22:03 +00004819 Result.UserDefined.ConversionFunction = nullptr;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004820 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004821 return Result;
4822 }
4823
Larisse Voufo19d08672015-01-27 18:47:05 +00004824 // C++14 [over.ics.list]p6:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004825 // C++11 [over.ics.list]p5:
4826 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redldf888642011-12-03 14:54:30 +00004827 if (ToType->isReferenceType()) {
4828 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4829 // mention initializer lists in any way. So we go by what list-
4830 // initialization would do and try to extrapolate from that.
4831
4832 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4833
4834 // If the initializer list has a single element that is reference-related
4835 // to the parameter type, we initialize the reference from that.
4836 if (From->getNumInits() == 1) {
4837 Expr *Init = From->getInit(0);
4838
4839 QualType T2 = Init->getType();
4840
4841 // If the initializer is the address of an overloaded function, try
4842 // to resolve the overloaded function. If all goes well, T2 is the
4843 // type of the resulting function.
4844 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4845 DeclAccessPair Found;
4846 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4847 Init, ToType, false, Found))
4848 T2 = Fn->getType();
4849 }
4850
4851 // Compute some basic properties of the types and the initializer.
4852 bool dummy1 = false;
4853 bool dummy2 = false;
4854 bool dummy3 = false;
4855 Sema::ReferenceCompareResult RefRelationship
4856 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4857 dummy2, dummy3);
4858
Richard Smith4d2bbd72013-09-06 01:22:42 +00004859 if (RefRelationship >= Sema::Ref_Related) {
Richard Smitha93f1022013-09-06 22:30:28 +00004860 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4861 SuppressUserConversions,
4862 /*AllowExplicit=*/false);
Richard Smith4d2bbd72013-09-06 01:22:42 +00004863 }
Sebastian Redldf888642011-12-03 14:54:30 +00004864 }
4865
4866 // Otherwise, we bind the reference to a temporary created from the
4867 // initializer list.
4868 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4869 InOverloadResolution,
4870 AllowObjCWritebackConversion);
4871 if (Result.isFailure())
4872 return Result;
4873 assert(!Result.isEllipsis() &&
4874 "Sub-initialization cannot result in ellipsis conversion.");
4875
4876 // Can we even bind to a temporary?
4877 if (ToType->isRValueReferenceType() ||
4878 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4879 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4880 Result.UserDefined.After;
4881 SCS.ReferenceBinding = true;
4882 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4883 SCS.BindsToRvalue = true;
4884 SCS.BindsToFunctionLvalue = false;
4885 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4886 SCS.ObjCLifetimeConversionBinding = false;
4887 } else
4888 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4889 From, ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004890 return Result;
Sebastian Redldf888642011-12-03 14:54:30 +00004891 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004892
Larisse Voufo19d08672015-01-27 18:47:05 +00004893 // C++14 [over.ics.list]p7:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004894 // C++11 [over.ics.list]p6:
4895 // Otherwise, if the parameter type is not a class:
4896 if (!ToType->isRecordType()) {
Larisse Voufo19d08672015-01-27 18:47:05 +00004897 // - if the initializer list has one element that is not itself an
4898 // initializer list, the implicit conversion sequence is the one
4899 // required to convert the element to the parameter type.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004900 unsigned NumInits = From->getNumInits();
Richard Smith1bbaba82015-01-27 23:23:39 +00004901 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004902 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4903 SuppressUserConversions,
4904 InOverloadResolution,
4905 AllowObjCWritebackConversion);
4906 // - if the initializer list has no elements, the implicit conversion
4907 // sequence is the identity conversion.
4908 else if (NumInits == 0) {
4909 Result.setStandard();
4910 Result.Standard.setAsIdentityConversion();
John McCallb73bc9a2012-04-04 02:40:27 +00004911 Result.Standard.setFromType(ToType);
4912 Result.Standard.setAllToTypes(ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004913 }
4914 return Result;
4915 }
4916
Larisse Voufo19d08672015-01-27 18:47:05 +00004917 // C++14 [over.ics.list]p8:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004918 // C++11 [over.ics.list]p7:
4919 // In all cases other than those enumerated above, no conversion is possible
4920 return Result;
4921}
4922
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004923/// TryCopyInitialization - Try to copy-initialize a value of type
4924/// ToType from the expression From. Return the implicit conversion
4925/// sequence required to pass this argument, which may be a bad
4926/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00004927/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00004928/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004929static ImplicitConversionSequence
4930TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004931 bool SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004932 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004933 bool AllowObjCWritebackConversion,
4934 bool AllowExplicit) {
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004935 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4936 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4937 InOverloadResolution,AllowObjCWritebackConversion);
4938
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004939 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004940 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004941 /*FIXME:*/From->getLocStart(),
4942 SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004943 AllowExplicit);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004944
John McCall5c32be02010-08-24 20:38:10 +00004945 return TryImplicitConversion(S, From, ToType,
4946 SuppressUserConversions,
4947 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004948 InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00004949 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004950 AllowObjCWritebackConversion,
4951 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004952}
4953
Anna Zaks1b068122011-07-28 19:46:48 +00004954static bool TryCopyInitialization(const CanQualType FromQTy,
4955 const CanQualType ToQTy,
4956 Sema &S,
4957 SourceLocation Loc,
4958 ExprValueKind FromVK) {
4959 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4960 ImplicitConversionSequence ICS =
4961 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4962
4963 return !ICS.isBad();
4964}
4965
Douglas Gregor436424c2008-11-18 23:14:02 +00004966/// TryObjectArgumentInitialization - Try to initialize the object
4967/// parameter of the given member function (@c Method) from the
4968/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00004969static ImplicitConversionSequence
Richard Smith0f59cb32015-12-18 21:45:41 +00004970TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004971 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00004972 CXXMethodDecl *Method,
4973 CXXRecordDecl *ActingContext) {
4974 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00004975 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4976 // const volatile object.
4977 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4978 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00004979 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00004980
4981 // Set up the conversion sequence as a "bad" conversion, to allow us
4982 // to exit early.
4983 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00004984
4985 // We need to have an object of class type.
Douglas Gregor02824322011-01-26 19:30:28 +00004986 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004987 FromType = PT->getPointeeType();
4988
Douglas Gregor02824322011-01-26 19:30:28 +00004989 // When we had a pointer, it's implicitly dereferenced, so we
4990 // better have an lvalue.
4991 assert(FromClassification.isLValue());
4992 }
4993
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004994 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00004995
Douglas Gregor02824322011-01-26 19:30:28 +00004996 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004997 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00004998 // parameter is
4999 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005000 // - "lvalue reference to cv X" for functions declared without a
5001 // ref-qualifier or with the & ref-qualifier
5002 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00005003 // ref-qualifier
5004 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005005 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00005006 // cv-qualification on the member function declaration.
5007 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005008 // However, when finding an implicit conversion sequence for the argument, we
Richard Smith122f88d2016-12-06 23:52:28 +00005009 // are not allowed to perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00005010 // (C++ [over.match.funcs]p5). We perform a simplified version of
5011 // reference binding here, that allows class rvalues to bind to
5012 // non-constant references.
5013
Douglas Gregor02824322011-01-26 19:30:28 +00005014 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00005015 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005016 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005017 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00005018 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00005019 ICS.setBad(BadConversionSequence::bad_qualifiers,
Richard Smith03c66d32013-01-26 02:07:32 +00005020 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00005021 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00005022 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005023
5024 // Check that we have either the same type or a derived type. It
5025 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00005026 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00005027 ImplicitConversionKind SecondKind;
5028 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5029 SecondKind = ICK_Identity;
Richard Smith0f59cb32015-12-18 21:45:41 +00005030 } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00005031 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00005032 else {
John McCall65eb8792010-02-25 01:37:24 +00005033 ICS.setBad(BadConversionSequence::unrelated_class,
5034 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00005035 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00005036 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005037
Douglas Gregor02824322011-01-26 19:30:28 +00005038 // Check the ref-qualifier.
5039 switch (Method->getRefQualifier()) {
5040 case RQ_None:
5041 // Do nothing; we don't care about lvalueness or rvalueness.
5042 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005043
Douglas Gregor02824322011-01-26 19:30:28 +00005044 case RQ_LValue:
5045 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
5046 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005047 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00005048 ImplicitParamType);
5049 return ICS;
5050 }
5051 break;
5052
5053 case RQ_RValue:
5054 if (!FromClassification.isRValue()) {
5055 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005056 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00005057 ImplicitParamType);
5058 return ICS;
5059 }
5060 break;
5061 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005062
Douglas Gregor436424c2008-11-18 23:14:02 +00005063 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00005064 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00005065 ICS.Standard.setAsIdentityConversion();
5066 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00005067 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00005068 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00005069 ICS.Standard.ReferenceBinding = true;
5070 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005071 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00005072 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00005073 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5074 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5075 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00005076 return ICS;
5077}
5078
5079/// PerformObjectArgumentInitialization - Perform initialization of
5080/// the implicit object parameter for the given Method with the given
5081/// expression.
John Wiegley01296292011-04-08 18:41:53 +00005082ExprResult
5083Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005084 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00005085 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00005086 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005087 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00005088 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005089 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00005090
Douglas Gregor02824322011-01-26 19:30:28 +00005091 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005092 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005093 FromRecordType = PT->getPointeeType();
5094 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00005095 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005096 } else {
5097 FromRecordType = From->getType();
5098 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00005099 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005100 }
5101
John McCall6e9f8f62009-12-03 04:06:58 +00005102 // Note that we always use the true parent context when performing
5103 // the actual argument initialization.
Nico Weberb58e51c2014-11-19 05:21:39 +00005104 ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
Richard Smith0f59cb32015-12-18 21:45:41 +00005105 *this, From->getLocStart(), From->getType(), FromClassification, Method,
5106 Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005107 if (ICS.isBad()) {
5108 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
5109 Qualifiers FromQs = FromRecordType.getQualifiers();
5110 Qualifiers ToQs = DestType.getQualifiers();
5111 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5112 if (CVR) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005113 Diag(From->getLocStart(),
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005114 diag::err_member_function_call_bad_cvr)
5115 << Method->getDeclName() << FromRecordType << (CVR - 1)
5116 << From->getSourceRange();
5117 Diag(Method->getLocation(), diag::note_previous_decl)
5118 << Method->getDeclName();
John Wiegley01296292011-04-08 18:41:53 +00005119 return ExprError();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005120 }
5121 }
5122
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005123 return Diag(From->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00005124 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005125 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005126 }
Mike Stump11289f42009-09-09 15:08:12 +00005127
John Wiegley01296292011-04-08 18:41:53 +00005128 if (ICS.Standard.Second == ICK_Derived_To_Base) {
5129 ExprResult FromRes =
5130 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5131 if (FromRes.isInvalid())
5132 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005133 From = FromRes.get();
John Wiegley01296292011-04-08 18:41:53 +00005134 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005135
Douglas Gregorcc3f3252010-03-03 23:55:11 +00005136 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley01296292011-04-08 18:41:53 +00005137 From = ImpCastExprToType(From, DestType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005138 From->getValueKind()).get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005139 return From;
Douglas Gregor436424c2008-11-18 23:14:02 +00005140}
5141
Douglas Gregor5fb53972009-01-14 15:45:31 +00005142/// TryContextuallyConvertToBool - Attempt to contextually convert the
5143/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00005144static ImplicitConversionSequence
5145TryContextuallyConvertToBool(Sema &S, Expr *From) {
John McCall5c32be02010-08-24 20:38:10 +00005146 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00005147 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00005148 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00005149 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00005150 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005151 /*AllowObjCWritebackConversion=*/false,
5152 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00005153}
5154
5155/// PerformContextuallyConvertToBool - Perform a contextual conversion
5156/// of the expression From to bool (C++0x [conv]p3).
John Wiegley01296292011-04-08 18:41:53 +00005157ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00005158 if (checkPlaceholderForOverload(*this, From))
5159 return ExprError();
5160
John McCall5c32be02010-08-24 20:38:10 +00005161 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00005162 if (!ICS.isBad())
5163 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005164
Fariborz Jahanian76197412009-11-18 18:26:29 +00005165 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005166 return Diag(From->getLocStart(),
John McCall0009fcc2011-04-26 20:42:42 +00005167 diag::err_typecheck_bool_condition)
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00005168 << From->getType() << From->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00005169 return ExprError();
Douglas Gregor5fb53972009-01-14 15:45:31 +00005170}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005171
Richard Smithf8379a02012-01-18 23:55:52 +00005172/// Check that the specified conversion is permitted in a converted constant
5173/// expression, according to C++11 [expr.const]p3. Return true if the conversion
5174/// is acceptable.
5175static bool CheckConvertedConstantConversions(Sema &S,
5176 StandardConversionSequence &SCS) {
5177 // Since we know that the target type is an integral or unscoped enumeration
5178 // type, most conversion kinds are impossible. All possible First and Third
5179 // conversions are fine.
5180 switch (SCS.Second) {
5181 case ICK_Identity:
Richard Smith3c4f8d22016-10-16 17:54:23 +00005182 case ICK_Function_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005183 case ICK_Integral_Promotion:
Richard Smith410cc892014-11-26 03:26:53 +00005184 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
Egor Churaev89831422016-12-23 14:55:49 +00005185 case ICK_Zero_Queue_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005186 return true;
5187
5188 case ICK_Boolean_Conversion:
Richard Smithca24ed42012-09-13 22:00:12 +00005189 // Conversion from an integral or unscoped enumeration type to bool is
Richard Smith410cc892014-11-26 03:26:53 +00005190 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5191 // conversion, so we allow it in a converted constant expression.
5192 //
5193 // FIXME: Per core issue 1407, we should not allow this, but that breaks
5194 // a lot of popular code. We should at least add a warning for this
5195 // (non-conforming) extension.
Richard Smithca24ed42012-09-13 22:00:12 +00005196 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5197 SCS.getToType(2)->isBooleanType();
5198
Richard Smith410cc892014-11-26 03:26:53 +00005199 case ICK_Pointer_Conversion:
5200 case ICK_Pointer_Member:
5201 // C++1z: null pointer conversions and null member pointer conversions are
5202 // only permitted if the source type is std::nullptr_t.
5203 return SCS.getFromType()->isNullPtrType();
5204
5205 case ICK_Floating_Promotion:
5206 case ICK_Complex_Promotion:
5207 case ICK_Floating_Conversion:
5208 case ICK_Complex_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005209 case ICK_Floating_Integral:
Richard Smith410cc892014-11-26 03:26:53 +00005210 case ICK_Compatible_Conversion:
5211 case ICK_Derived_To_Base:
5212 case ICK_Vector_Conversion:
5213 case ICK_Vector_Splat:
Richard Smithf8379a02012-01-18 23:55:52 +00005214 case ICK_Complex_Real:
Richard Smith410cc892014-11-26 03:26:53 +00005215 case ICK_Block_Pointer_Conversion:
5216 case ICK_TransparentUnionConversion:
5217 case ICK_Writeback_Conversion:
5218 case ICK_Zero_Event_Conversion:
George Burgess IV45461812015-10-11 20:13:20 +00005219 case ICK_C_Only_Conversion:
George Burgess IV2099b542016-09-02 22:59:57 +00005220 case ICK_Incompatible_Pointer_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005221 return false;
5222
5223 case ICK_Lvalue_To_Rvalue:
5224 case ICK_Array_To_Pointer:
5225 case ICK_Function_To_Pointer:
Richard Smith410cc892014-11-26 03:26:53 +00005226 llvm_unreachable("found a first conversion kind in Second");
5227
Richard Smithf8379a02012-01-18 23:55:52 +00005228 case ICK_Qualification:
Richard Smith410cc892014-11-26 03:26:53 +00005229 llvm_unreachable("found a third conversion kind in Second");
Richard Smithf8379a02012-01-18 23:55:52 +00005230
5231 case ICK_Num_Conversion_Kinds:
5232 break;
5233 }
5234
5235 llvm_unreachable("unknown conversion kind");
5236}
5237
5238/// CheckConvertedConstantExpression - Check that the expression From is a
5239/// converted constant expression of type T, perform the conversion and produce
5240/// the converted expression, per C++11 [expr.const]p3.
Richard Smith410cc892014-11-26 03:26:53 +00005241static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5242 QualType T, APValue &Value,
5243 Sema::CCEKind CCE,
5244 bool RequireInt) {
5245 assert(S.getLangOpts().CPlusPlus11 &&
5246 "converted constant expression outside C++11");
Richard Smithf8379a02012-01-18 23:55:52 +00005247
Richard Smith410cc892014-11-26 03:26:53 +00005248 if (checkPlaceholderForOverload(S, From))
Richard Smithf8379a02012-01-18 23:55:52 +00005249 return ExprError();
5250
Richard Smith410cc892014-11-26 03:26:53 +00005251 // C++1z [expr.const]p3:
5252 // A converted constant expression of type T is an expression,
5253 // implicitly converted to type T, where the converted
5254 // expression is a constant expression and the implicit conversion
5255 // sequence contains only [... list of conversions ...].
Ismail Pazarbasi4a007742016-09-07 18:24:54 +00005256 // C++1z [stmt.if]p2:
5257 // If the if statement is of the form if constexpr, the value of the
5258 // condition shall be a contextually converted constant expression of type
5259 // bool.
Richard Smithf8379a02012-01-18 23:55:52 +00005260 ImplicitConversionSequence ICS =
Ismail Pazarbasi4a007742016-09-07 18:24:54 +00005261 CCE == Sema::CCEK_ConstexprIf
5262 ? TryContextuallyConvertToBool(S, From)
5263 : TryCopyInitialization(S, From, T,
5264 /*SuppressUserConversions=*/false,
5265 /*InOverloadResolution=*/false,
5266 /*AllowObjcWritebackConversion=*/false,
5267 /*AllowExplicit=*/false);
Craig Topperc3ec1492014-05-26 06:22:03 +00005268 StandardConversionSequence *SCS = nullptr;
Richard Smithf8379a02012-01-18 23:55:52 +00005269 switch (ICS.getKind()) {
5270 case ImplicitConversionSequence::StandardConversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005271 SCS = &ICS.Standard;
5272 break;
5273 case ImplicitConversionSequence::UserDefinedConversion:
Richard Smith410cc892014-11-26 03:26:53 +00005274 // We are converting to a non-class type, so the Before sequence
5275 // must be trivial.
Richard Smithf8379a02012-01-18 23:55:52 +00005276 SCS = &ICS.UserDefined.After;
5277 break;
5278 case ImplicitConversionSequence::AmbiguousConversion:
5279 case ImplicitConversionSequence::BadConversion:
Richard Smith410cc892014-11-26 03:26:53 +00005280 if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5281 return S.Diag(From->getLocStart(),
5282 diag::err_typecheck_converted_constant_expression)
5283 << From->getType() << From->getSourceRange() << T;
Richard Smithf8379a02012-01-18 23:55:52 +00005284 return ExprError();
5285
5286 case ImplicitConversionSequence::EllipsisConversion:
5287 llvm_unreachable("ellipsis conversion in converted constant expression");
5288 }
5289
Richard Smith410cc892014-11-26 03:26:53 +00005290 // Check that we would only use permitted conversions.
5291 if (!CheckConvertedConstantConversions(S, *SCS)) {
5292 return S.Diag(From->getLocStart(),
5293 diag::err_typecheck_converted_constant_expression_disallowed)
5294 << From->getType() << From->getSourceRange() << T;
5295 }
5296 // [...] and where the reference binding (if any) binds directly.
5297 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5298 return S.Diag(From->getLocStart(),
5299 diag::err_typecheck_converted_constant_expression_indirect)
5300 << From->getType() << From->getSourceRange() << T;
5301 }
5302
5303 ExprResult Result =
5304 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
Richard Smithf8379a02012-01-18 23:55:52 +00005305 if (Result.isInvalid())
5306 return Result;
5307
5308 // Check for a narrowing implicit conversion.
5309 APValue PreNarrowingValue;
Richard Smith5614ca72012-03-23 23:55:39 +00005310 QualType PreNarrowingType;
Richard Smith410cc892014-11-26 03:26:53 +00005311 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
Richard Smith5614ca72012-03-23 23:55:39 +00005312 PreNarrowingType)) {
Richard Smith52e624f2016-12-21 21:42:57 +00005313 case NK_Dependent_Narrowing:
5314 // Implicit conversion to a narrower type, but the expression is
5315 // value-dependent so we can't tell whether it's actually narrowing.
Richard Smithf8379a02012-01-18 23:55:52 +00005316 case NK_Variable_Narrowing:
5317 // Implicit conversion to a narrower type, and the value is not a constant
5318 // expression. We'll diagnose this in a moment.
5319 case NK_Not_Narrowing:
5320 break;
5321
5322 case NK_Constant_Narrowing:
Richard Smith410cc892014-11-26 03:26:53 +00005323 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00005324 << CCE << /*Constant*/1
Richard Smith410cc892014-11-26 03:26:53 +00005325 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
Richard Smithf8379a02012-01-18 23:55:52 +00005326 break;
5327
5328 case NK_Type_Narrowing:
Richard Smith410cc892014-11-26 03:26:53 +00005329 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00005330 << CCE << /*Constant*/0 << From->getType() << T;
5331 break;
5332 }
5333
Richard Smith52e624f2016-12-21 21:42:57 +00005334 if (Result.get()->isValueDependent()) {
5335 Value = APValue();
5336 return Result;
5337 }
5338
Richard Smithf8379a02012-01-18 23:55:52 +00005339 // Check the expression is a constant expression.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005340 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithf8379a02012-01-18 23:55:52 +00005341 Expr::EvalResult Eval;
5342 Eval.Diag = &Notes;
5343
Richard Smith410cc892014-11-26 03:26:53 +00005344 if ((T->isReferenceType()
5345 ? !Result.get()->EvaluateAsLValue(Eval, S.Context)
5346 : !Result.get()->EvaluateAsRValue(Eval, S.Context)) ||
5347 (RequireInt && !Eval.Val.isInt())) {
Richard Smithf8379a02012-01-18 23:55:52 +00005348 // The expression can't be folded, so we can't keep it at this position in
5349 // the AST.
5350 Result = ExprError();
Richard Smith911e1422012-01-30 22:27:01 +00005351 } else {
Richard Smith410cc892014-11-26 03:26:53 +00005352 Value = Eval.Val;
Richard Smith911e1422012-01-30 22:27:01 +00005353
5354 if (Notes.empty()) {
5355 // It's a constant expression.
5356 return Result;
5357 }
Richard Smithf8379a02012-01-18 23:55:52 +00005358 }
5359
5360 // It's not a constant expression. Produce an appropriate diagnostic.
5361 if (Notes.size() == 1 &&
5362 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
Richard Smith410cc892014-11-26 03:26:53 +00005363 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
Richard Smithf8379a02012-01-18 23:55:52 +00005364 else {
Richard Smith410cc892014-11-26 03:26:53 +00005365 S.Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smithf8379a02012-01-18 23:55:52 +00005366 << CCE << From->getSourceRange();
5367 for (unsigned I = 0; I < Notes.size(); ++I)
Richard Smith410cc892014-11-26 03:26:53 +00005368 S.Diag(Notes[I].first, Notes[I].second);
Richard Smithf8379a02012-01-18 23:55:52 +00005369 }
Richard Smith410cc892014-11-26 03:26:53 +00005370 return ExprError();
Richard Smithf8379a02012-01-18 23:55:52 +00005371}
5372
Richard Smith410cc892014-11-26 03:26:53 +00005373ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5374 APValue &Value, CCEKind CCE) {
5375 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5376}
5377
5378ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5379 llvm::APSInt &Value,
5380 CCEKind CCE) {
5381 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5382
5383 APValue V;
5384 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
Richard Smith01bfa682016-12-27 02:02:09 +00005385 if (!R.isInvalid() && !R.get()->isValueDependent())
Richard Smith410cc892014-11-26 03:26:53 +00005386 Value = V.getInt();
5387 return R;
5388}
5389
5390
John McCallfec112d2011-09-09 06:11:02 +00005391/// dropPointerConversions - If the given standard conversion sequence
5392/// involves any pointer conversions, remove them. This may change
5393/// the result type of the conversion sequence.
5394static void dropPointerConversion(StandardConversionSequence &SCS) {
5395 if (SCS.Second == ICK_Pointer_Conversion) {
5396 SCS.Second = ICK_Identity;
5397 SCS.Third = ICK_Identity;
5398 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5399 }
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005400}
John McCall5c32be02010-08-24 20:38:10 +00005401
John McCallfec112d2011-09-09 06:11:02 +00005402/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5403/// convert the expression From to an Objective-C pointer type.
5404static ImplicitConversionSequence
5405TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5406 // Do an implicit conversion to 'id'.
5407 QualType Ty = S.Context.getObjCIdType();
5408 ImplicitConversionSequence ICS
5409 = TryImplicitConversion(S, From, Ty,
5410 // FIXME: Are these flags correct?
5411 /*SuppressUserConversions=*/false,
5412 /*AllowExplicit=*/true,
5413 /*InOverloadResolution=*/false,
5414 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005415 /*AllowObjCWritebackConversion=*/false,
5416 /*AllowObjCConversionOnExplicit=*/true);
John McCallfec112d2011-09-09 06:11:02 +00005417
5418 // Strip off any final conversions to 'id'.
5419 switch (ICS.getKind()) {
5420 case ImplicitConversionSequence::BadConversion:
5421 case ImplicitConversionSequence::AmbiguousConversion:
5422 case ImplicitConversionSequence::EllipsisConversion:
5423 break;
5424
5425 case ImplicitConversionSequence::UserDefinedConversion:
5426 dropPointerConversion(ICS.UserDefined.After);
5427 break;
5428
5429 case ImplicitConversionSequence::StandardConversion:
5430 dropPointerConversion(ICS.Standard);
5431 break;
5432 }
5433
5434 return ICS;
5435}
5436
5437/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5438/// conversion of the expression From to an Objective-C pointer type.
Richard Smithe15a3702016-10-06 23:12:58 +00005439/// Returns a valid but null ExprResult if no conversion sequence exists.
John McCallfec112d2011-09-09 06:11:02 +00005440ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00005441 if (checkPlaceholderForOverload(*this, From))
5442 return ExprError();
5443
John McCall8b07ec22010-05-15 11:32:37 +00005444 QualType Ty = Context.getObjCIdType();
John McCallfec112d2011-09-09 06:11:02 +00005445 ImplicitConversionSequence ICS =
5446 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005447 if (!ICS.isBad())
5448 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
Richard Smithe15a3702016-10-06 23:12:58 +00005449 return ExprResult();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005450}
Douglas Gregor5fb53972009-01-14 15:45:31 +00005451
Richard Smith8dd34252012-02-04 07:07:42 +00005452/// Determine whether the provided type is an integral type, or an enumeration
5453/// type of a permitted flavor.
Richard Smithccc11812013-05-21 19:05:48 +00005454bool Sema::ICEConvertDiagnoser::match(QualType T) {
5455 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5456 : T->isIntegralOrUnscopedEnumerationType();
Richard Smith8dd34252012-02-04 07:07:42 +00005457}
5458
Larisse Voufo236bec22013-06-10 06:50:24 +00005459static ExprResult
5460diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5461 Sema::ContextualImplicitConverter &Converter,
5462 QualType T, UnresolvedSetImpl &ViableConversions) {
5463
5464 if (Converter.Suppress)
5465 return ExprError();
5466
5467 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5468 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5469 CXXConversionDecl *Conv =
5470 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5471 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5472 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5473 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005474 return From;
Larisse Voufo236bec22013-06-10 06:50:24 +00005475}
5476
5477static bool
5478diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5479 Sema::ContextualImplicitConverter &Converter,
5480 QualType T, bool HadMultipleCandidates,
5481 UnresolvedSetImpl &ExplicitConversions) {
5482 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5483 DeclAccessPair Found = ExplicitConversions[0];
5484 CXXConversionDecl *Conversion =
5485 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5486
5487 // The user probably meant to invoke the given explicit
5488 // conversion; use it.
5489 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5490 std::string TypeStr;
5491 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5492
5493 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5494 << FixItHint::CreateInsertion(From->getLocStart(),
5495 "static_cast<" + TypeStr + ">(")
5496 << FixItHint::CreateInsertion(
Alp Tokerb6cc5922014-05-03 03:45:55 +00005497 SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
Larisse Voufo236bec22013-06-10 06:50:24 +00005498 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5499
5500 // If we aren't in a SFINAE context, build a call to the
5501 // explicit conversion function.
5502 if (SemaRef.isSFINAEContext())
5503 return true;
5504
Craig Topperc3ec1492014-05-26 06:22:03 +00005505 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
Larisse Voufo236bec22013-06-10 06:50:24 +00005506 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5507 HadMultipleCandidates);
5508 if (Result.isInvalid())
5509 return true;
5510 // Record usage of conversion in an implicit cast.
5511 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005512 CK_UserDefinedConversion, Result.get(),
5513 nullptr, Result.get()->getValueKind());
Larisse Voufo236bec22013-06-10 06:50:24 +00005514 }
5515 return false;
5516}
5517
5518static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5519 Sema::ContextualImplicitConverter &Converter,
5520 QualType T, bool HadMultipleCandidates,
5521 DeclAccessPair &Found) {
5522 CXXConversionDecl *Conversion =
5523 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00005524 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
Larisse Voufo236bec22013-06-10 06:50:24 +00005525
5526 QualType ToType = Conversion->getConversionType().getNonReferenceType();
5527 if (!Converter.SuppressConversion) {
5528 if (SemaRef.isSFINAEContext())
5529 return true;
5530
5531 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5532 << From->getSourceRange();
5533 }
5534
5535 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5536 HadMultipleCandidates);
5537 if (Result.isInvalid())
5538 return true;
5539 // Record usage of conversion in an implicit cast.
5540 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005541 CK_UserDefinedConversion, Result.get(),
5542 nullptr, Result.get()->getValueKind());
Larisse Voufo236bec22013-06-10 06:50:24 +00005543 return false;
5544}
5545
5546static ExprResult finishContextualImplicitConversion(
5547 Sema &SemaRef, SourceLocation Loc, Expr *From,
5548 Sema::ContextualImplicitConverter &Converter) {
5549 if (!Converter.match(From->getType()) && !Converter.Suppress)
5550 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5551 << From->getSourceRange();
5552
5553 return SemaRef.DefaultLvalueConversion(From);
5554}
5555
5556static void
5557collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5558 UnresolvedSetImpl &ViableConversions,
5559 OverloadCandidateSet &CandidateSet) {
5560 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5561 DeclAccessPair FoundDecl = ViableConversions[I];
5562 NamedDecl *D = FoundDecl.getDecl();
5563 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5564 if (isa<UsingShadowDecl>(D))
5565 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5566
5567 CXXConversionDecl *Conv;
5568 FunctionTemplateDecl *ConvTemplate;
5569 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5570 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5571 else
5572 Conv = cast<CXXConversionDecl>(D);
5573
5574 if (ConvTemplate)
5575 SemaRef.AddTemplateConversionCandidate(
Douglas Gregor4b60a152013-11-07 22:34:54 +00005576 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5577 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005578 else
5579 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005580 ToType, CandidateSet,
5581 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005582 }
5583}
5584
Richard Smithccc11812013-05-21 19:05:48 +00005585/// \brief Attempt to convert the given expression to a type which is accepted
5586/// by the given converter.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005587///
Richard Smithccc11812013-05-21 19:05:48 +00005588/// This routine will attempt to convert an expression of class type to a
5589/// type accepted by the specified converter. In C++11 and before, the class
5590/// must have a single non-explicit conversion function converting to a matching
5591/// type. In C++1y, there can be multiple such conversion functions, but only
5592/// one target type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005593///
Douglas Gregor4799d032010-06-30 00:20:43 +00005594/// \param Loc The source location of the construct that requires the
5595/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005596///
James Dennett18348b62012-06-22 08:52:37 +00005597/// \param From The expression we're converting from.
Douglas Gregor4799d032010-06-30 00:20:43 +00005598///
Richard Smithccc11812013-05-21 19:05:48 +00005599/// \param Converter Used to control and diagnose the conversion process.
Richard Smith8dd34252012-02-04 07:07:42 +00005600///
Douglas Gregor4799d032010-06-30 00:20:43 +00005601/// \returns The expression, converted to an integral or enumeration type if
5602/// successful.
Richard Smithccc11812013-05-21 19:05:48 +00005603ExprResult Sema::PerformContextualImplicitConversion(
5604 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005605 // We can't perform any more checking for type-dependent expressions.
5606 if (From->isTypeDependent())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005607 return From;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005608
Eli Friedman1da70392012-01-26 00:26:18 +00005609 // Process placeholders immediately.
5610 if (From->hasPlaceholderType()) {
5611 ExprResult result = CheckPlaceholderExpr(From);
Larisse Voufo236bec22013-06-10 06:50:24 +00005612 if (result.isInvalid())
5613 return result;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005614 From = result.get();
Eli Friedman1da70392012-01-26 00:26:18 +00005615 }
5616
Richard Smithccc11812013-05-21 19:05:48 +00005617 // If the expression already has a matching type, we're golden.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005618 QualType T = From->getType();
Richard Smithccc11812013-05-21 19:05:48 +00005619 if (Converter.match(T))
Eli Friedman1da70392012-01-26 00:26:18 +00005620 return DefaultLvalueConversion(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005621
5622 // FIXME: Check for missing '()' if T is a function type?
5623
Richard Smithccc11812013-05-21 19:05:48 +00005624 // We can only perform contextual implicit conversions on objects of class
5625 // type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005626 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikiebbafb8a2012-03-11 07:00:24 +00005627 if (!RecordTy || !getLangOpts().CPlusPlus) {
Richard Smithccc11812013-05-21 19:05:48 +00005628 if (!Converter.Suppress)
5629 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005630 return From;
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005631 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005632
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005633 // We must have a complete class type.
Douglas Gregora6c5abb2012-05-04 16:48:41 +00005634 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
Richard Smithccc11812013-05-21 19:05:48 +00005635 ContextualImplicitConverter &Converter;
Douglas Gregore2b37442012-05-04 22:38:52 +00005636 Expr *From;
Richard Smithccc11812013-05-21 19:05:48 +00005637
5638 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
Richard Smithdb0ac552015-12-18 22:40:25 +00005639 : Converter(Converter), From(From) {}
Richard Smithccc11812013-05-21 19:05:48 +00005640
Craig Toppere14c0f82014-03-12 04:55:44 +00005641 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00005642 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005643 }
Richard Smithccc11812013-05-21 19:05:48 +00005644 } IncompleteDiagnoser(Converter, From);
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005645
Richard Smithdb0ac552015-12-18 22:40:25 +00005646 if (Converter.Suppress ? !isCompleteType(Loc, T)
5647 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005648 return From;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005649
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005650 // Look for a conversion to an integral or enumeration type.
Larisse Voufo236bec22013-06-10 06:50:24 +00005651 UnresolvedSet<4>
5652 ViableConversions; // These are *potentially* viable in C++1y.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005653 UnresolvedSet<4> ExplicitConversions;
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005654 const auto &Conversions =
Larisse Voufo236bec22013-06-10 06:50:24 +00005655 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005656
Larisse Voufo236bec22013-06-10 06:50:24 +00005657 bool HadMultipleCandidates =
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005658 (std::distance(Conversions.begin(), Conversions.end()) > 1);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005659
Larisse Voufo236bec22013-06-10 06:50:24 +00005660 // To check that there is only one target type, in C++1y:
5661 QualType ToType;
5662 bool HasUniqueTargetType = true;
5663
5664 // Collect explicit or viable (potentially in C++1y) conversions.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005665 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005666 NamedDecl *D = (*I)->getUnderlyingDecl();
5667 CXXConversionDecl *Conversion;
5668 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5669 if (ConvTemplate) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005670 if (getLangOpts().CPlusPlus14)
Larisse Voufo236bec22013-06-10 06:50:24 +00005671 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5672 else
5673 continue; // C++11 does not consider conversion operator templates(?).
5674 } else
5675 Conversion = cast<CXXConversionDecl>(D);
5676
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005677 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
Larisse Voufo236bec22013-06-10 06:50:24 +00005678 "Conversion operator templates are considered potentially "
5679 "viable in C++1y");
5680
5681 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5682 if (Converter.match(CurToType) || ConvTemplate) {
5683
5684 if (Conversion->isExplicit()) {
5685 // FIXME: For C++1y, do we need this restriction?
5686 // cf. diagnoseNoViableConversion()
5687 if (!ConvTemplate)
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005688 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
Larisse Voufo236bec22013-06-10 06:50:24 +00005689 } else {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005690 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005691 if (ToType.isNull())
5692 ToType = CurToType.getUnqualifiedType();
5693 else if (HasUniqueTargetType &&
5694 (CurToType.getUnqualifiedType() != ToType))
5695 HasUniqueTargetType = false;
5696 }
5697 ViableConversions.addDecl(I.getDecl(), I.getAccess());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005698 }
Richard Smith8dd34252012-02-04 07:07:42 +00005699 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005700 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005701
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005702 if (getLangOpts().CPlusPlus14) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005703 // C++1y [conv]p6:
5704 // ... An expression e of class type E appearing in such a context
5705 // is said to be contextually implicitly converted to a specified
5706 // type T and is well-formed if and only if e can be implicitly
5707 // converted to a type T that is determined as follows: E is searched
Larisse Voufo67170bd2013-06-10 08:25:58 +00005708 // for conversion functions whose return type is cv T or reference to
5709 // cv T such that T is allowed by the context. There shall be
Larisse Voufo236bec22013-06-10 06:50:24 +00005710 // exactly one such T.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005711
Larisse Voufo236bec22013-06-10 06:50:24 +00005712 // If no unique T is found:
5713 if (ToType.isNull()) {
5714 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5715 HadMultipleCandidates,
5716 ExplicitConversions))
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005717 return ExprError();
Larisse Voufo236bec22013-06-10 06:50:24 +00005718 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005719 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005720
Larisse Voufo236bec22013-06-10 06:50:24 +00005721 // If more than one unique Ts are found:
5722 if (!HasUniqueTargetType)
5723 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5724 ViableConversions);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005725
Larisse Voufo236bec22013-06-10 06:50:24 +00005726 // If one unique T is found:
5727 // First, build a candidate set from the previously recorded
5728 // potentially viable conversions.
Richard Smith100b24a2014-04-17 01:52:14 +00005729 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Larisse Voufo236bec22013-06-10 06:50:24 +00005730 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5731 CandidateSet);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005732
Larisse Voufo236bec22013-06-10 06:50:24 +00005733 // Then, perform overload resolution over the candidate set.
5734 OverloadCandidateSet::iterator Best;
5735 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5736 case OR_Success: {
5737 // Apply this conversion.
5738 DeclAccessPair Found =
5739 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5740 if (recordConversion(*this, Loc, From, Converter, T,
5741 HadMultipleCandidates, Found))
5742 return ExprError();
5743 break;
5744 }
5745 case OR_Ambiguous:
5746 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5747 ViableConversions);
5748 case OR_No_Viable_Function:
5749 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5750 HadMultipleCandidates,
5751 ExplicitConversions))
5752 return ExprError();
5753 // fall through 'OR_Deleted' case.
5754 case OR_Deleted:
5755 // We'll complain below about a non-integral condition type.
5756 break;
5757 }
5758 } else {
5759 switch (ViableConversions.size()) {
5760 case 0: {
5761 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5762 HadMultipleCandidates,
5763 ExplicitConversions))
Douglas Gregor4799d032010-06-30 00:20:43 +00005764 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005765
Larisse Voufo236bec22013-06-10 06:50:24 +00005766 // We'll complain below about a non-integral condition type.
5767 break;
Douglas Gregor4799d032010-06-30 00:20:43 +00005768 }
Larisse Voufo236bec22013-06-10 06:50:24 +00005769 case 1: {
5770 // Apply this conversion.
5771 DeclAccessPair Found = ViableConversions[0];
5772 if (recordConversion(*this, Loc, From, Converter, T,
5773 HadMultipleCandidates, Found))
5774 return ExprError();
5775 break;
5776 }
5777 default:
5778 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5779 ViableConversions);
5780 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005781 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005782
Larisse Voufo236bec22013-06-10 06:50:24 +00005783 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005784}
5785
Richard Smith100b24a2014-04-17 01:52:14 +00005786/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5787/// an acceptable non-member overloaded operator for a call whose
5788/// arguments have types T1 (and, if non-empty, T2). This routine
5789/// implements the check in C++ [over.match.oper]p3b2 concerning
5790/// enumeration types.
5791static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5792 FunctionDecl *Fn,
5793 ArrayRef<Expr *> Args) {
5794 QualType T1 = Args[0]->getType();
5795 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5796
5797 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5798 return true;
5799
5800 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5801 return true;
5802
5803 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5804 if (Proto->getNumParams() < 1)
5805 return false;
5806
5807 if (T1->isEnumeralType()) {
5808 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5809 if (Context.hasSameUnqualifiedType(T1, ArgType))
5810 return true;
5811 }
5812
5813 if (Proto->getNumParams() < 2)
5814 return false;
5815
5816 if (!T2.isNull() && T2->isEnumeralType()) {
5817 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5818 if (Context.hasSameUnqualifiedType(T2, ArgType))
5819 return true;
5820 }
5821
5822 return false;
5823}
5824
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005825/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00005826/// candidate functions, using the given function call arguments. If
5827/// @p SuppressUserConversions, then don't allow user-defined
5828/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00005829///
James Dennett2a4d13c2012-06-15 07:13:21 +00005830/// \param PartialOverloading true if we are performing "partial" overloading
Douglas Gregorcabea402009-09-22 15:41:20 +00005831/// based on an incomplete set of function arguments. This feature is used by
5832/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00005833void
5834Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00005835 DeclAccessPair FoundDecl,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005836 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005837 OverloadCandidateSet &CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00005838 bool SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005839 bool PartialOverloading,
5840 bool AllowExplicit) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005841 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00005842 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005843 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00005844 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005845 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00005846
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005847 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005848 if (!isa<CXXConstructorDecl>(Method)) {
5849 // If we get here, it's because we're calling a member function
5850 // that is named without a member access expression (e.g.,
5851 // "this->f") that was either written explicitly or created
5852 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00005853 // function, e.g., X::f(). We use an empty type for the implied
5854 // object argument (C++ [over.call.func]p3), and the acting context
5855 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00005856 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005857 QualType(), Expr::Classification::makeSimpleLValue(),
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005858 Args, CandidateSet, SuppressUserConversions,
5859 PartialOverloading);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005860 return;
5861 }
5862 // We treat a constructor like a non-member function, since its object
5863 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005864 }
5865
Douglas Gregorff7028a2009-11-13 23:59:09 +00005866 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005867 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00005868
Richard Smith100b24a2014-04-17 01:52:14 +00005869 // C++ [over.match.oper]p3:
5870 // if no operand has a class type, only those non-member functions in the
5871 // lookup set that have a first parameter of type T1 or "reference to
5872 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5873 // is a right operand) a second parameter of type T2 or "reference to
5874 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
5875 // candidate functions.
5876 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5877 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5878 return;
5879
Richard Smith8b86f2d2013-11-04 01:48:18 +00005880 // C++11 [class.copy]p11: [DR1402]
5881 // A defaulted move constructor that is defined as deleted is ignored by
5882 // overload resolution.
5883 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5884 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5885 Constructor->isMoveConstructor())
5886 return;
5887
Douglas Gregor27381f32009-11-23 12:27:39 +00005888 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005889 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005890
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005891 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005892 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCalla0296f72010-03-19 07:35:19 +00005893 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005894 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005895 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005896 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005897 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005898 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005899
John McCall578a1f82014-12-14 01:46:53 +00005900 if (Constructor) {
5901 // C++ [class.copy]p3:
5902 // A member function template is never instantiated to perform the copy
5903 // of a class object to an object of its class type.
5904 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
Richard Smith0f59cb32015-12-18 21:45:41 +00005905 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
John McCall578a1f82014-12-14 01:46:53 +00005906 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00005907 IsDerivedFrom(Args[0]->getLocStart(), Args[0]->getType(),
5908 ClassType))) {
John McCall578a1f82014-12-14 01:46:53 +00005909 Candidate.Viable = false;
5910 Candidate.FailureKind = ovl_fail_illegal_constructor;
5911 return;
5912 }
5913 }
5914
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005915 unsigned NumParams = Proto->getNumParams();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005916
5917 // (C++ 13.3.2p2): A candidate function having fewer than m
5918 // parameters is viable only if it has an ellipsis in its parameter
5919 // list (8.3.5).
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005920 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
Douglas Gregor2a920012009-09-23 14:56:09 +00005921 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005922 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005923 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005924 return;
5925 }
5926
5927 // (C++ 13.3.2p2): A candidate function having more than m parameters
5928 // is viable only if the (m+1)st parameter has a default argument
5929 // (8.3.6). For the purposes of overload resolution, the
5930 // parameter list is truncated on the right, so that there are
5931 // exactly m parameters.
5932 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005933 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005934 // Not enough arguments.
5935 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005936 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005937 return;
5938 }
5939
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005940 // (CUDA B.1): Check for invalid calls between targets.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005941 if (getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005942 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
Eli Bendersky9a220fc2014-09-29 20:38:29 +00005943 // Skip the check for callers that are implicit members, because in this
5944 // case we may not yet know what the member's target is; the target is
5945 // inferred for the member automatically, based on the bases and fields of
5946 // the class.
Justin Lebarb0080032016-08-10 01:09:11 +00005947 if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005948 Candidate.Viable = false;
5949 Candidate.FailureKind = ovl_fail_bad_target;
5950 return;
5951 }
5952
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005953 // Determine the implicit conversion sequences for each of the
5954 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005955 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005956 if (ArgIdx < NumParams) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005957 // (C++ 13.3.2p3): for F to be a viable function, there shall
5958 // exist for each argument an implicit conversion sequence
5959 // (13.3.3.1) that converts that argument to the corresponding
5960 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00005961 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005962 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005963 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005964 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00005965 /*InOverloadResolution=*/true,
5966 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005967 getLangOpts().ObjCAutoRefCount,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005968 AllowExplicit);
John McCall0d1da222010-01-12 00:44:57 +00005969 if (Candidate.Conversions[ArgIdx].isBad()) {
5970 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005971 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005972 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00005973 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005974 } else {
5975 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5976 // argument for which there is no corresponding parameter is
5977 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005978 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005979 }
5980 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005981
5982 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
5983 Candidate.Viable = false;
5984 Candidate.FailureKind = ovl_fail_enable_if;
5985 Candidate.DeductionFailure.Data = FailedAttr;
5986 return;
5987 }
Yaxun Liu5b746652016-12-18 05:18:55 +00005988
5989 if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) {
5990 Candidate.Viable = false;
5991 Candidate.FailureKind = ovl_fail_ext_disabled;
5992 return;
5993 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005994}
5995
Manman Rend2a3cd72016-04-07 19:30:20 +00005996ObjCMethodDecl *
5997Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
5998 SmallVectorImpl<ObjCMethodDecl *> &Methods) {
5999 if (Methods.size() <= 1)
Fariborz Jahanian0ded4242014-08-13 21:24:14 +00006000 return nullptr;
Manman Rend2a3cd72016-04-07 19:30:20 +00006001
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006002 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6003 bool Match = true;
6004 ObjCMethodDecl *Method = Methods[b];
6005 unsigned NumNamedArgs = Sel.getNumArgs();
6006 // Method might have more arguments than selector indicates. This is due
6007 // to addition of c-style arguments in method.
6008 if (Method->param_size() > NumNamedArgs)
6009 NumNamedArgs = Method->param_size();
6010 if (Args.size() < NumNamedArgs)
6011 continue;
6012
6013 for (unsigned i = 0; i < NumNamedArgs; i++) {
6014 // We can't do any type-checking on a type-dependent argument.
6015 if (Args[i]->isTypeDependent()) {
6016 Match = false;
6017 break;
6018 }
6019
6020 ParmVarDecl *param = Method->parameters()[i];
6021 Expr *argExpr = Args[i];
6022 assert(argExpr && "SelectBestMethod(): missing expression");
6023
6024 // Strip the unbridged-cast placeholder expression off unless it's
6025 // a consumed argument.
6026 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
6027 !param->hasAttr<CFConsumedAttr>())
6028 argExpr = stripARCUnbridgedCast(argExpr);
6029
6030 // If the parameter is __unknown_anytype, move on to the next method.
6031 if (param->getType() == Context.UnknownAnyTy) {
6032 Match = false;
6033 break;
6034 }
George Burgess IV45461812015-10-11 20:13:20 +00006035
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006036 ImplicitConversionSequence ConversionState
6037 = TryCopyInitialization(*this, argExpr, param->getType(),
6038 /*SuppressUserConversions*/false,
6039 /*InOverloadResolution=*/true,
6040 /*AllowObjCWritebackConversion=*/
6041 getLangOpts().ObjCAutoRefCount,
6042 /*AllowExplicit*/false);
George Burgess IV2099b542016-09-02 22:59:57 +00006043 // This function looks for a reasonably-exact match, so we consider
6044 // incompatible pointer conversions to be a failure here.
6045 if (ConversionState.isBad() ||
6046 (ConversionState.isStandard() &&
6047 ConversionState.Standard.Second ==
6048 ICK_Incompatible_Pointer_Conversion)) {
6049 Match = false;
6050 break;
6051 }
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006052 }
6053 // Promote additional arguments to variadic methods.
6054 if (Match && Method->isVariadic()) {
6055 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6056 if (Args[i]->isTypeDependent()) {
6057 Match = false;
6058 break;
6059 }
6060 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6061 nullptr);
6062 if (Arg.isInvalid()) {
6063 Match = false;
6064 break;
6065 }
6066 }
Fariborz Jahanian180d76b2014-08-27 16:38:47 +00006067 } else {
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006068 // Check for extra arguments to non-variadic methods.
6069 if (Args.size() != NumNamedArgs)
6070 Match = false;
Fariborz Jahanian180d76b2014-08-27 16:38:47 +00006071 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6072 // Special case when selectors have no argument. In this case, select
6073 // one with the most general result type of 'id'.
6074 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6075 QualType ReturnT = Methods[b]->getReturnType();
6076 if (ReturnT->isObjCIdType())
6077 return Methods[b];
6078 }
6079 }
6080 }
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006081
6082 if (Match)
6083 return Method;
6084 }
6085 return nullptr;
6086}
6087
George Burgess IV2a6150d2015-10-16 01:17:38 +00006088// specific_attr_iterator iterates over enable_if attributes in reverse, and
6089// enable_if is order-sensitive. As a result, we need to reverse things
6090// sometimes. Size of 4 elements is arbitrary.
6091static SmallVector<EnableIfAttr *, 4>
6092getOrderedEnableIfAttrs(const FunctionDecl *Function) {
6093 SmallVector<EnableIfAttr *, 4> Result;
6094 if (!Function->hasAttrs())
6095 return Result;
6096
6097 const auto &FuncAttrs = Function->getAttrs();
6098 for (Attr *Attr : FuncAttrs)
6099 if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr))
6100 Result.push_back(EnableIf);
6101
6102 std::reverse(Result.begin(), Result.end());
6103 return Result;
6104}
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006105
6106EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
6107 bool MissingImplicitThis) {
George Burgess IV2a6150d2015-10-16 01:17:38 +00006108 auto EnableIfAttrs = getOrderedEnableIfAttrs(Function);
6109 if (EnableIfAttrs.empty())
Craig Topperc3ec1492014-05-26 06:22:03 +00006110 return nullptr;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006111
6112 SFINAETrap Trap(*this);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006113 SmallVector<Expr *, 16> ConvertedArgs;
6114 bool InitializationFailed = false;
Nick Lewyckye283c552015-08-25 22:33:16 +00006115
George Burgess IV458b3f32016-08-12 04:19:35 +00006116 // Ignore any variadic arguments. Converting them is pointless, since the
George Burgess IV53b938d2016-08-12 04:12:31 +00006117 // user can't refer to them in the enable_if condition.
6118 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6119
Nick Lewyckye283c552015-08-25 22:33:16 +00006120 // Convert the arguments.
George Burgess IV53b938d2016-08-12 04:12:31 +00006121 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
George Burgess IVe96abf72016-02-24 22:31:14 +00006122 ExprResult R;
6123 if (I == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) &&
Nick Lewyckyb8336b72014-02-28 05:26:13 +00006124 !cast<CXXMethodDecl>(Function)->isStatic() &&
6125 !isa<CXXConstructorDecl>(Function)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006126 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
George Burgess IVe96abf72016-02-24 22:31:14 +00006127 R = PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
6128 Method, Method);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006129 } else {
George Burgess IVe96abf72016-02-24 22:31:14 +00006130 R = PerformCopyInitialization(InitializedEntity::InitializeParameter(
6131 Context, Function->getParamDecl(I)),
6132 SourceLocation(), Args[I]);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006133 }
George Burgess IVe96abf72016-02-24 22:31:14 +00006134
6135 if (R.isInvalid()) {
6136 InitializationFailed = true;
6137 break;
6138 }
6139
George Burgess IVe96abf72016-02-24 22:31:14 +00006140 ConvertedArgs.push_back(R.get());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006141 }
6142
6143 if (InitializationFailed || Trap.hasErrorOccurred())
George Burgess IV2a6150d2015-10-16 01:17:38 +00006144 return EnableIfAttrs[0];
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006145
Nick Lewyckye283c552015-08-25 22:33:16 +00006146 // Push default arguments if needed.
6147 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6148 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6149 ParmVarDecl *P = Function->getParamDecl(i);
6150 ExprResult R = PerformCopyInitialization(
6151 InitializedEntity::InitializeParameter(Context,
6152 Function->getParamDecl(i)),
6153 SourceLocation(),
6154 P->hasUninstantiatedDefaultArg() ? P->getUninstantiatedDefaultArg()
6155 : P->getDefaultArg());
6156 if (R.isInvalid()) {
6157 InitializationFailed = true;
6158 break;
6159 }
Nick Lewyckye283c552015-08-25 22:33:16 +00006160 ConvertedArgs.push_back(R.get());
6161 }
6162
6163 if (InitializationFailed || Trap.hasErrorOccurred())
George Burgess IV2a6150d2015-10-16 01:17:38 +00006164 return EnableIfAttrs[0];
Nick Lewyckye283c552015-08-25 22:33:16 +00006165 }
6166
George Burgess IV2a6150d2015-10-16 01:17:38 +00006167 for (auto *EIA : EnableIfAttrs) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006168 APValue Result;
George Burgess IVe8f10cc2016-05-11 01:38:27 +00006169 // FIXME: This doesn't consider value-dependent cases, because doing so is
6170 // very difficult. Ideally, we should handle them more gracefully.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006171 if (!EIA->getCond()->EvaluateWithSubstitution(
George Burgess IVe8f10cc2016-05-11 01:38:27 +00006172 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006173 return EIA;
George Burgess IVe8f10cc2016-05-11 01:38:27 +00006174
6175 if (!Result.isInt() || !Result.getInt().getBoolValue())
6176 return EIA;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006177 }
Craig Topperc3ec1492014-05-26 06:22:03 +00006178 return nullptr;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006179}
6180
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006181/// \brief Add all of the function declarations in the given function set to
Nick Lewyckyed4265c2013-09-22 10:06:01 +00006182/// the overload candidate set.
John McCall4c4c1df2010-01-26 03:27:55 +00006183void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006184 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006185 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006186 TemplateArgumentListInfo *ExplicitTemplateArgs,
Richard Smithbcc22fc2012-03-09 08:00:36 +00006187 bool SuppressUserConversions,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006188 bool PartialOverloading) {
John McCall4c4c1df2010-01-26 03:27:55 +00006189 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00006190 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6191 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006192 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00006193 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00006194 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00006195 Args[0]->getType(), Args[0]->Classify(Context),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006196 Args.slice(1), CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006197 SuppressUserConversions, PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006198 else
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006199 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006200 SuppressUserConversions, PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006201 } else {
John McCalla0296f72010-03-19 07:35:19 +00006202 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006203 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
6204 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00006205 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00006206 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Richard Smithbcc22fc2012-03-09 08:00:36 +00006207 ExplicitTemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006208 Args[0]->getType(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006209 Args[0]->Classify(Context), Args.slice(1),
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006210 CandidateSet, SuppressUserConversions,
6211 PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006212 else
John McCalla0296f72010-03-19 07:35:19 +00006213 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smithbcc22fc2012-03-09 08:00:36 +00006214 ExplicitTemplateArgs, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006215 CandidateSet, SuppressUserConversions,
6216 PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006217 }
Douglas Gregor15448f82009-06-27 21:05:07 +00006218 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006219}
6220
John McCallf0f1cf02009-11-17 07:50:12 +00006221/// AddMethodCandidate - Adds a named decl (which is some kind of
6222/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00006223void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006224 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006225 Expr::Classification ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00006226 ArrayRef<Expr *> Args,
John McCallf0f1cf02009-11-17 07:50:12 +00006227 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006228 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00006229 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00006230 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00006231
6232 if (isa<UsingShadowDecl>(Decl))
6233 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006234
John McCallf0f1cf02009-11-17 07:50:12 +00006235 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6236 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6237 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00006238 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
Craig Topperc3ec1492014-05-26 06:22:03 +00006239 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006240 ObjectType, ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00006241 Args, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006242 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00006243 } else {
John McCalla0296f72010-03-19 07:35:19 +00006244 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006245 ObjectType, ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00006246 Args,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006247 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00006248 }
6249}
6250
Douglas Gregor436424c2008-11-18 23:14:02 +00006251/// AddMethodCandidate - Adds the given C++ member function to the set
6252/// of candidate functions, using the given function call arguments
6253/// and the object argument (@c Object). For example, in a call
6254/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6255/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6256/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00006257/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00006258void
John McCalla0296f72010-03-19 07:35:19 +00006259Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00006260 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006261 Expr::Classification ObjectClassification,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006262 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006263 OverloadCandidateSet &CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006264 bool SuppressUserConversions,
6265 bool PartialOverloading) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006266 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00006267 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00006268 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00006269 assert(!isa<CXXConstructorDecl>(Method) &&
6270 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00006271
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006272 if (!CandidateSet.isNewCandidate(Method))
6273 return;
6274
Richard Smith8b86f2d2013-11-04 01:48:18 +00006275 // C++11 [class.copy]p23: [DR1402]
6276 // A defaulted move assignment operator that is defined as deleted is
6277 // ignored by overload resolution.
6278 if (Method->isDefaulted() && Method->isDeleted() &&
6279 Method->isMoveAssignmentOperator())
6280 return;
6281
Douglas Gregor27381f32009-11-23 12:27:39 +00006282 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006283 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006284
Douglas Gregor436424c2008-11-18 23:14:02 +00006285 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006286 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00006287 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00006288 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006289 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006290 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006291 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor436424c2008-11-18 23:14:02 +00006292
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006293 unsigned NumParams = Proto->getNumParams();
Douglas Gregor436424c2008-11-18 23:14:02 +00006294
6295 // (C++ 13.3.2p2): A candidate function having fewer than m
6296 // parameters is viable only if it has an ellipsis in its parameter
6297 // list (8.3.5).
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006298 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6299 !Proto->isVariadic()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006300 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006301 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00006302 return;
6303 }
6304
6305 // (C++ 13.3.2p2): A candidate function having more than m parameters
6306 // is viable only if the (m+1)st parameter has a default argument
6307 // (8.3.6). For the purposes of overload resolution, the
6308 // parameter list is truncated on the right, so that there are
6309 // exactly m parameters.
6310 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006311 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006312 // Not enough arguments.
6313 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006314 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00006315 return;
6316 }
6317
6318 Candidate.Viable = true;
Douglas Gregor436424c2008-11-18 23:14:02 +00006319
John McCall6e9f8f62009-12-03 04:06:58 +00006320 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006321 // The implicit object argument is ignored.
6322 Candidate.IgnoreObjectArgument = true;
6323 else {
6324 // Determine the implicit conversion sequence for the object
6325 // parameter.
Richard Smith0f59cb32015-12-18 21:45:41 +00006326 Candidate.Conversions[0] = TryObjectArgumentInitialization(
6327 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6328 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00006329 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006330 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006331 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006332 return;
6333 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006334 }
6335
Eli Bendersky291a57e2014-09-25 23:59:08 +00006336 // (CUDA B.1): Check for invalid calls between targets.
6337 if (getLangOpts().CUDA)
6338 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
Justin Lebarb0080032016-08-10 01:09:11 +00006339 if (!IsAllowedCUDACall(Caller, Method)) {
Eli Bendersky291a57e2014-09-25 23:59:08 +00006340 Candidate.Viable = false;
6341 Candidate.FailureKind = ovl_fail_bad_target;
6342 return;
6343 }
6344
Douglas Gregor436424c2008-11-18 23:14:02 +00006345 // Determine the implicit conversion sequences for each of the
6346 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006347 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006348 if (ArgIdx < NumParams) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006349 // (C++ 13.3.2p3): for F to be a viable function, there shall
6350 // exist for each argument an implicit conversion sequence
6351 // (13.3.3.1) that converts that argument to the corresponding
6352 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00006353 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00006354 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006355 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006356 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00006357 /*InOverloadResolution=*/true,
6358 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006359 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00006360 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006361 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006362 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006363 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00006364 }
6365 } else {
6366 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6367 // argument for which there is no corresponding parameter is
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006368 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006369 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00006370 }
6371 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006372
6373 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6374 Candidate.Viable = false;
6375 Candidate.FailureKind = ovl_fail_enable_if;
6376 Candidate.DeductionFailure.Data = FailedAttr;
6377 return;
6378 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006379}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006380
Douglas Gregor97628d62009-08-21 00:16:32 +00006381/// \brief Add a C++ member function template as a candidate to the candidate
6382/// set, using template argument deduction to produce an appropriate member
6383/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00006384void
Douglas Gregor97628d62009-08-21 00:16:32 +00006385Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00006386 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006387 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006388 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006389 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006390 Expr::Classification ObjectClassification,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006391 ArrayRef<Expr *> Args,
Douglas Gregor97628d62009-08-21 00:16:32 +00006392 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006393 bool SuppressUserConversions,
6394 bool PartialOverloading) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006395 if (!CandidateSet.isNewCandidate(MethodTmpl))
6396 return;
6397
Douglas Gregor97628d62009-08-21 00:16:32 +00006398 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00006399 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00006400 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00006401 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00006402 // candidate functions in the usual way.113) A given name can refer to one
6403 // or more function templates and also to a set of overloaded non-template
6404 // functions. In such a case, the candidate functions generated from each
6405 // function template are combined with the set of non-template candidate
6406 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00006407 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006408 FunctionDecl *Specialization = nullptr;
Douglas Gregor97628d62009-08-21 00:16:32 +00006409 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006410 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006411 Specialization, Info, PartialOverloading)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006412 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006413 Candidate.FoundDecl = FoundDecl;
6414 Candidate.Function = MethodTmpl->getTemplatedDecl();
6415 Candidate.Viable = false;
6416 Candidate.FailureKind = ovl_fail_bad_deduction;
6417 Candidate.IsSurrogate = false;
6418 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006419 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006420 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006421 Info);
6422 return;
6423 }
Mike Stump11289f42009-09-09 15:08:12 +00006424
Douglas Gregor97628d62009-08-21 00:16:32 +00006425 // Add the function template specialization produced by template argument
6426 // deduction as a candidate.
6427 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00006428 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00006429 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00006430 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006431 ActingContext, ObjectType, ObjectClassification, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006432 CandidateSet, SuppressUserConversions, PartialOverloading);
Douglas Gregor97628d62009-08-21 00:16:32 +00006433}
6434
Douglas Gregor05155d82009-08-21 23:19:43 +00006435/// \brief Add a C++ function template specialization as a candidate
6436/// in the candidate set, using template argument deduction to produce
6437/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00006438void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006439Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00006440 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006441 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006442 ArrayRef<Expr *> Args,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006443 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006444 bool SuppressUserConversions,
6445 bool PartialOverloading) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006446 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6447 return;
6448
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006449 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00006450 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006451 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00006452 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006453 // candidate functions in the usual way.113) A given name can refer to one
6454 // or more function templates and also to a set of overloaded non-template
6455 // functions. In such a case, the candidate functions generated from each
6456 // function template are combined with the set of non-template candidate
6457 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00006458 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006459 FunctionDecl *Specialization = nullptr;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006460 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006461 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006462 Specialization, Info, PartialOverloading)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006463 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCalla0296f72010-03-19 07:35:19 +00006464 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00006465 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6466 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006467 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00006468 Candidate.IsSurrogate = false;
6469 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006470 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006471 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006472 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006473 return;
6474 }
Mike Stump11289f42009-09-09 15:08:12 +00006475
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006476 // Add the function template specialization produced by template argument
6477 // deduction as a candidate.
6478 assert(Specialization && "Missing function template specialization?");
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006479 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006480 SuppressUserConversions, PartialOverloading);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006481}
Mike Stump11289f42009-09-09 15:08:12 +00006482
Douglas Gregor4b60a152013-11-07 22:34:54 +00006483/// Determine whether this is an allowable conversion from the result
6484/// of an explicit conversion operator to the expected type, per C++
6485/// [over.match.conv]p1 and [over.match.ref]p1.
6486///
6487/// \param ConvType The return type of the conversion function.
6488///
6489/// \param ToType The type we are converting to.
6490///
6491/// \param AllowObjCPointerConversion Allow a conversion from one
6492/// Objective-C pointer to another.
6493///
6494/// \returns true if the conversion is allowable, false otherwise.
6495static bool isAllowableExplicitConversion(Sema &S,
6496 QualType ConvType, QualType ToType,
6497 bool AllowObjCPointerConversion) {
6498 QualType ToNonRefType = ToType.getNonReferenceType();
6499
6500 // Easy case: the types are the same.
6501 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6502 return true;
6503
6504 // Allow qualification conversions.
6505 bool ObjCLifetimeConversion;
6506 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6507 ObjCLifetimeConversion))
6508 return true;
6509
6510 // If we're not allowed to consider Objective-C pointer conversions,
6511 // we're done.
6512 if (!AllowObjCPointerConversion)
6513 return false;
6514
6515 // Is this an Objective-C pointer conversion?
6516 bool IncompatibleObjC = false;
6517 QualType ConvertedType;
6518 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6519 IncompatibleObjC);
6520}
6521
Douglas Gregora1f013e2008-11-07 22:36:19 +00006522/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00006523/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00006524/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00006525/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00006526/// (which may or may not be the same type as the type that the
6527/// conversion function produces).
6528void
6529Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006530 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006531 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00006532 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006533 OverloadCandidateSet& CandidateSet,
6534 bool AllowObjCConversionOnExplicit) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006535 assert(!Conversion->getDescribedFunctionTemplate() &&
6536 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00006537 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006538 if (!CandidateSet.isNewCandidate(Conversion))
6539 return;
6540
Richard Smith2a7d4812013-05-04 07:00:32 +00006541 // If the conversion function has an undeduced return type, trigger its
6542 // deduction now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006543 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00006544 if (DeduceReturnType(Conversion, From->getExprLoc()))
6545 return;
6546 ConvType = Conversion->getConversionType().getNonReferenceType();
6547 }
6548
Richard Smith089c3162013-09-21 21:55:46 +00006549 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6550 // operator is only a candidate if its return type is the target type or
6551 // can be converted to the target type with a qualification conversion.
Douglas Gregor4b60a152013-11-07 22:34:54 +00006552 if (Conversion->isExplicit() &&
6553 !isAllowableExplicitConversion(*this, ConvType, ToType,
6554 AllowObjCConversionOnExplicit))
Richard Smith089c3162013-09-21 21:55:46 +00006555 return;
6556
Douglas Gregor27381f32009-11-23 12:27:39 +00006557 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006558 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006559
Douglas Gregora1f013e2008-11-07 22:36:19 +00006560 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006561 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCalla0296f72010-03-19 07:35:19 +00006562 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006563 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006564 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006565 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006566 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00006567 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00006568 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00006569 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006570 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006571
Douglas Gregor6affc782010-08-19 15:37:02 +00006572 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006573 // For conversion functions, the function is considered to be a member of
6574 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00006575 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006576 //
6577 // Determine the implicit conversion sequence for the implicit
6578 // object parameter.
6579 QualType ImplicitParamType = From->getType();
6580 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6581 ImplicitParamType = FromPtrType->getPointeeType();
6582 CXXRecordDecl *ConversionContext
6583 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006584
Richard Smith0f59cb32015-12-18 21:45:41 +00006585 Candidate.Conversions[0] = TryObjectArgumentInitialization(
6586 *this, CandidateSet.getLocation(), From->getType(),
6587 From->Classify(Context), Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006588
John McCall0d1da222010-01-12 00:44:57 +00006589 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006590 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006591 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006592 return;
6593 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006594
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006595 // We won't go through a user-defined type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006596 // derived to base as such conversions are given Conversion Rank. They only
6597 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6598 QualType FromCanon
6599 = Context.getCanonicalType(From->getType().getUnqualifiedType());
6600 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
Richard Smith0f59cb32015-12-18 21:45:41 +00006601 if (FromCanon == ToCanon ||
6602 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006603 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006604 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006605 return;
6606 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006607
Douglas Gregora1f013e2008-11-07 22:36:19 +00006608 // To determine what the conversion from the result of calling the
6609 // conversion function to the type we're eventually trying to
6610 // convert to (ToType), we need to synthesize a call to the
6611 // conversion function and attempt copy initialization from it. This
6612 // makes sure that we get the right semantics with respect to
6613 // lvalues/rvalues and the type. Fortunately, we can allocate this
6614 // call on the stack and we don't need its arguments to be
6615 // well-formed.
John McCall113bee02012-03-10 09:33:50 +00006616 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00006617 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00006618 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6619 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00006620 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00006621 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00006622
Richard Smith48d24642011-07-13 22:53:21 +00006623 QualType ConversionType = Conversion->getConversionType();
Richard Smithdb0ac552015-12-18 22:40:25 +00006624 if (!isCompleteType(From->getLocStart(), ConversionType)) {
Douglas Gregor72ebdab2010-11-13 19:36:57 +00006625 Candidate.Viable = false;
6626 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6627 return;
6628 }
6629
Richard Smith48d24642011-07-13 22:53:21 +00006630 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCall7decc9e2010-11-18 06:31:45 +00006631
Mike Stump11289f42009-09-09 15:08:12 +00006632 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00006633 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6634 // allocator).
Richard Smith48d24642011-07-13 22:53:21 +00006635 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00006636 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00006637 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00006638 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006639 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00006640 /*SuppressUserConversions=*/true,
John McCall31168b02011-06-15 23:02:42 +00006641 /*InOverloadResolution=*/false,
6642 /*AllowObjCWritebackConversion=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00006643
John McCall0d1da222010-01-12 00:44:57 +00006644 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006645 case ImplicitConversionSequence::StandardConversion:
6646 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006647
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006648 // C++ [over.ics.user]p3:
6649 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006650 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006651 // shall have exact match rank.
6652 if (Conversion->getPrimaryTemplate() &&
6653 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6654 Candidate.Viable = false;
6655 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006656 return;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006657 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006658
Douglas Gregorcba72b12011-01-21 05:18:22 +00006659 // C++0x [dcl.init.ref]p5:
6660 // In the second case, if the reference is an rvalue reference and
6661 // the second standard conversion sequence of the user-defined
6662 // conversion sequence includes an lvalue-to-rvalue conversion, the
6663 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006664 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00006665 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6666 Candidate.Viable = false;
6667 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006668 return;
Douglas Gregorcba72b12011-01-21 05:18:22 +00006669 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00006670 break;
6671
6672 case ImplicitConversionSequence::BadConversion:
6673 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006674 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006675 return;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006676
6677 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006678 llvm_unreachable(
Douglas Gregora1f013e2008-11-07 22:36:19 +00006679 "Can only end up with a standard conversion sequence or failure");
6680 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006681
Craig Topper5fc8fc22014-08-27 06:28:36 +00006682 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006683 Candidate.Viable = false;
6684 Candidate.FailureKind = ovl_fail_enable_if;
6685 Candidate.DeductionFailure.Data = FailedAttr;
6686 return;
6687 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00006688}
6689
Douglas Gregor05155d82009-08-21 23:19:43 +00006690/// \brief Adds a conversion function template specialization
6691/// candidate to the overload set, using template argument deduction
6692/// to deduce the template arguments of the conversion function
6693/// template from the type that we are converting to (C++
6694/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00006695void
Douglas Gregor05155d82009-08-21 23:19:43 +00006696Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00006697 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006698 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00006699 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006700 OverloadCandidateSet &CandidateSet,
6701 bool AllowObjCConversionOnExplicit) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006702 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
6703 "Only conversion function templates permitted here");
6704
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006705 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6706 return;
6707
Craig Toppere6706e42012-09-19 02:26:47 +00006708 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006709 CXXConversionDecl *Specialization = nullptr;
Douglas Gregor05155d82009-08-21 23:19:43 +00006710 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00006711 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00006712 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006713 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006714 Candidate.FoundDecl = FoundDecl;
6715 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6716 Candidate.Viable = false;
6717 Candidate.FailureKind = ovl_fail_bad_deduction;
6718 Candidate.IsSurrogate = false;
6719 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006720 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006721 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006722 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00006723 return;
6724 }
Mike Stump11289f42009-09-09 15:08:12 +00006725
Douglas Gregor05155d82009-08-21 23:19:43 +00006726 // Add the conversion function template specialization produced by
6727 // template argument deduction as a candidate.
6728 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00006729 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006730 CandidateSet, AllowObjCConversionOnExplicit);
Douglas Gregor05155d82009-08-21 23:19:43 +00006731}
6732
Douglas Gregorab7897a2008-11-19 22:57:39 +00006733/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
6734/// converts the given @c Object to a function pointer via the
6735/// conversion function @c Conversion, and then attempts to call it
6736/// with the given arguments (C++ [over.call.object]p2-4). Proto is
6737/// the type of function that we'll eventually be calling.
6738void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006739 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006740 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006741 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00006742 Expr *Object,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006743 ArrayRef<Expr *> Args,
Douglas Gregorab7897a2008-11-19 22:57:39 +00006744 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006745 if (!CandidateSet.isNewCandidate(Conversion))
6746 return;
6747
Douglas Gregor27381f32009-11-23 12:27:39 +00006748 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006749 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006750
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006751 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00006752 Candidate.FoundDecl = FoundDecl;
Craig Topperc3ec1492014-05-26 06:22:03 +00006753 Candidate.Function = nullptr;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006754 Candidate.Surrogate = Conversion;
6755 Candidate.Viable = true;
6756 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006757 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006758 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006759
6760 // Determine the implicit conversion sequence for the implicit
6761 // object parameter.
Richard Smith0f59cb32015-12-18 21:45:41 +00006762 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
6763 *this, CandidateSet.getLocation(), Object->getType(),
6764 Object->Classify(Context), Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00006765 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006766 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006767 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00006768 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006769 return;
6770 }
6771
6772 // The first conversion is actually a user-defined conversion whose
6773 // first conversion is ObjectInit's standard conversion (which is
6774 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00006775 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006776 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00006777 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006778 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006779 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00006780 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump11289f42009-09-09 15:08:12 +00006781 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00006782 = Candidate.Conversions[0].UserDefined.Before;
6783 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
6784
Mike Stump11289f42009-09-09 15:08:12 +00006785 // Find the
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006786 unsigned NumParams = Proto->getNumParams();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006787
6788 // (C++ 13.3.2p2): A candidate function having fewer than m
6789 // parameters is viable only if it has an ellipsis in its parameter
6790 // list (8.3.5).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006791 if (Args.size() > NumParams && !Proto->isVariadic()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006792 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006793 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006794 return;
6795 }
6796
6797 // Function types don't have any default arguments, so just check if
6798 // we have enough arguments.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006799 if (Args.size() < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006800 // Not enough arguments.
6801 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006802 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006803 return;
6804 }
6805
6806 // Determine the implicit conversion sequences for each of the
6807 // arguments.
Richard Smithe54c3072013-05-05 15:51:06 +00006808 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006809 if (ArgIdx < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006810 // (C++ 13.3.2p3): for F to be a viable function, there shall
6811 // exist for each argument an implicit conversion sequence
6812 // (13.3.3.1) that converts that argument to the corresponding
6813 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00006814 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00006815 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006816 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00006817 /*SuppressUserConversions=*/false,
John McCall31168b02011-06-15 23:02:42 +00006818 /*InOverloadResolution=*/false,
6819 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006820 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00006821 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006822 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006823 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006824 return;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006825 }
6826 } else {
6827 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6828 // argument for which there is no corresponding parameter is
6829 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006830 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006831 }
6832 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006833
Craig Topper5fc8fc22014-08-27 06:28:36 +00006834 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006835 Candidate.Viable = false;
6836 Candidate.FailureKind = ovl_fail_enable_if;
6837 Candidate.DeductionFailure.Data = FailedAttr;
6838 return;
6839 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00006840}
6841
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006842/// \brief Add overload candidates for overloaded operators that are
6843/// member functions.
6844///
6845/// Add the overloaded operator candidates that are member functions
6846/// for the operator Op that was used in an operator expression such
6847/// as "x Op y". , Args/NumArgs provides the operator arguments, and
6848/// CandidateSet will store the added overload candidates. (C++
6849/// [over.match.oper]).
6850void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
6851 SourceLocation OpLoc,
Richard Smithe54c3072013-05-05 15:51:06 +00006852 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006853 OverloadCandidateSet& CandidateSet,
6854 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006855 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6856
6857 // C++ [over.match.oper]p3:
6858 // For a unary operator @ with an operand of a type whose
6859 // cv-unqualified version is T1, and for a binary operator @ with
6860 // a left operand of a type whose cv-unqualified version is T1 and
6861 // a right operand of a type whose cv-unqualified version is T2,
6862 // three sets of candidate functions, designated member
6863 // candidates, non-member candidates and built-in candidates, are
6864 // constructed as follows:
6865 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00006866
Richard Smith0feaf0c2013-04-20 12:41:22 +00006867 // -- If T1 is a complete class type or a class currently being
6868 // defined, the set of member candidates is the result of the
6869 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
6870 // the set of member candidates is empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006871 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Richard Smith0feaf0c2013-04-20 12:41:22 +00006872 // Complete the type if it can be completed.
Richard Smithdb0ac552015-12-18 22:40:25 +00006873 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
Richard Smith82b8d4e2015-12-18 22:19:11 +00006874 return;
Richard Smith0feaf0c2013-04-20 12:41:22 +00006875 // If the type is neither complete nor being defined, bail out now.
6876 if (!T1Rec->getDecl()->getDefinition())
Douglas Gregor6a1f9652009-08-27 23:35:55 +00006877 return;
Mike Stump11289f42009-09-09 15:08:12 +00006878
John McCall27b18f82009-11-17 02:14:36 +00006879 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6880 LookupQualifiedName(Operators, T1Rec->getDecl());
6881 Operators.suppressDiagnostics();
6882
Mike Stump11289f42009-09-09 15:08:12 +00006883 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00006884 OperEnd = Operators.end();
6885 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00006886 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00006887 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
Rafael Espindola51629df2013-04-29 19:29:25 +00006888 Args[0]->Classify(Context),
Richard Smithe54c3072013-05-05 15:51:06 +00006889 Args.slice(1),
Douglas Gregor02824322011-01-26 19:30:28 +00006890 CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00006891 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00006892 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006893}
6894
Douglas Gregora11693b2008-11-12 17:17:38 +00006895/// AddBuiltinCandidate - Add a candidate for a built-in
6896/// operator. ResultTy and ParamTys are the result and parameter types
6897/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00006898/// arguments being passed to the candidate. IsAssignmentOperator
6899/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00006900/// operator. NumContextualBoolArguments is the number of arguments
6901/// (at the beginning of the argument list) that will be contextually
6902/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00006903void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Richard Smithe54c3072013-05-05 15:51:06 +00006904 ArrayRef<Expr *> Args,
Douglas Gregorc5e61072009-01-13 00:52:54 +00006905 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00006906 bool IsAssignmentOperator,
6907 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00006908 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006909 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006910
Douglas Gregora11693b2008-11-12 17:17:38 +00006911 // Add this candidate
Richard Smithe54c3072013-05-05 15:51:06 +00006912 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
Craig Topperc3ec1492014-05-26 06:22:03 +00006913 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
6914 Candidate.Function = nullptr;
Douglas Gregor1d248c52008-12-12 02:00:36 +00006915 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006916 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00006917 Candidate.BuiltinTypes.ResultTy = ResultTy;
Richard Smithe54c3072013-05-05 15:51:06 +00006918 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Douglas Gregora11693b2008-11-12 17:17:38 +00006919 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6920
6921 // Determine the implicit conversion sequences for each of the
6922 // arguments.
6923 Candidate.Viable = true;
Richard Smithe54c3072013-05-05 15:51:06 +00006924 Candidate.ExplicitCallArguments = Args.size();
6925 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00006926 // C++ [over.match.oper]p4:
6927 // For the built-in assignment operators, conversions of the
6928 // left operand are restricted as follows:
6929 // -- no temporaries are introduced to hold the left operand, and
6930 // -- no user-defined conversions are applied to the left
6931 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00006932 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00006933 //
6934 // We block these conversions by turning off user-defined
6935 // conversions, since that is the only way that initialization of
6936 // a reference to a non-class type can occur from something that
6937 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00006938 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00006939 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00006940 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00006941 Candidate.Conversions[ArgIdx]
6942 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006943 } else {
Mike Stump11289f42009-09-09 15:08:12 +00006944 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006945 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00006946 ArgIdx == 0 && IsAssignmentOperator,
John McCall31168b02011-06-15 23:02:42 +00006947 /*InOverloadResolution=*/false,
6948 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006949 getLangOpts().ObjCAutoRefCount);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006950 }
John McCall0d1da222010-01-12 00:44:57 +00006951 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006952 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006953 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00006954 break;
6955 }
Douglas Gregora11693b2008-11-12 17:17:38 +00006956 }
6957}
6958
Craig Toppercd7b0332013-07-01 06:29:40 +00006959namespace {
6960
Douglas Gregora11693b2008-11-12 17:17:38 +00006961/// BuiltinCandidateTypeSet - A set of types that will be used for the
6962/// candidate operator functions for built-in operators (C++
6963/// [over.built]). The types are separated into pointer types and
6964/// enumeration types.
6965class BuiltinCandidateTypeSet {
6966 /// TypeSet - A set of types.
Richard Smith95853072016-03-25 00:08:53 +00006967 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
6968 llvm::SmallPtrSet<QualType, 8>> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00006969
6970 /// PointerTypes - The set of pointer types that will be used in the
6971 /// built-in candidates.
6972 TypeSet PointerTypes;
6973
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006974 /// MemberPointerTypes - The set of member pointer types that will be
6975 /// used in the built-in candidates.
6976 TypeSet MemberPointerTypes;
6977
Douglas Gregora11693b2008-11-12 17:17:38 +00006978 /// EnumerationTypes - The set of enumeration types that will be
6979 /// used in the built-in candidates.
6980 TypeSet EnumerationTypes;
6981
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006982 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006983 /// candidates.
6984 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00006985
6986 /// \brief A flag indicating non-record types are viable candidates
6987 bool HasNonRecordTypes;
6988
6989 /// \brief A flag indicating whether either arithmetic or enumeration types
6990 /// were present in the candidate set.
6991 bool HasArithmeticOrEnumeralTypes;
6992
Douglas Gregor80af3132011-05-21 23:15:46 +00006993 /// \brief A flag indicating whether the nullptr type was present in the
6994 /// candidate set.
6995 bool HasNullPtrType;
6996
Douglas Gregor8a2e6012009-08-24 15:23:48 +00006997 /// Sema - The semantic analysis instance where we are building the
6998 /// candidate type set.
6999 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00007000
Douglas Gregora11693b2008-11-12 17:17:38 +00007001 /// Context - The AST context in which we will build the type sets.
7002 ASTContext &Context;
7003
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007004 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7005 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007006 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00007007
7008public:
7009 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00007010 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00007011
Mike Stump11289f42009-09-09 15:08:12 +00007012 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00007013 : HasNonRecordTypes(false),
7014 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor80af3132011-05-21 23:15:46 +00007015 HasNullPtrType(false),
Chandler Carruth00a38332010-12-13 01:44:01 +00007016 SemaRef(SemaRef),
7017 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00007018
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007019 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007020 SourceLocation Loc,
7021 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007022 bool AllowExplicitConversions,
7023 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00007024
7025 /// pointer_begin - First pointer type found;
7026 iterator pointer_begin() { return PointerTypes.begin(); }
7027
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007028 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00007029 iterator pointer_end() { return PointerTypes.end(); }
7030
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007031 /// member_pointer_begin - First member pointer type found;
7032 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
7033
7034 /// member_pointer_end - Past the last member pointer type found;
7035 iterator member_pointer_end() { return MemberPointerTypes.end(); }
7036
Douglas Gregora11693b2008-11-12 17:17:38 +00007037 /// enumeration_begin - First enumeration type found;
7038 iterator enumeration_begin() { return EnumerationTypes.begin(); }
7039
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007040 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00007041 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007042
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007043 iterator vector_begin() { return VectorTypes.begin(); }
7044 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00007045
7046 bool hasNonRecordTypes() { return HasNonRecordTypes; }
7047 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor80af3132011-05-21 23:15:46 +00007048 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregora11693b2008-11-12 17:17:38 +00007049};
7050
Craig Toppercd7b0332013-07-01 06:29:40 +00007051} // end anonymous namespace
7052
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007053/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00007054/// the set of pointer types along with any more-qualified variants of
7055/// that type. For example, if @p Ty is "int const *", this routine
7056/// will add "int const *", "int const volatile *", "int const
7057/// restrict *", and "int const volatile restrict *" to the set of
7058/// pointer types. Returns true if the add of @p Ty itself succeeded,
7059/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00007060///
7061/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007062bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007063BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7064 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00007065
Douglas Gregora11693b2008-11-12 17:17:38 +00007066 // Insert this type.
Richard Smith95853072016-03-25 00:08:53 +00007067 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00007068 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007069
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00007070 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00007071 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00007072 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00007073 if (!PointerTy) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00007074 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7075 PointeeTy = PTy->getPointeeType();
7076 buildObjCPtr = true;
7077 } else {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00007078 PointeeTy = PointerTy->getPointeeType();
Douglas Gregor5bee2582012-06-04 00:15:09 +00007079 }
7080
Sebastian Redl4990a632009-11-18 20:39:26 +00007081 // Don't add qualified variants of arrays. For one, they're not allowed
7082 // (the qualifier would sink to the element type), and for another, the
7083 // only overload situation where it matters is subscript or pointer +- int,
7084 // and those shouldn't have qualifier variants anyway.
7085 if (PointeeTy->isArrayType())
7086 return true;
Douglas Gregor5bee2582012-06-04 00:15:09 +00007087
John McCall8ccfcb52009-09-24 19:53:00 +00007088 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007089 bool hasVolatile = VisibleQuals.hasVolatile();
7090 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007091
John McCall8ccfcb52009-09-24 19:53:00 +00007092 // Iterate through all strict supersets of BaseCVR.
7093 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7094 if ((CVR | BaseCVR) != CVR) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00007095 // Skip over volatile if no volatile found anywhere in the types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007096 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00007097
7098 // Skip over restrict if no restrict found anywhere in the types, or if
7099 // the type cannot be restrict-qualified.
7100 if ((CVR & Qualifiers::Restrict) &&
7101 (!hasRestrict ||
7102 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7103 continue;
7104
7105 // Build qualified pointee type.
John McCall8ccfcb52009-09-24 19:53:00 +00007106 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007107
7108 // Build qualified pointer type.
7109 QualType QPointerTy;
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00007110 if (!buildObjCPtr)
Douglas Gregor5bee2582012-06-04 00:15:09 +00007111 QPointerTy = Context.getPointerType(QPointeeTy);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00007112 else
Douglas Gregor5bee2582012-06-04 00:15:09 +00007113 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
7114
7115 // Insert qualified pointer type.
7116 PointerTypes.insert(QPointerTy);
Douglas Gregora11693b2008-11-12 17:17:38 +00007117 }
7118
7119 return true;
7120}
7121
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007122/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7123/// to the set of pointer types along with any more-qualified variants of
7124/// that type. For example, if @p Ty is "int const *", this routine
7125/// will add "int const *", "int const volatile *", "int const
7126/// restrict *", and "int const volatile restrict *" to the set of
7127/// pointer types. Returns true if the add of @p Ty itself succeeded,
7128/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00007129///
7130/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007131bool
7132BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7133 QualType Ty) {
7134 // Insert this type.
Richard Smith95853072016-03-25 00:08:53 +00007135 if (!MemberPointerTypes.insert(Ty))
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007136 return false;
7137
John McCall8ccfcb52009-09-24 19:53:00 +00007138 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
7139 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007140
John McCall8ccfcb52009-09-24 19:53:00 +00007141 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00007142 // Don't add qualified variants of arrays. For one, they're not allowed
7143 // (the qualifier would sink to the element type), and for another, the
7144 // only overload situation where it matters is subscript or pointer +- int,
7145 // and those shouldn't have qualifier variants anyway.
7146 if (PointeeTy->isArrayType())
7147 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00007148 const Type *ClassTy = PointerTy->getClass();
7149
7150 // Iterate through all strict supersets of the pointee type's CVR
7151 // qualifiers.
7152 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7153 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7154 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007155
John McCall8ccfcb52009-09-24 19:53:00 +00007156 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00007157 MemberPointerTypes.insert(
7158 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007159 }
7160
7161 return true;
7162}
7163
Douglas Gregora11693b2008-11-12 17:17:38 +00007164/// AddTypesConvertedFrom - Add each of the types to which the type @p
7165/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007166/// primarily interested in pointer types and enumeration types. We also
7167/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00007168/// AllowUserConversions is true if we should look at the conversion
7169/// functions of a class type, and AllowExplicitConversions if we
7170/// should also include the explicit conversion functions of a class
7171/// type.
Mike Stump11289f42009-09-09 15:08:12 +00007172void
Douglas Gregor5fb53972009-01-14 15:45:31 +00007173BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007174 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00007175 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007176 bool AllowExplicitConversions,
7177 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007178 // Only deal with canonical types.
7179 Ty = Context.getCanonicalType(Ty);
7180
7181 // Look through reference types; they aren't part of the type of an
7182 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007183 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00007184 Ty = RefTy->getPointeeType();
7185
John McCall33ddac02011-01-19 10:06:00 +00007186 // If we're dealing with an array type, decay to the pointer.
7187 if (Ty->isArrayType())
7188 Ty = SemaRef.Context.getArrayDecayedType(Ty);
7189
7190 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007191 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00007192
Chandler Carruth00a38332010-12-13 01:44:01 +00007193 // Flag if we ever add a non-record type.
7194 const RecordType *TyRec = Ty->getAs<RecordType>();
7195 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7196
Chandler Carruth00a38332010-12-13 01:44:01 +00007197 // Flag if we encounter an arithmetic type.
7198 HasArithmeticOrEnumeralTypes =
7199 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7200
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00007201 if (Ty->isObjCIdType() || Ty->isObjCClassType())
7202 PointerTypes.insert(Ty);
7203 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007204 // Insert our type, and its more-qualified variants, into the set
7205 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007206 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00007207 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007208 } else if (Ty->isMemberPointerType()) {
7209 // Member pointers are far easier, since the pointee can't be converted.
7210 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7211 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00007212 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007213 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00007214 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007215 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007216 // We treat vector types as arithmetic types in many contexts as an
7217 // extension.
7218 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007219 VectorTypes.insert(Ty);
Douglas Gregor80af3132011-05-21 23:15:46 +00007220 } else if (Ty->isNullPtrType()) {
7221 HasNullPtrType = true;
Chandler Carruth00a38332010-12-13 01:44:01 +00007222 } else if (AllowUserConversions && TyRec) {
7223 // No conversion functions in incomplete types.
Richard Smithdb0ac552015-12-18 22:40:25 +00007224 if (!SemaRef.isCompleteType(Loc, Ty))
Chandler Carruth00a38332010-12-13 01:44:01 +00007225 return;
Mike Stump11289f42009-09-09 15:08:12 +00007226
Chandler Carruth00a38332010-12-13 01:44:01 +00007227 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00007228 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007229 if (isa<UsingShadowDecl>(D))
7230 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00007231
Chandler Carruth00a38332010-12-13 01:44:01 +00007232 // Skip conversion function templates; they don't tell us anything
7233 // about which builtin types we can convert to.
7234 if (isa<FunctionTemplateDecl>(D))
7235 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00007236
Chandler Carruth00a38332010-12-13 01:44:01 +00007237 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7238 if (AllowExplicitConversions || !Conv->isExplicit()) {
7239 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7240 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00007241 }
7242 }
7243 }
7244}
7245
Douglas Gregor84605ae2009-08-24 13:43:27 +00007246/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
7247/// the volatile- and non-volatile-qualified assignment operators for the
7248/// given type to the candidate set.
7249static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7250 QualType T,
Richard Smithe54c3072013-05-05 15:51:06 +00007251 ArrayRef<Expr *> Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00007252 OverloadCandidateSet &CandidateSet) {
7253 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00007254
Douglas Gregor84605ae2009-08-24 13:43:27 +00007255 // T& operator=(T&, T)
7256 ParamTypes[0] = S.Context.getLValueReferenceType(T);
7257 ParamTypes[1] = T;
Richard Smithe54c3072013-05-05 15:51:06 +00007258 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor84605ae2009-08-24 13:43:27 +00007259 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00007260
Douglas Gregor84605ae2009-08-24 13:43:27 +00007261 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7262 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00007263 ParamTypes[0]
7264 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00007265 ParamTypes[1] = T;
Richard Smithe54c3072013-05-05 15:51:06 +00007266 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00007267 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00007268 }
7269}
Mike Stump11289f42009-09-09 15:08:12 +00007270
Sebastian Redl1054fae2009-10-25 17:03:50 +00007271/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7272/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007273static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7274 Qualifiers VRQuals;
7275 const RecordType *TyRec;
7276 if (const MemberPointerType *RHSMPType =
7277 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00007278 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007279 else
7280 TyRec = ArgExpr->getType()->getAs<RecordType>();
7281 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007282 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007283 VRQuals.addVolatile();
7284 VRQuals.addRestrict();
7285 return VRQuals;
7286 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007287
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007288 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00007289 if (!ClassDecl->hasDefinition())
7290 return VRQuals;
7291
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00007292 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
John McCallda4458e2010-03-31 01:36:47 +00007293 if (isa<UsingShadowDecl>(D))
7294 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7295 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007296 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7297 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7298 CanTy = ResTypeRef->getPointeeType();
7299 // Need to go down the pointer/mempointer chain and add qualifiers
7300 // as see them.
7301 bool done = false;
7302 while (!done) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00007303 if (CanTy.isRestrictQualified())
7304 VRQuals.addRestrict();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007305 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7306 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007307 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007308 CanTy->getAs<MemberPointerType>())
7309 CanTy = ResTypeMPtr->getPointeeType();
7310 else
7311 done = true;
7312 if (CanTy.isVolatileQualified())
7313 VRQuals.addVolatile();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007314 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7315 return VRQuals;
7316 }
7317 }
7318 }
7319 return VRQuals;
7320}
John McCall52872982010-11-13 05:51:15 +00007321
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007322namespace {
John McCall52872982010-11-13 05:51:15 +00007323
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007324/// \brief Helper class to manage the addition of builtin operator overload
7325/// candidates. It provides shared state and utility methods used throughout
7326/// the process, as well as a helper method to add each group of builtin
7327/// operator overloads from the standard to a candidate set.
7328class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007329 // Common instance state available to all overload candidate addition methods.
7330 Sema &S;
Richard Smithe54c3072013-05-05 15:51:06 +00007331 ArrayRef<Expr *> Args;
Chandler Carruthc6586e52010-12-12 10:35:00 +00007332 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00007333 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007334 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruthc6586e52010-12-12 10:35:00 +00007335 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007336
Chandler Carruthc6586e52010-12-12 10:35:00 +00007337 // Define some constants used to index and iterate over the arithemetic types
7338 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00007339 // The "promoted arithmetic types" are the arithmetic
7340 // types are that preserved by promotion (C++ [over.built]p2).
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00007341 static const unsigned FirstIntegralType = 4;
7342 static const unsigned LastIntegralType = 21;
7343 static const unsigned FirstPromotedIntegralType = 4,
7344 LastPromotedIntegralType = 12;
John McCall52872982010-11-13 05:51:15 +00007345 static const unsigned FirstPromotedArithmeticType = 0,
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00007346 LastPromotedArithmeticType = 12;
7347 static const unsigned NumArithmeticTypes = 21;
John McCall52872982010-11-13 05:51:15 +00007348
Chandler Carruthc6586e52010-12-12 10:35:00 +00007349 /// \brief Get the canonical type for a given arithmetic type index.
7350 CanQualType getArithmeticType(unsigned index) {
7351 assert(index < NumArithmeticTypes);
7352 static CanQualType ASTContext::* const
7353 ArithmeticTypes[NumArithmeticTypes] = {
7354 // Start of promoted types.
7355 &ASTContext::FloatTy,
7356 &ASTContext::DoubleTy,
7357 &ASTContext::LongDoubleTy,
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00007358 &ASTContext::Float128Ty,
John McCall52872982010-11-13 05:51:15 +00007359
Chandler Carruthc6586e52010-12-12 10:35:00 +00007360 // Start of integral types.
7361 &ASTContext::IntTy,
7362 &ASTContext::LongTy,
7363 &ASTContext::LongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00007364 &ASTContext::Int128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00007365 &ASTContext::UnsignedIntTy,
7366 &ASTContext::UnsignedLongTy,
7367 &ASTContext::UnsignedLongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00007368 &ASTContext::UnsignedInt128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00007369 // End of promoted types.
7370
7371 &ASTContext::BoolTy,
7372 &ASTContext::CharTy,
7373 &ASTContext::WCharTy,
7374 &ASTContext::Char16Ty,
7375 &ASTContext::Char32Ty,
7376 &ASTContext::SignedCharTy,
7377 &ASTContext::ShortTy,
7378 &ASTContext::UnsignedCharTy,
7379 &ASTContext::UnsignedShortTy,
7380 // End of integral types.
Richard Smith521ecc12012-06-10 08:00:26 +00007381 // FIXME: What about complex? What about half?
Chandler Carruthc6586e52010-12-12 10:35:00 +00007382 };
7383 return S.Context.*ArithmeticTypes[index];
7384 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007385
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007386 /// \brief Gets the canonical type resulting from the usual arithemetic
7387 /// converions for the given arithmetic types.
7388 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
7389 // Accelerator table for performing the usual arithmetic conversions.
7390 // The rules are basically:
7391 // - if either is floating-point, use the wider floating-point
7392 // - if same signedness, use the higher rank
7393 // - if same size, use unsigned of the higher rank
7394 // - use the larger type
7395 // These rules, together with the axiom that higher ranks are
7396 // never smaller, are sufficient to precompute all of these results
7397 // *except* when dealing with signed types of higher rank.
7398 // (we could precompute SLL x UI for all known platforms, but it's
7399 // better not to make any assumptions).
Richard Smith521ecc12012-06-10 08:00:26 +00007400 // We assume that int128 has a higher rank than long long on all platforms.
George Burgess IVf23ce362016-04-29 21:32:53 +00007401 enum PromotedType : int8_t {
Richard Smith521ecc12012-06-10 08:00:26 +00007402 Dep=-1,
7403 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007404 };
Nuno Lopes9af6b032012-04-21 14:45:25 +00007405 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007406 [LastPromotedArithmeticType] = {
Richard Smith521ecc12012-06-10 08:00:26 +00007407/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
7408/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
7409/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
7410/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
7411/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
7412/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
7413/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
7414/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
7415/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
7416/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
7417/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007418 };
7419
7420 assert(L < LastPromotedArithmeticType);
7421 assert(R < LastPromotedArithmeticType);
7422 int Idx = ConversionsTable[L][R];
7423
7424 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007425 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007426
7427 // Slow path: we need to compare widths.
7428 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007429 CanQualType LT = getArithmeticType(L),
7430 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007431 unsigned LW = S.Context.getIntWidth(LT),
7432 RW = S.Context.getIntWidth(RT);
7433
7434 // If they're different widths, use the signed type.
7435 if (LW > RW) return LT;
7436 else if (LW < RW) return RT;
7437
7438 // Otherwise, use the unsigned type of the signed type's rank.
7439 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
7440 assert(L == SLL || R == SLL);
7441 return S.Context.UnsignedLongLongTy;
7442 }
7443
Chandler Carruth5659c0c2010-12-12 09:22:45 +00007444 /// \brief Helper method to factor out the common pattern of adding overloads
7445 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007446 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007447 bool HasVolatile,
7448 bool HasRestrict) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007449 QualType ParamTypes[2] = {
7450 S.Context.getLValueReferenceType(CandidateTy),
7451 S.Context.IntTy
7452 };
7453
7454 // Non-volatile version.
Richard Smithe54c3072013-05-05 15:51:06 +00007455 if (Args.size() == 1)
7456 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007457 else
Richard Smithe54c3072013-05-05 15:51:06 +00007458 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007459
7460 // Use a heuristic to reduce number of builtin candidates in the set:
7461 // add volatile version only if there are conversions to a volatile type.
7462 if (HasVolatile) {
7463 ParamTypes[0] =
7464 S.Context.getLValueReferenceType(
7465 S.Context.getVolatileType(CandidateTy));
Richard Smithe54c3072013-05-05 15:51:06 +00007466 if (Args.size() == 1)
7467 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007468 else
Richard Smithe54c3072013-05-05 15:51:06 +00007469 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007470 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007471
7472 // Add restrict version only if there are conversions to a restrict type
7473 // and our candidate type is a non-restrict-qualified pointer.
7474 if (HasRestrict && CandidateTy->isAnyPointerType() &&
7475 !CandidateTy.isRestrictQualified()) {
7476 ParamTypes[0]
7477 = S.Context.getLValueReferenceType(
7478 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
Richard Smithe54c3072013-05-05 15:51:06 +00007479 if (Args.size() == 1)
7480 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007481 else
Richard Smithe54c3072013-05-05 15:51:06 +00007482 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007483
7484 if (HasVolatile) {
7485 ParamTypes[0]
7486 = S.Context.getLValueReferenceType(
7487 S.Context.getCVRQualifiedType(CandidateTy,
7488 (Qualifiers::Volatile |
7489 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007490 if (Args.size() == 1)
7491 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007492 else
Richard Smithe54c3072013-05-05 15:51:06 +00007493 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007494 }
7495 }
7496
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007497 }
7498
7499public:
7500 BuiltinOperatorOverloadBuilder(
Richard Smithe54c3072013-05-05 15:51:06 +00007501 Sema &S, ArrayRef<Expr *> Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007502 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00007503 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007504 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007505 OverloadCandidateSet &CandidateSet)
Richard Smithe54c3072013-05-05 15:51:06 +00007506 : S(S), Args(Args),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007507 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00007508 HasArithmeticOrEnumeralCandidateType(
7509 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007510 CandidateTypes(CandidateTypes),
7511 CandidateSet(CandidateSet) {
7512 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007513 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007514 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007515 assert(getArithmeticType(LastPromotedIntegralType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00007516 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007517 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007518 assert(getArithmeticType(FirstPromotedArithmeticType)
7519 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007520 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007521 assert(getArithmeticType(LastPromotedArithmeticType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00007522 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007523 "Invalid last promoted arithmetic type");
7524 }
7525
7526 // C++ [over.built]p3:
7527 //
7528 // For every pair (T, VQ), where T is an arithmetic type, and VQ
7529 // is either volatile or empty, there exist candidate operator
7530 // functions of the form
7531 //
7532 // VQ T& operator++(VQ T&);
7533 // T operator++(VQ T&, int);
7534 //
7535 // C++ [over.built]p4:
7536 //
7537 // For every pair (T, VQ), where T is an arithmetic type other
7538 // than bool, and VQ is either volatile or empty, there exist
7539 // candidate operator functions of the form
7540 //
7541 // VQ T& operator--(VQ T&);
7542 // T operator--(VQ T&, int);
7543 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007544 if (!HasArithmeticOrEnumeralCandidateType)
7545 return;
7546
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007547 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
7548 Arith < NumArithmeticTypes; ++Arith) {
7549 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00007550 getArithmeticType(Arith),
Douglas Gregor5bee2582012-06-04 00:15:09 +00007551 VisibleTypeConversionsQuals.hasVolatile(),
7552 VisibleTypeConversionsQuals.hasRestrict());
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007553 }
7554 }
7555
7556 // C++ [over.built]p5:
7557 //
7558 // For every pair (T, VQ), where T is a cv-qualified or
7559 // cv-unqualified object type, and VQ is either volatile or
7560 // empty, there exist candidate operator functions of the form
7561 //
7562 // T*VQ& operator++(T*VQ&);
7563 // T*VQ& operator--(T*VQ&);
7564 // T* operator++(T*VQ&, int);
7565 // T* operator--(T*VQ&, int);
7566 void addPlusPlusMinusMinusPointerOverloads() {
7567 for (BuiltinCandidateTypeSet::iterator
7568 Ptr = CandidateTypes[0].pointer_begin(),
7569 PtrEnd = CandidateTypes[0].pointer_end();
7570 Ptr != PtrEnd; ++Ptr) {
7571 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00007572 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007573 continue;
7574
7575 addPlusPlusMinusMinusStyleOverloads(*Ptr,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007576 (!(*Ptr).isVolatileQualified() &&
7577 VisibleTypeConversionsQuals.hasVolatile()),
7578 (!(*Ptr).isRestrictQualified() &&
7579 VisibleTypeConversionsQuals.hasRestrict()));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007580 }
7581 }
7582
7583 // C++ [over.built]p6:
7584 // For every cv-qualified or cv-unqualified object type T, there
7585 // exist candidate operator functions of the form
7586 //
7587 // T& operator*(T*);
7588 //
7589 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007590 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00007591 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007592 // T& operator*(T*);
7593 void addUnaryStarPointerOverloads() {
7594 for (BuiltinCandidateTypeSet::iterator
7595 Ptr = CandidateTypes[0].pointer_begin(),
7596 PtrEnd = CandidateTypes[0].pointer_end();
7597 Ptr != PtrEnd; ++Ptr) {
7598 QualType ParamTy = *Ptr;
7599 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007600 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7601 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007602
Douglas Gregor02824322011-01-26 19:30:28 +00007603 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7604 if (Proto->getTypeQuals() || Proto->getRefQualifier())
7605 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007606
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007607 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
Richard Smithe54c3072013-05-05 15:51:06 +00007608 &ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007609 }
7610 }
7611
7612 // C++ [over.built]p9:
7613 // For every promoted arithmetic type T, there exist candidate
7614 // operator functions of the form
7615 //
7616 // T operator+(T);
7617 // T operator-(T);
7618 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007619 if (!HasArithmeticOrEnumeralCandidateType)
7620 return;
7621
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007622 for (unsigned Arith = FirstPromotedArithmeticType;
7623 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007624 QualType ArithTy = getArithmeticType(Arith);
Richard Smithe54c3072013-05-05 15:51:06 +00007625 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007626 }
7627
7628 // Extension: We also add these operators for vector types.
7629 for (BuiltinCandidateTypeSet::iterator
7630 Vec = CandidateTypes[0].vector_begin(),
7631 VecEnd = CandidateTypes[0].vector_end();
7632 Vec != VecEnd; ++Vec) {
7633 QualType VecTy = *Vec;
Richard Smithe54c3072013-05-05 15:51:06 +00007634 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007635 }
7636 }
7637
7638 // C++ [over.built]p8:
7639 // For every type T, there exist candidate operator functions of
7640 // the form
7641 //
7642 // T* operator+(T*);
7643 void addUnaryPlusPointerOverloads() {
7644 for (BuiltinCandidateTypeSet::iterator
7645 Ptr = CandidateTypes[0].pointer_begin(),
7646 PtrEnd = CandidateTypes[0].pointer_end();
7647 Ptr != PtrEnd; ++Ptr) {
7648 QualType ParamTy = *Ptr;
Richard Smithe54c3072013-05-05 15:51:06 +00007649 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007650 }
7651 }
7652
7653 // C++ [over.built]p10:
7654 // For every promoted integral type T, there exist candidate
7655 // operator functions of the form
7656 //
7657 // T operator~(T);
7658 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007659 if (!HasArithmeticOrEnumeralCandidateType)
7660 return;
7661
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007662 for (unsigned Int = FirstPromotedIntegralType;
7663 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007664 QualType IntTy = getArithmeticType(Int);
Richard Smithe54c3072013-05-05 15:51:06 +00007665 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007666 }
7667
7668 // Extension: We also add this operator for vector types.
7669 for (BuiltinCandidateTypeSet::iterator
7670 Vec = CandidateTypes[0].vector_begin(),
7671 VecEnd = CandidateTypes[0].vector_end();
7672 Vec != VecEnd; ++Vec) {
7673 QualType VecTy = *Vec;
Richard Smithe54c3072013-05-05 15:51:06 +00007674 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007675 }
7676 }
7677
7678 // C++ [over.match.oper]p16:
Richard Smith5e9746f2016-10-21 22:00:42 +00007679 // For every pointer to member type T or type std::nullptr_t, there
7680 // exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007681 //
7682 // bool operator==(T,T);
7683 // bool operator!=(T,T);
Richard Smith5e9746f2016-10-21 22:00:42 +00007684 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007685 /// Set of (canonical) types that we've already handled.
7686 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7687
Richard Smithe54c3072013-05-05 15:51:06 +00007688 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007689 for (BuiltinCandidateTypeSet::iterator
7690 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7691 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7692 MemPtr != MemPtrEnd;
7693 ++MemPtr) {
7694 // Don't add the same builtin candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007695 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007696 continue;
7697
7698 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smithe54c3072013-05-05 15:51:06 +00007699 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007700 }
Richard Smith5e9746f2016-10-21 22:00:42 +00007701
7702 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7703 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7704 if (AddedTypes.insert(NullPtrTy).second) {
7705 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
7706 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
7707 CandidateSet);
7708 }
7709 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007710 }
7711 }
7712
7713 // C++ [over.built]p15:
7714 //
Richard Smith5e9746f2016-10-21 22:00:42 +00007715 // For every T, where T is an enumeration type or a pointer type,
7716 // there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007717 //
7718 // bool operator<(T, T);
7719 // bool operator>(T, T);
7720 // bool operator<=(T, T);
7721 // bool operator>=(T, T);
7722 // bool operator==(T, T);
7723 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007724 void addRelationalPointerOrEnumeralOverloads() {
Eli Friedman14f082b2012-09-18 21:52:24 +00007725 // C++ [over.match.oper]p3:
7726 // [...]the built-in candidates include all of the candidate operator
7727 // functions defined in 13.6 that, compared to the given operator, [...]
7728 // do not have the same parameter-type-list as any non-template non-member
7729 // candidate.
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007730 //
Eli Friedman14f082b2012-09-18 21:52:24 +00007731 // Note that in practice, this only affects enumeration types because there
7732 // aren't any built-in candidates of record type, and a user-defined operator
7733 // must have an operand of record or enumeration type. Also, the only other
7734 // overloaded operator with enumeration arguments, operator=,
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007735 // cannot be overloaded for enumeration types, so this is the only place
7736 // where we must suppress candidates like this.
7737 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7738 UserDefinedBinaryOperators;
7739
Richard Smithe54c3072013-05-05 15:51:06 +00007740 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007741 if (CandidateTypes[ArgIdx].enumeration_begin() !=
7742 CandidateTypes[ArgIdx].enumeration_end()) {
7743 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7744 CEnd = CandidateSet.end();
7745 C != CEnd; ++C) {
7746 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7747 continue;
7748
Eli Friedman14f082b2012-09-18 21:52:24 +00007749 if (C->Function->isFunctionTemplateSpecialization())
7750 continue;
7751
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007752 QualType FirstParamType =
7753 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7754 QualType SecondParamType =
7755 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7756
7757 // Skip if either parameter isn't of enumeral type.
7758 if (!FirstParamType->isEnumeralType() ||
7759 !SecondParamType->isEnumeralType())
7760 continue;
7761
7762 // Add this operator to the set of known user-defined operators.
7763 UserDefinedBinaryOperators.insert(
7764 std::make_pair(S.Context.getCanonicalType(FirstParamType),
7765 S.Context.getCanonicalType(SecondParamType)));
7766 }
7767 }
7768 }
7769
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007770 /// Set of (canonical) types that we've already handled.
7771 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7772
Richard Smithe54c3072013-05-05 15:51:06 +00007773 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007774 for (BuiltinCandidateTypeSet::iterator
7775 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7776 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7777 Ptr != PtrEnd; ++Ptr) {
7778 // Don't add the same builtin candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007779 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007780 continue;
7781
7782 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smithe54c3072013-05-05 15:51:06 +00007783 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007784 }
7785 for (BuiltinCandidateTypeSet::iterator
7786 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7787 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7788 Enum != EnumEnd; ++Enum) {
7789 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
7790
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007791 // Don't add the same builtin candidate twice, or if a user defined
7792 // candidate exists.
David Blaikie82e95a32014-11-19 07:49:47 +00007793 if (!AddedTypes.insert(CanonType).second ||
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007794 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
7795 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007796 continue;
7797
7798 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smithe54c3072013-05-05 15:51:06 +00007799 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007800 }
7801 }
7802 }
7803
7804 // C++ [over.built]p13:
7805 //
7806 // For every cv-qualified or cv-unqualified object type T
7807 // there exist candidate operator functions of the form
7808 //
7809 // T* operator+(T*, ptrdiff_t);
7810 // T& operator[](T*, ptrdiff_t); [BELOW]
7811 // T* operator-(T*, ptrdiff_t);
7812 // T* operator+(ptrdiff_t, T*);
7813 // T& operator[](ptrdiff_t, T*); [BELOW]
7814 //
7815 // C++ [over.built]p14:
7816 //
7817 // For every T, where T is a pointer to object type, there
7818 // exist candidate operator functions of the form
7819 //
7820 // ptrdiff_t operator-(T, T);
7821 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
7822 /// Set of (canonical) types that we've already handled.
7823 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7824
7825 for (int Arg = 0; Arg < 2; ++Arg) {
Eric Christopher9207a522015-08-21 16:24:01 +00007826 QualType AsymmetricParamTypes[2] = {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007827 S.Context.getPointerDiffType(),
7828 S.Context.getPointerDiffType(),
7829 };
7830 for (BuiltinCandidateTypeSet::iterator
7831 Ptr = CandidateTypes[Arg].pointer_begin(),
7832 PtrEnd = CandidateTypes[Arg].pointer_end();
7833 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00007834 QualType PointeeTy = (*Ptr)->getPointeeType();
7835 if (!PointeeTy->isObjectType())
7836 continue;
7837
Eric Christopher9207a522015-08-21 16:24:01 +00007838 AsymmetricParamTypes[Arg] = *Ptr;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007839 if (Arg == 0 || Op == OO_Plus) {
7840 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
7841 // T* operator+(ptrdiff_t, T*);
Eric Christopher9207a522015-08-21 16:24:01 +00007842 S.AddBuiltinCandidate(*Ptr, AsymmetricParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007843 }
7844 if (Op == OO_Minus) {
7845 // ptrdiff_t operator-(T, T);
David Blaikie82e95a32014-11-19 07:49:47 +00007846 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007847 continue;
7848
7849 QualType ParamTypes[2] = { *Ptr, *Ptr };
7850 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
Richard Smithe54c3072013-05-05 15:51:06 +00007851 Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007852 }
7853 }
7854 }
7855 }
7856
7857 // C++ [over.built]p12:
7858 //
7859 // For every pair of promoted arithmetic types L and R, there
7860 // exist candidate operator functions of the form
7861 //
7862 // LR operator*(L, R);
7863 // LR operator/(L, R);
7864 // LR operator+(L, R);
7865 // LR operator-(L, R);
7866 // bool operator<(L, R);
7867 // bool operator>(L, R);
7868 // bool operator<=(L, R);
7869 // bool operator>=(L, R);
7870 // bool operator==(L, R);
7871 // bool operator!=(L, R);
7872 //
7873 // where LR is the result of the usual arithmetic conversions
7874 // between types L and R.
7875 //
7876 // C++ [over.built]p24:
7877 //
7878 // For every pair of promoted arithmetic types L and R, there exist
7879 // candidate operator functions of the form
7880 //
7881 // LR operator?(bool, L, R);
7882 //
7883 // where LR is the result of the usual arithmetic conversions
7884 // between types L and R.
7885 // Our candidates ignore the first parameter.
7886 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007887 if (!HasArithmeticOrEnumeralCandidateType)
7888 return;
7889
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007890 for (unsigned Left = FirstPromotedArithmeticType;
7891 Left < LastPromotedArithmeticType; ++Left) {
7892 for (unsigned Right = FirstPromotedArithmeticType;
7893 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007894 QualType LandR[2] = { getArithmeticType(Left),
7895 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007896 QualType Result =
7897 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007898 : getUsualArithmeticConversions(Left, Right);
Richard Smithe54c3072013-05-05 15:51:06 +00007899 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007900 }
7901 }
7902
7903 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7904 // conditional operator for vector types.
7905 for (BuiltinCandidateTypeSet::iterator
7906 Vec1 = CandidateTypes[0].vector_begin(),
7907 Vec1End = CandidateTypes[0].vector_end();
7908 Vec1 != Vec1End; ++Vec1) {
7909 for (BuiltinCandidateTypeSet::iterator
7910 Vec2 = CandidateTypes[1].vector_begin(),
7911 Vec2End = CandidateTypes[1].vector_end();
7912 Vec2 != Vec2End; ++Vec2) {
7913 QualType LandR[2] = { *Vec1, *Vec2 };
7914 QualType Result = S.Context.BoolTy;
7915 if (!isComparison) {
7916 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7917 Result = *Vec1;
7918 else
7919 Result = *Vec2;
7920 }
7921
Richard Smithe54c3072013-05-05 15:51:06 +00007922 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007923 }
7924 }
7925 }
7926
7927 // C++ [over.built]p17:
7928 //
7929 // For every pair of promoted integral types L and R, there
7930 // exist candidate operator functions of the form
7931 //
7932 // LR operator%(L, R);
7933 // LR operator&(L, R);
7934 // LR operator^(L, R);
7935 // LR operator|(L, R);
7936 // L operator<<(L, R);
7937 // L operator>>(L, R);
7938 //
7939 // where LR is the result of the usual arithmetic conversions
7940 // between types L and R.
7941 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007942 if (!HasArithmeticOrEnumeralCandidateType)
7943 return;
7944
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007945 for (unsigned Left = FirstPromotedIntegralType;
7946 Left < LastPromotedIntegralType; ++Left) {
7947 for (unsigned Right = FirstPromotedIntegralType;
7948 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007949 QualType LandR[2] = { getArithmeticType(Left),
7950 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007951 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7952 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007953 : getUsualArithmeticConversions(Left, Right);
Richard Smithe54c3072013-05-05 15:51:06 +00007954 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007955 }
7956 }
7957 }
7958
7959 // C++ [over.built]p20:
7960 //
7961 // For every pair (T, VQ), where T is an enumeration or
7962 // pointer to member type and VQ is either volatile or
7963 // empty, there exist candidate operator functions of the form
7964 //
7965 // VQ T& operator=(VQ T&, T);
7966 void addAssignmentMemberPointerOrEnumeralOverloads() {
7967 /// Set of (canonical) types that we've already handled.
7968 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7969
7970 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7971 for (BuiltinCandidateTypeSet::iterator
7972 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7973 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7974 Enum != EnumEnd; ++Enum) {
David Blaikie82e95a32014-11-19 07:49:47 +00007975 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007976 continue;
7977
Richard Smithe54c3072013-05-05 15:51:06 +00007978 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007979 }
7980
7981 for (BuiltinCandidateTypeSet::iterator
7982 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7983 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7984 MemPtr != MemPtrEnd; ++MemPtr) {
David Blaikie82e95a32014-11-19 07:49:47 +00007985 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007986 continue;
7987
Richard Smithe54c3072013-05-05 15:51:06 +00007988 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007989 }
7990 }
7991 }
7992
7993 // C++ [over.built]p19:
7994 //
7995 // For every pair (T, VQ), where T is any type and VQ is either
7996 // volatile or empty, there exist candidate operator functions
7997 // of the form
7998 //
7999 // T*VQ& operator=(T*VQ&, T*);
8000 //
8001 // C++ [over.built]p21:
8002 //
8003 // For every pair (T, VQ), where T is a cv-qualified or
8004 // cv-unqualified object type and VQ is either volatile or
8005 // empty, there exist candidate operator functions of the form
8006 //
8007 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
8008 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
8009 void addAssignmentPointerOverloads(bool isEqualOp) {
8010 /// Set of (canonical) types that we've already handled.
8011 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8012
8013 for (BuiltinCandidateTypeSet::iterator
8014 Ptr = CandidateTypes[0].pointer_begin(),
8015 PtrEnd = CandidateTypes[0].pointer_end();
8016 Ptr != PtrEnd; ++Ptr) {
8017 // If this is operator=, keep track of the builtin candidates we added.
8018 if (isEqualOp)
8019 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00008020 else if (!(*Ptr)->getPointeeType()->isObjectType())
8021 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008022
8023 // non-volatile version
8024 QualType ParamTypes[2] = {
8025 S.Context.getLValueReferenceType(*Ptr),
8026 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
8027 };
Richard Smithe54c3072013-05-05 15:51:06 +00008028 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008029 /*IsAssigmentOperator=*/ isEqualOp);
8030
Douglas Gregor5bee2582012-06-04 00:15:09 +00008031 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8032 VisibleTypeConversionsQuals.hasVolatile();
8033 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008034 // volatile version
8035 ParamTypes[0] =
8036 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00008037 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008038 /*IsAssigmentOperator=*/isEqualOp);
8039 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00008040
8041 if (!(*Ptr).isRestrictQualified() &&
8042 VisibleTypeConversionsQuals.hasRestrict()) {
8043 // restrict version
8044 ParamTypes[0]
8045 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00008046 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00008047 /*IsAssigmentOperator=*/isEqualOp);
8048
8049 if (NeedVolatile) {
8050 // volatile restrict version
8051 ParamTypes[0]
8052 = S.Context.getLValueReferenceType(
8053 S.Context.getCVRQualifiedType(*Ptr,
8054 (Qualifiers::Volatile |
8055 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00008056 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00008057 /*IsAssigmentOperator=*/isEqualOp);
8058 }
8059 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008060 }
8061
8062 if (isEqualOp) {
8063 for (BuiltinCandidateTypeSet::iterator
8064 Ptr = CandidateTypes[1].pointer_begin(),
8065 PtrEnd = CandidateTypes[1].pointer_end();
8066 Ptr != PtrEnd; ++Ptr) {
8067 // Make sure we don't add the same candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00008068 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008069 continue;
8070
Chandler Carruth8e543b32010-12-12 08:17:55 +00008071 QualType ParamTypes[2] = {
8072 S.Context.getLValueReferenceType(*Ptr),
8073 *Ptr,
8074 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008075
8076 // non-volatile version
Richard Smithe54c3072013-05-05 15:51:06 +00008077 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008078 /*IsAssigmentOperator=*/true);
8079
Douglas Gregor5bee2582012-06-04 00:15:09 +00008080 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8081 VisibleTypeConversionsQuals.hasVolatile();
8082 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008083 // volatile version
8084 ParamTypes[0] =
8085 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00008086 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8087 /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008088 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00008089
8090 if (!(*Ptr).isRestrictQualified() &&
8091 VisibleTypeConversionsQuals.hasRestrict()) {
8092 // restrict version
8093 ParamTypes[0]
8094 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00008095 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8096 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00008097
8098 if (NeedVolatile) {
8099 // volatile restrict version
8100 ParamTypes[0]
8101 = S.Context.getLValueReferenceType(
8102 S.Context.getCVRQualifiedType(*Ptr,
8103 (Qualifiers::Volatile |
8104 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00008105 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8106 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00008107 }
8108 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008109 }
8110 }
8111 }
8112
8113 // C++ [over.built]p18:
8114 //
8115 // For every triple (L, VQ, R), where L is an arithmetic type,
8116 // VQ is either volatile or empty, and R is a promoted
8117 // arithmetic type, there exist candidate operator functions of
8118 // the form
8119 //
8120 // VQ L& operator=(VQ L&, R);
8121 // VQ L& operator*=(VQ L&, R);
8122 // VQ L& operator/=(VQ L&, R);
8123 // VQ L& operator+=(VQ L&, R);
8124 // VQ L& operator-=(VQ L&, R);
8125 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00008126 if (!HasArithmeticOrEnumeralCandidateType)
8127 return;
8128
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008129 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
8130 for (unsigned Right = FirstPromotedArithmeticType;
8131 Right < LastPromotedArithmeticType; ++Right) {
8132 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00008133 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008134
8135 // Add this built-in operator as a candidate (VQ is empty).
8136 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00008137 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smithe54c3072013-05-05 15:51:06 +00008138 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008139 /*IsAssigmentOperator=*/isEqualOp);
8140
8141 // Add this built-in operator as a candidate (VQ is 'volatile').
8142 if (VisibleTypeConversionsQuals.hasVolatile()) {
8143 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00008144 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008145 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00008146 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008147 /*IsAssigmentOperator=*/isEqualOp);
8148 }
8149 }
8150 }
8151
8152 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8153 for (BuiltinCandidateTypeSet::iterator
8154 Vec1 = CandidateTypes[0].vector_begin(),
8155 Vec1End = CandidateTypes[0].vector_end();
8156 Vec1 != Vec1End; ++Vec1) {
8157 for (BuiltinCandidateTypeSet::iterator
8158 Vec2 = CandidateTypes[1].vector_begin(),
8159 Vec2End = CandidateTypes[1].vector_end();
8160 Vec2 != Vec2End; ++Vec2) {
8161 QualType ParamTypes[2];
8162 ParamTypes[1] = *Vec2;
8163 // Add this built-in operator as a candidate (VQ is empty).
8164 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
Richard Smithe54c3072013-05-05 15:51:06 +00008165 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008166 /*IsAssigmentOperator=*/isEqualOp);
8167
8168 // Add this built-in operator as a candidate (VQ is 'volatile').
8169 if (VisibleTypeConversionsQuals.hasVolatile()) {
8170 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
8171 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00008172 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008173 /*IsAssigmentOperator=*/isEqualOp);
8174 }
8175 }
8176 }
8177 }
8178
8179 // C++ [over.built]p22:
8180 //
8181 // For every triple (L, VQ, R), where L is an integral type, VQ
8182 // is either volatile or empty, and R is a promoted integral
8183 // type, there exist candidate operator functions of the form
8184 //
8185 // VQ L& operator%=(VQ L&, R);
8186 // VQ L& operator<<=(VQ L&, R);
8187 // VQ L& operator>>=(VQ L&, R);
8188 // VQ L& operator&=(VQ L&, R);
8189 // VQ L& operator^=(VQ L&, R);
8190 // VQ L& operator|=(VQ L&, R);
8191 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00008192 if (!HasArithmeticOrEnumeralCandidateType)
8193 return;
8194
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008195 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8196 for (unsigned Right = FirstPromotedIntegralType;
8197 Right < LastPromotedIntegralType; ++Right) {
8198 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00008199 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008200
8201 // Add this built-in operator as a candidate (VQ is empty).
8202 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00008203 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smithe54c3072013-05-05 15:51:06 +00008204 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008205 if (VisibleTypeConversionsQuals.hasVolatile()) {
8206 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00008207 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008208 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8209 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00008210 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008211 }
8212 }
8213 }
8214 }
8215
8216 // C++ [over.operator]p23:
8217 //
8218 // There also exist candidate operator functions of the form
8219 //
8220 // bool operator!(bool);
8221 // bool operator&&(bool, bool);
8222 // bool operator||(bool, bool);
8223 void addExclaimOverload() {
8224 QualType ParamTy = S.Context.BoolTy;
Richard Smithe54c3072013-05-05 15:51:06 +00008225 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008226 /*IsAssignmentOperator=*/false,
8227 /*NumContextualBoolArguments=*/1);
8228 }
8229 void addAmpAmpOrPipePipeOverload() {
8230 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
Richard Smithe54c3072013-05-05 15:51:06 +00008231 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008232 /*IsAssignmentOperator=*/false,
8233 /*NumContextualBoolArguments=*/2);
8234 }
8235
8236 // C++ [over.built]p13:
8237 //
8238 // For every cv-qualified or cv-unqualified object type T there
8239 // exist candidate operator functions of the form
8240 //
8241 // T* operator+(T*, ptrdiff_t); [ABOVE]
8242 // T& operator[](T*, ptrdiff_t);
8243 // T* operator-(T*, ptrdiff_t); [ABOVE]
8244 // T* operator+(ptrdiff_t, T*); [ABOVE]
8245 // T& operator[](ptrdiff_t, T*);
8246 void addSubscriptOverloads() {
8247 for (BuiltinCandidateTypeSet::iterator
8248 Ptr = CandidateTypes[0].pointer_begin(),
8249 PtrEnd = CandidateTypes[0].pointer_end();
8250 Ptr != PtrEnd; ++Ptr) {
8251 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8252 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00008253 if (!PointeeType->isObjectType())
8254 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008255
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008256 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8257
8258 // T& operator[](T*, ptrdiff_t)
Richard Smithe54c3072013-05-05 15:51:06 +00008259 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008260 }
8261
8262 for (BuiltinCandidateTypeSet::iterator
8263 Ptr = CandidateTypes[1].pointer_begin(),
8264 PtrEnd = CandidateTypes[1].pointer_end();
8265 Ptr != PtrEnd; ++Ptr) {
8266 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8267 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00008268 if (!PointeeType->isObjectType())
8269 continue;
8270
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008271 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8272
8273 // T& operator[](ptrdiff_t, T*)
Richard Smithe54c3072013-05-05 15:51:06 +00008274 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008275 }
8276 }
8277
8278 // C++ [over.built]p11:
8279 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8280 // C1 is the same type as C2 or is a derived class of C2, T is an object
8281 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8282 // there exist candidate operator functions of the form
8283 //
8284 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8285 //
8286 // where CV12 is the union of CV1 and CV2.
8287 void addArrowStarOverloads() {
8288 for (BuiltinCandidateTypeSet::iterator
8289 Ptr = CandidateTypes[0].pointer_begin(),
8290 PtrEnd = CandidateTypes[0].pointer_end();
8291 Ptr != PtrEnd; ++Ptr) {
8292 QualType C1Ty = (*Ptr);
8293 QualType C1;
8294 QualifierCollector Q1;
8295 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8296 if (!isa<RecordType>(C1))
8297 continue;
8298 // heuristic to reduce number of builtin candidates in the set.
8299 // Add volatile/restrict version only if there are conversions to a
8300 // volatile/restrict type.
8301 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8302 continue;
8303 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8304 continue;
8305 for (BuiltinCandidateTypeSet::iterator
8306 MemPtr = CandidateTypes[1].member_pointer_begin(),
8307 MemPtrEnd = CandidateTypes[1].member_pointer_end();
8308 MemPtr != MemPtrEnd; ++MemPtr) {
8309 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8310 QualType C2 = QualType(mptr->getClass(), 0);
8311 C2 = C2.getUnqualifiedType();
Richard Smith0f59cb32015-12-18 21:45:41 +00008312 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008313 break;
8314 QualType ParamTypes[2] = { *Ptr, *MemPtr };
8315 // build CV12 T&
8316 QualType T = mptr->getPointeeType();
8317 if (!VisibleTypeConversionsQuals.hasVolatile() &&
8318 T.isVolatileQualified())
8319 continue;
8320 if (!VisibleTypeConversionsQuals.hasRestrict() &&
8321 T.isRestrictQualified())
8322 continue;
8323 T = Q1.apply(S.Context, T);
8324 QualType ResultTy = S.Context.getLValueReferenceType(T);
Richard Smithe54c3072013-05-05 15:51:06 +00008325 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008326 }
8327 }
8328 }
8329
8330 // Note that we don't consider the first argument, since it has been
8331 // contextually converted to bool long ago. The candidates below are
8332 // therefore added as binary.
8333 //
8334 // C++ [over.built]p25:
8335 // For every type T, where T is a pointer, pointer-to-member, or scoped
8336 // enumeration type, there exist candidate operator functions of the form
8337 //
8338 // T operator?(bool, T, T);
8339 //
8340 void addConditionalOperatorOverloads() {
8341 /// Set of (canonical) types that we've already handled.
8342 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8343
8344 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8345 for (BuiltinCandidateTypeSet::iterator
8346 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8347 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8348 Ptr != PtrEnd; ++Ptr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008349 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008350 continue;
8351
8352 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smithe54c3072013-05-05 15:51:06 +00008353 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008354 }
8355
8356 for (BuiltinCandidateTypeSet::iterator
8357 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8358 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8359 MemPtr != MemPtrEnd; ++MemPtr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008360 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008361 continue;
8362
8363 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smithe54c3072013-05-05 15:51:06 +00008364 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008365 }
8366
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008367 if (S.getLangOpts().CPlusPlus11) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008368 for (BuiltinCandidateTypeSet::iterator
8369 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8370 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8371 Enum != EnumEnd; ++Enum) {
8372 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8373 continue;
8374
David Blaikie82e95a32014-11-19 07:49:47 +00008375 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008376 continue;
8377
8378 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smithe54c3072013-05-05 15:51:06 +00008379 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008380 }
8381 }
8382 }
8383 }
8384};
8385
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008386} // end anonymous namespace
8387
8388/// AddBuiltinOperatorCandidates - Add the appropriate built-in
8389/// operator overloads to the candidate set (C++ [over.built]), based
8390/// on the operator @p Op and the arguments given. For example, if the
8391/// operator is a binary '+', this routine might add "int
8392/// operator+(int, int)" to cover integer addition.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00008393void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8394 SourceLocation OpLoc,
8395 ArrayRef<Expr *> Args,
8396 OverloadCandidateSet &CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00008397 // Find all of the types that the arguments can convert to, but only
8398 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00008399 // that make use of these types. Also record whether we encounter non-record
8400 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00008401 Qualifiers VisibleTypeConversionsQuals;
8402 VisibleTypeConversionsQuals.addConst();
Richard Smithe54c3072013-05-05 15:51:06 +00008403 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00008404 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00008405
8406 bool HasNonRecordCandidateType = false;
8407 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008408 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Richard Smithe54c3072013-05-05 15:51:06 +00008409 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Benjamin Kramer57dddd482015-02-17 21:55:18 +00008410 CandidateTypes.emplace_back(*this);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00008411 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8412 OpLoc,
8413 true,
8414 (Op == OO_Exclaim ||
8415 Op == OO_AmpAmp ||
8416 Op == OO_PipePipe),
8417 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00008418 HasNonRecordCandidateType = HasNonRecordCandidateType ||
8419 CandidateTypes[ArgIdx].hasNonRecordTypes();
8420 HasArithmeticOrEnumeralCandidateType =
8421 HasArithmeticOrEnumeralCandidateType ||
8422 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00008423 }
Douglas Gregora11693b2008-11-12 17:17:38 +00008424
Chandler Carruth00a38332010-12-13 01:44:01 +00008425 // Exit early when no non-record types have been added to the candidate set
8426 // for any of the arguments to the operator.
Douglas Gregor877d4eb2011-10-10 14:05:31 +00008427 //
8428 // We can't exit early for !, ||, or &&, since there we have always have
8429 // 'bool' overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00008430 if (!HasNonRecordCandidateType &&
Douglas Gregor877d4eb2011-10-10 14:05:31 +00008431 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth00a38332010-12-13 01:44:01 +00008432 return;
8433
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008434 // Setup an object to manage the common state for building overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00008435 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008436 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00008437 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008438 CandidateTypes, CandidateSet);
8439
8440 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00008441 switch (Op) {
8442 case OO_None:
8443 case NUM_OVERLOADED_OPERATORS:
David Blaikie83d382b2011-09-23 05:06:16 +00008444 llvm_unreachable("Expected an overloaded operator");
Douglas Gregora11693b2008-11-12 17:17:38 +00008445
Chandler Carruth5184de02010-12-12 08:51:33 +00008446 case OO_New:
8447 case OO_Delete:
8448 case OO_Array_New:
8449 case OO_Array_Delete:
8450 case OO_Call:
David Blaikie83d382b2011-09-23 05:06:16 +00008451 llvm_unreachable(
8452 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruth5184de02010-12-12 08:51:33 +00008453
8454 case OO_Comma:
8455 case OO_Arrow:
Richard Smith9f690bd2015-10-27 06:02:45 +00008456 case OO_Coawait:
Chandler Carruth5184de02010-12-12 08:51:33 +00008457 // C++ [over.match.oper]p3:
Richard Smith9f690bd2015-10-27 06:02:45 +00008458 // -- For the operator ',', the unary operator '&', the
8459 // operator '->', or the operator 'co_await', the
8460 // built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00008461 break;
8462
8463 case OO_Plus: // '+' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008464 if (Args.size() == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008465 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00008466 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00008467
8468 case OO_Minus: // '-' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008469 if (Args.size() == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008470 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008471 } else {
8472 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8473 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8474 }
Douglas Gregord08452f2008-11-19 15:42:04 +00008475 break;
8476
Chandler Carruth5184de02010-12-12 08:51:33 +00008477 case OO_Star: // '*' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008478 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008479 OpBuilder.addUnaryStarPointerOverloads();
8480 else
8481 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8482 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008483
Chandler Carruth5184de02010-12-12 08:51:33 +00008484 case OO_Slash:
8485 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008486 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008487
8488 case OO_PlusPlus:
8489 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008490 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8491 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00008492 break;
8493
Douglas Gregor84605ae2009-08-24 13:43:27 +00008494 case OO_EqualEqual:
8495 case OO_ExclaimEqual:
Richard Smith5e9746f2016-10-21 22:00:42 +00008496 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00008497 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008498
Douglas Gregora11693b2008-11-12 17:17:38 +00008499 case OO_Less:
8500 case OO_Greater:
8501 case OO_LessEqual:
8502 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00008503 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00008504 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
8505 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008506
Douglas Gregora11693b2008-11-12 17:17:38 +00008507 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00008508 case OO_Caret:
8509 case OO_Pipe:
8510 case OO_LessLess:
8511 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008512 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00008513 break;
8514
Chandler Carruth5184de02010-12-12 08:51:33 +00008515 case OO_Amp: // '&' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008516 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008517 // C++ [over.match.oper]p3:
8518 // -- For the operator ',', the unary operator '&', or the
8519 // operator '->', the built-in candidates set is empty.
8520 break;
8521
8522 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8523 break;
8524
8525 case OO_Tilde:
8526 OpBuilder.addUnaryTildePromotedIntegralOverloads();
8527 break;
8528
Douglas Gregora11693b2008-11-12 17:17:38 +00008529 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008530 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00008531 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00008532
8533 case OO_PlusEqual:
8534 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008535 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008536 // Fall through.
8537
8538 case OO_StarEqual:
8539 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008540 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008541 break;
8542
8543 case OO_PercentEqual:
8544 case OO_LessLessEqual:
8545 case OO_GreaterGreaterEqual:
8546 case OO_AmpEqual:
8547 case OO_CaretEqual:
8548 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008549 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008550 break;
8551
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008552 case OO_Exclaim:
8553 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00008554 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008555
Douglas Gregora11693b2008-11-12 17:17:38 +00008556 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008557 case OO_PipePipe:
8558 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00008559 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008560
8561 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008562 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008563 break;
8564
8565 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008566 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008567 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00008568
8569 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008570 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008571 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8572 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008573 }
8574}
8575
Douglas Gregore254f902009-02-04 00:32:51 +00008576/// \brief Add function candidates found via argument-dependent lookup
8577/// to the set of overloading candidates.
8578///
8579/// This routine performs argument-dependent name lookup based on the
8580/// given function name (which may also be an operator name) and adds
8581/// all of the overload candidates found by ADL to the overload
8582/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00008583void
Douglas Gregore254f902009-02-04 00:32:51 +00008584Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smith100b24a2014-04-17 01:52:14 +00008585 SourceLocation Loc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008586 ArrayRef<Expr *> Args,
Douglas Gregor739b107a2011-03-03 02:41:12 +00008587 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008588 OverloadCandidateSet& CandidateSet,
Richard Smithb6626742012-10-18 17:56:02 +00008589 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00008590 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00008591
John McCall91f61fc2010-01-26 06:04:06 +00008592 // FIXME: This approach for uniquing ADL results (and removing
8593 // redundant candidates from the set) relies on pointer-equality,
8594 // which means we need to key off the canonical decl. However,
8595 // always going back to the canonical decl might not get us the
8596 // right set of default arguments. What default arguments are
8597 // we supposed to consider on ADL candidates, anyway?
8598
Douglas Gregorcabea402009-09-22 15:41:20 +00008599 // FIXME: Pass in the explicit template arguments?
Richard Smith100b24a2014-04-17 01:52:14 +00008600 ArgumentDependentLookup(Name, Loc, Args, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00008601
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008602 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008603 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8604 CandEnd = CandidateSet.end();
8605 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00008606 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00008607 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00008608 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00008609 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00008610 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008611
8612 // For each of the ADL candidates we found, add it to the overload
8613 // set.
John McCall8fe68082010-01-26 07:16:45 +00008614 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00008615 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00008616 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00008617 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00008618 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008619
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008620 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8621 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00008622 } else
John McCall4c4c1df2010-01-26 03:27:55 +00008623 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00008624 FoundDecl, ExplicitTemplateArgs,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00008625 Args, CandidateSet, PartialOverloading);
Douglas Gregor15448f82009-06-27 21:05:07 +00008626 }
Douglas Gregore254f902009-02-04 00:32:51 +00008627}
8628
George Burgess IV3dc166912016-05-10 01:59:34 +00008629namespace {
8630enum class Comparison { Equal, Better, Worse };
8631}
8632
8633/// Compares the enable_if attributes of two FunctionDecls, for the purposes of
8634/// overload resolution.
8635///
8636/// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
8637/// Cand1's first N enable_if attributes have precisely the same conditions as
8638/// Cand2's first N enable_if attributes (where N = the number of enable_if
8639/// attributes on Cand2), and Cand1 has more than N enable_if attributes.
8640///
8641/// Note that you can have a pair of candidates such that Cand1's enable_if
8642/// attributes are worse than Cand2's, and Cand2's enable_if attributes are
8643/// worse than Cand1's.
8644static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
8645 const FunctionDecl *Cand2) {
8646 // Common case: One (or both) decls don't have enable_if attrs.
8647 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
8648 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
8649 if (!Cand1Attr || !Cand2Attr) {
8650 if (Cand1Attr == Cand2Attr)
8651 return Comparison::Equal;
8652 return Cand1Attr ? Comparison::Better : Comparison::Worse;
8653 }
George Burgess IV2a6150d2015-10-16 01:17:38 +00008654
8655 // FIXME: The next several lines are just
8656 // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8657 // instead of reverse order which is how they're stored in the AST.
8658 auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1);
8659 auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2);
8660
George Burgess IV3dc166912016-05-10 01:59:34 +00008661 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
8662 // has fewer enable_if attributes than Cand2.
8663 if (Cand1Attrs.size() < Cand2Attrs.size())
8664 return Comparison::Worse;
George Burgess IV2a6150d2015-10-16 01:17:38 +00008665
8666 auto Cand1I = Cand1Attrs.begin();
8667 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
8668 for (auto &Cand2A : Cand2Attrs) {
8669 Cand1ID.clear();
8670 Cand2ID.clear();
8671
8672 auto &Cand1A = *Cand1I++;
8673 Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true);
8674 Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true);
8675 if (Cand1ID != Cand2ID)
George Burgess IV3dc166912016-05-10 01:59:34 +00008676 return Comparison::Worse;
George Burgess IV2a6150d2015-10-16 01:17:38 +00008677 }
8678
George Burgess IV3dc166912016-05-10 01:59:34 +00008679 return Cand1I == Cand1Attrs.end() ? Comparison::Equal : Comparison::Better;
George Burgess IV2a6150d2015-10-16 01:17:38 +00008680}
8681
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008682/// isBetterOverloadCandidate - Determines whether the first overload
8683/// candidate is a better candidate than the second (C++ 13.3.3p1).
Richard Smith17c00b42014-11-12 01:24:00 +00008684bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1,
8685 const OverloadCandidate &Cand2,
8686 SourceLocation Loc,
8687 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008688 // Define viable functions to be better candidates than non-viable
8689 // functions.
8690 if (!Cand2.Viable)
8691 return Cand1.Viable;
8692 else if (!Cand1.Viable)
8693 return false;
8694
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008695 // C++ [over.match.best]p1:
8696 //
8697 // -- if F is a static member function, ICS1(F) is defined such
8698 // that ICS1(F) is neither better nor worse than ICS1(G) for
8699 // any function G, and, symmetrically, ICS1(G) is neither
8700 // better nor worse than ICS1(F).
8701 unsigned StartArg = 0;
8702 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8703 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008704
George Burgess IVfbad5b22016-09-07 20:03:19 +00008705 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
8706 // We don't allow incompatible pointer conversions in C++.
8707 if (!S.getLangOpts().CPlusPlus)
8708 return ICS.isStandard() &&
8709 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
8710
8711 // The only ill-formed conversion we allow in C++ is the string literal to
8712 // char* conversion, which is only considered ill-formed after C++11.
8713 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
8714 hasDeprecatedStringLiteralToCharPtrConversion(ICS);
8715 };
8716
8717 // Define functions that don't require ill-formed conversions for a given
8718 // argument to be better candidates than functions that do.
8719 unsigned NumArgs = Cand1.NumConversions;
8720 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
8721 bool HasBetterConversion = false;
8722 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
8723 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
8724 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
8725 if (Cand1Bad != Cand2Bad) {
8726 if (Cand1Bad)
8727 return false;
8728 HasBetterConversion = true;
8729 }
8730 }
8731
8732 if (HasBetterConversion)
8733 return true;
8734
Douglas Gregord3cb3562009-07-07 23:38:56 +00008735 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00008736 // A viable function F1 is defined to be a better function than another
8737 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00008738 // conversion sequence than ICSi(F2), and then...
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008739 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Richard Smith0f59cb32015-12-18 21:45:41 +00008740 switch (CompareImplicitConversionSequences(S, Loc,
John McCall5c32be02010-08-24 20:38:10 +00008741 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008742 Cand2.Conversions[ArgIdx])) {
8743 case ImplicitConversionSequence::Better:
8744 // Cand1 has a better conversion sequence.
8745 HasBetterConversion = true;
8746 break;
8747
8748 case ImplicitConversionSequence::Worse:
8749 // Cand1 can't be better than Cand2.
8750 return false;
8751
8752 case ImplicitConversionSequence::Indistinguishable:
8753 // Do nothing.
8754 break;
8755 }
8756 }
8757
Mike Stump11289f42009-09-09 15:08:12 +00008758 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00008759 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008760 if (HasBetterConversion)
8761 return true;
8762
Douglas Gregora1f013e2008-11-07 22:36:19 +00008763 // -- the context is an initialization by user-defined conversion
8764 // (see 8.5, 13.3.1.5) and the standard conversion sequence
8765 // from the return type of F1 to the destination type (i.e.,
8766 // the type of the entity being initialized) is a better
8767 // conversion sequence than the standard conversion sequence
8768 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00008769 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00008770 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00008771 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregor2837aa22012-02-22 17:32:19 +00008772 // First check whether we prefer one of the conversion functions over the
8773 // other. This only distinguishes the results in non-standard, extension
8774 // cases such as the conversion from a lambda closure type to a function
8775 // pointer or block.
Richard Smithec2748a2014-05-17 04:36:39 +00008776 ImplicitConversionSequence::CompareKind Result =
8777 compareConversionFunctions(S, Cand1.Function, Cand2.Function);
8778 if (Result == ImplicitConversionSequence::Indistinguishable)
Richard Smith0f59cb32015-12-18 21:45:41 +00008779 Result = CompareStandardConversionSequences(S, Loc,
Richard Smithec2748a2014-05-17 04:36:39 +00008780 Cand1.FinalConversion,
8781 Cand2.FinalConversion);
Richard Smith6fdeaab2014-05-17 01:58:45 +00008782
Richard Smithec2748a2014-05-17 04:36:39 +00008783 if (Result != ImplicitConversionSequence::Indistinguishable)
8784 return Result == ImplicitConversionSequence::Better;
Richard Smith6fdeaab2014-05-17 01:58:45 +00008785
8786 // FIXME: Compare kind of reference binding if conversion functions
8787 // convert to a reference type used in direct reference binding, per
8788 // C++14 [over.match.best]p1 section 2 bullet 3.
8789 }
8790
8791 // -- F1 is a non-template function and F2 is a function template
8792 // specialization, or, if not that,
8793 bool Cand1IsSpecialization = Cand1.Function &&
8794 Cand1.Function->getPrimaryTemplate();
8795 bool Cand2IsSpecialization = Cand2.Function &&
8796 Cand2.Function->getPrimaryTemplate();
8797 if (Cand1IsSpecialization != Cand2IsSpecialization)
8798 return Cand2IsSpecialization;
8799
8800 // -- F1 and F2 are function template specializations, and the function
8801 // template for F1 is more specialized than the template for F2
8802 // according to the partial ordering rules described in 14.5.5.2, or,
8803 // if not that,
8804 if (Cand1IsSpecialization && Cand2IsSpecialization) {
8805 if (FunctionTemplateDecl *BetterTemplate
8806 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
8807 Cand2.Function->getPrimaryTemplate(),
8808 Loc,
8809 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
8810 : TPOC_Call,
8811 Cand1.ExplicitCallArguments,
8812 Cand2.ExplicitCallArguments))
8813 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregora1f013e2008-11-07 22:36:19 +00008814 }
8815
Richard Smith5179eb72016-06-28 19:03:57 +00008816 // FIXME: Work around a defect in the C++17 inheriting constructor wording.
8817 // A derived-class constructor beats an (inherited) base class constructor.
8818 bool Cand1IsInherited =
8819 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
8820 bool Cand2IsInherited =
8821 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
8822 if (Cand1IsInherited != Cand2IsInherited)
8823 return Cand2IsInherited;
8824 else if (Cand1IsInherited) {
8825 assert(Cand2IsInherited);
8826 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
8827 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
8828 if (Cand1Class->isDerivedFrom(Cand2Class))
8829 return true;
8830 if (Cand2Class->isDerivedFrom(Cand1Class))
8831 return false;
8832 // Inherited from sibling base classes: still ambiguous.
8833 }
8834
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008835 // Check for enable_if value-based overload resolution.
George Burgess IV3dc166912016-05-10 01:59:34 +00008836 if (Cand1.Function && Cand2.Function) {
8837 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
8838 if (Cmp != Comparison::Equal)
8839 return Cmp == Comparison::Better;
8840 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008841
Justin Lebar25c4a812016-03-29 16:24:16 +00008842 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
Artem Belevich94a55e82015-09-22 17:22:59 +00008843 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
8844 return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
8845 S.IdentifyCUDAPreference(Caller, Cand2.Function);
8846 }
8847
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008848 bool HasPS1 = Cand1.Function != nullptr &&
8849 functionHasPassObjectSizeParams(Cand1.Function);
8850 bool HasPS2 = Cand2.Function != nullptr &&
8851 functionHasPassObjectSizeParams(Cand2.Function);
8852 return HasPS1 != HasPS2 && HasPS1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008853}
8854
Richard Smith2dbe4042015-11-04 19:26:32 +00008855/// Determine whether two declarations are "equivalent" for the purposes of
Richard Smith26210db2015-11-13 03:52:13 +00008856/// name lookup and overload resolution. This applies when the same internal/no
8857/// linkage entity is defined by two modules (probably by textually including
Richard Smith2dbe4042015-11-04 19:26:32 +00008858/// the same header). In such a case, we don't consider the declarations to
8859/// declare the same entity, but we also don't want lookups with both
8860/// declarations visible to be ambiguous in some cases (this happens when using
8861/// a modularized libstdc++).
8862bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
8863 const NamedDecl *B) {
Richard Smith26210db2015-11-13 03:52:13 +00008864 auto *VA = dyn_cast_or_null<ValueDecl>(A);
8865 auto *VB = dyn_cast_or_null<ValueDecl>(B);
8866 if (!VA || !VB)
8867 return false;
8868
8869 // The declarations must be declaring the same name as an internal linkage
8870 // entity in different modules.
8871 if (!VA->getDeclContext()->getRedeclContext()->Equals(
8872 VB->getDeclContext()->getRedeclContext()) ||
8873 getOwningModule(const_cast<ValueDecl *>(VA)) ==
8874 getOwningModule(const_cast<ValueDecl *>(VB)) ||
8875 VA->isExternallyVisible() || VB->isExternallyVisible())
8876 return false;
8877
8878 // Check that the declarations appear to be equivalent.
8879 //
8880 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
8881 // For constants and functions, we should check the initializer or body is
8882 // the same. For non-constant variables, we shouldn't allow it at all.
8883 if (Context.hasSameType(VA->getType(), VB->getType()))
8884 return true;
8885
8886 // Enum constants within unnamed enumerations will have different types, but
8887 // may still be similar enough to be interchangeable for our purposes.
8888 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
8889 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
8890 // Only handle anonymous enums. If the enumerations were named and
8891 // equivalent, they would have been merged to the same type.
8892 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
8893 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
8894 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
8895 !Context.hasSameType(EnumA->getIntegerType(),
8896 EnumB->getIntegerType()))
8897 return false;
8898 // Allow this only if the value is the same for both enumerators.
8899 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
8900 }
8901 }
8902
8903 // Nothing else is sufficiently similar.
8904 return false;
Richard Smith2dbe4042015-11-04 19:26:32 +00008905}
8906
8907void Sema::diagnoseEquivalentInternalLinkageDeclarations(
8908 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
8909 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
8910
8911 Module *M = getOwningModule(const_cast<NamedDecl*>(D));
8912 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
8913 << !M << (M ? M->getFullModuleName() : "");
8914
8915 for (auto *E : Equiv) {
8916 Module *M = getOwningModule(const_cast<NamedDecl*>(E));
8917 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
8918 << !M << (M ? M->getFullModuleName() : "");
8919 }
Richard Smith896c66e2015-10-21 07:13:52 +00008920}
8921
Mike Stump11289f42009-09-09 15:08:12 +00008922/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008923/// within an overload candidate set.
8924///
James Dennettffad8b72012-06-22 08:10:18 +00008925/// \param Loc The location of the function name (or operator symbol) for
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008926/// which overload resolution occurs.
8927///
James Dennettffad8b72012-06-22 08:10:18 +00008928/// \param Best If overload resolution was successful or found a deleted
8929/// function, \p Best points to the candidate function found.
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008930///
8931/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00008932OverloadingResult
8933OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00008934 iterator &Best,
Chandler Carruth30141632011-02-25 19:41:05 +00008935 bool UserDefinedConversion) {
Artem Belevich18609102016-02-12 18:29:18 +00008936 llvm::SmallVector<OverloadCandidate *, 16> Candidates;
8937 std::transform(begin(), end(), std::back_inserter(Candidates),
8938 [](OverloadCandidate &Cand) { return &Cand; });
8939
Justin Lebar66a2ab92016-08-10 00:40:43 +00008940 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
8941 // are accepted by both clang and NVCC. However, during a particular
Artem Belevich18609102016-02-12 18:29:18 +00008942 // compilation mode only one call variant is viable. We need to
8943 // exclude non-viable overload candidates from consideration based
8944 // only on their host/device attributes. Specifically, if one
8945 // candidate call is WrongSide and the other is SameSide, we ignore
8946 // the WrongSide candidate.
Justin Lebar25c4a812016-03-29 16:24:16 +00008947 if (S.getLangOpts().CUDA) {
Artem Belevich18609102016-02-12 18:29:18 +00008948 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
8949 bool ContainsSameSideCandidate =
8950 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
8951 return Cand->Function &&
8952 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
8953 Sema::CFP_SameSide;
8954 });
8955 if (ContainsSameSideCandidate) {
8956 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
8957 return Cand->Function &&
8958 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
8959 Sema::CFP_WrongSide;
8960 };
8961 Candidates.erase(std::remove_if(Candidates.begin(), Candidates.end(),
8962 IsWrongSideCandidate),
8963 Candidates.end());
8964 }
8965 }
8966
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008967 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00008968 Best = end();
Artem Belevich18609102016-02-12 18:29:18 +00008969 for (auto *Cand : Candidates)
John McCall5c32be02010-08-24 20:38:10 +00008970 if (Cand->Viable)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008971 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00008972 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008973 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008974
8975 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00008976 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008977 return OR_No_Viable_Function;
8978
Richard Smith2dbe4042015-11-04 19:26:32 +00008979 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
Richard Smith896c66e2015-10-21 07:13:52 +00008980
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008981 // Make sure that this function is better than every other viable
8982 // function. If not, we have an ambiguity.
Artem Belevich18609102016-02-12 18:29:18 +00008983 for (auto *Cand : Candidates) {
Mike Stump11289f42009-09-09 15:08:12 +00008984 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008985 Cand != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008986 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00008987 UserDefinedConversion)) {
Richard Smith2dbe4042015-11-04 19:26:32 +00008988 if (S.isEquivalentInternalLinkageDeclaration(Best->Function,
8989 Cand->Function)) {
8990 EquivalentCands.push_back(Cand->Function);
Richard Smith896c66e2015-10-21 07:13:52 +00008991 continue;
8992 }
8993
John McCall5c32be02010-08-24 20:38:10 +00008994 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008995 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00008996 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008997 }
Mike Stump11289f42009-09-09 15:08:12 +00008998
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008999 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00009000 if (Best->Function &&
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00009001 (Best->Function->isDeleted() ||
9002 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor171c45a2009-02-18 21:56:37 +00009003 return OR_Deleted;
9004
Richard Smith2dbe4042015-11-04 19:26:32 +00009005 if (!EquivalentCands.empty())
9006 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
9007 EquivalentCands);
Richard Smith896c66e2015-10-21 07:13:52 +00009008
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009009 return OR_Success;
9010}
9011
John McCall53262c92010-01-12 02:15:36 +00009012namespace {
9013
9014enum OverloadCandidateKind {
9015 oc_function,
9016 oc_method,
9017 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00009018 oc_function_template,
9019 oc_method_template,
9020 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00009021 oc_implicit_default_constructor,
9022 oc_implicit_copy_constructor,
Alexis Hunt119c10e2011-05-25 23:16:36 +00009023 oc_implicit_move_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00009024 oc_implicit_copy_assignment,
Alexis Hunt119c10e2011-05-25 23:16:36 +00009025 oc_implicit_move_assignment,
Richard Smith5179eb72016-06-28 19:03:57 +00009026 oc_inherited_constructor,
9027 oc_inherited_constructor_template
John McCall53262c92010-01-12 02:15:36 +00009028};
9029
George Burgess IVd66d37c2016-10-28 21:42:06 +00009030static OverloadCandidateKind
9031ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
9032 std::string &Description) {
John McCalle1ac8d12010-01-13 00:25:19 +00009033 bool isTemplate = false;
9034
9035 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
9036 isTemplate = true;
9037 Description = S.getTemplateArgumentBindingsText(
9038 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
9039 }
John McCallfd0b2f82010-01-06 09:43:14 +00009040
9041 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
Richard Smith5179eb72016-06-28 19:03:57 +00009042 if (!Ctor->isImplicit()) {
9043 if (isa<ConstructorUsingShadowDecl>(Found))
9044 return isTemplate ? oc_inherited_constructor_template
9045 : oc_inherited_constructor;
9046 else
9047 return isTemplate ? oc_constructor_template : oc_constructor;
9048 }
Sebastian Redl08905022011-02-05 19:23:19 +00009049
Alexis Hunt119c10e2011-05-25 23:16:36 +00009050 if (Ctor->isDefaultConstructor())
9051 return oc_implicit_default_constructor;
9052
9053 if (Ctor->isMoveConstructor())
9054 return oc_implicit_move_constructor;
9055
9056 assert(Ctor->isCopyConstructor() &&
9057 "unexpected sort of implicit constructor");
9058 return oc_implicit_copy_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00009059 }
9060
9061 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
9062 // This actually gets spelled 'candidate function' for now, but
9063 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00009064 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00009065 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00009066
Alexis Hunt119c10e2011-05-25 23:16:36 +00009067 if (Meth->isMoveAssignmentOperator())
9068 return oc_implicit_move_assignment;
9069
Douglas Gregor12695102012-02-10 08:36:38 +00009070 if (Meth->isCopyAssignmentOperator())
9071 return oc_implicit_copy_assignment;
9072
9073 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
9074 return oc_method;
John McCall53262c92010-01-12 02:15:36 +00009075 }
9076
John McCalle1ac8d12010-01-13 00:25:19 +00009077 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00009078}
9079
Richard Smith5179eb72016-06-28 19:03:57 +00009080void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
9081 // FIXME: It'd be nice to only emit a note once per using-decl per overload
9082 // set.
9083 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
9084 S.Diag(FoundDecl->getLocation(),
9085 diag::note_ovl_candidate_inherited_constructor)
9086 << Shadow->getNominatedBaseClass();
Sebastian Redl08905022011-02-05 19:23:19 +00009087}
9088
John McCall53262c92010-01-12 02:15:36 +00009089} // end anonymous namespace
9090
George Burgess IV5f21c712015-10-12 19:57:04 +00009091static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
9092 const FunctionDecl *FD) {
9093 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
9094 bool AlwaysTrue;
9095 if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
9096 return false;
9097 if (!AlwaysTrue)
9098 return false;
9099 }
9100 return true;
9101}
9102
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009103/// \brief Returns true if we can take the address of the function.
9104///
9105/// \param Complain - If true, we'll emit a diagnostic
9106/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
9107/// we in overload resolution?
9108/// \param Loc - The location of the statement we're complaining about. Ignored
9109/// if we're not complaining, or if we're in overload resolution.
9110static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
9111 bool Complain,
9112 bool InOverloadResolution,
9113 SourceLocation Loc) {
9114 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
9115 if (Complain) {
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009116 if (InOverloadResolution)
9117 S.Diag(FD->getLocStart(),
9118 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
9119 else
9120 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
9121 }
9122 return false;
9123 }
9124
George Burgess IV21081362016-07-24 23:12:40 +00009125 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
9126 return P->hasAttr<PassObjectSizeAttr>();
9127 });
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009128 if (I == FD->param_end())
9129 return true;
9130
9131 if (Complain) {
9132 // Add one to ParamNo because it's user-facing
9133 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
9134 if (InOverloadResolution)
9135 S.Diag(FD->getLocation(),
9136 diag::note_ovl_candidate_has_pass_object_size_params)
9137 << ParamNo;
9138 else
9139 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
9140 << FD << ParamNo;
9141 }
9142 return false;
9143}
9144
9145static bool checkAddressOfCandidateIsAvailable(Sema &S,
9146 const FunctionDecl *FD) {
9147 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
9148 /*InOverloadResolution=*/true,
9149 /*Loc=*/SourceLocation());
9150}
9151
9152bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
9153 bool Complain,
9154 SourceLocation Loc) {
9155 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
9156 /*InOverloadResolution=*/false,
9157 Loc);
9158}
9159
John McCall53262c92010-01-12 02:15:36 +00009160// Notes the location of an overload candidate.
Richard Smithc2bebe92016-05-11 20:37:46 +00009161void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
9162 QualType DestType, bool TakingAddress) {
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009163 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
9164 return;
9165
John McCalle1ac8d12010-01-13 00:25:19 +00009166 std::string FnDesc;
Richard Smithc2bebe92016-05-11 20:37:46 +00009167 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Found, Fn, FnDesc);
Richard Trieucaff2472011-11-23 22:32:32 +00009168 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
Saleem Abdulrasool78704fb2016-12-22 04:26:57 +00009169 << (unsigned) K << Fn << FnDesc;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009170
9171 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
Richard Trieucaff2472011-11-23 22:32:32 +00009172 Diag(Fn->getLocation(), PD);
Richard Smith5179eb72016-06-28 19:03:57 +00009173 MaybeEmitInheritedConstructorNote(*this, Found);
John McCallfd0b2f82010-01-06 09:43:14 +00009174}
9175
Nick Lewyckyed4265c2013-09-22 10:06:01 +00009176// Notes the location of all overload candidates designated through
Douglas Gregorb491ed32011-02-19 21:32:49 +00009177// OverloadedExpr
George Burgess IV5f21c712015-10-12 19:57:04 +00009178void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
9179 bool TakingAddress) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009180 assert(OverloadedExpr->getType() == Context.OverloadTy);
9181
9182 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
9183 OverloadExpr *OvlExpr = Ovl.Expression;
9184
9185 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9186 IEnd = OvlExpr->decls_end();
9187 I != IEnd; ++I) {
9188 if (FunctionTemplateDecl *FunTmpl =
9189 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Smithc2bebe92016-05-11 20:37:46 +00009190 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType,
George Burgess IV5f21c712015-10-12 19:57:04 +00009191 TakingAddress);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009192 } else if (FunctionDecl *Fun
9193 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Smithc2bebe92016-05-11 20:37:46 +00009194 NoteOverloadCandidate(*I, Fun, DestType, TakingAddress);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009195 }
9196 }
9197}
9198
John McCall0d1da222010-01-12 00:44:57 +00009199/// Diagnoses an ambiguous conversion. The partial diagnostic is the
9200/// "lead" diagnostic; it will be given two arguments, the source and
9201/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00009202void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
9203 Sema &S,
9204 SourceLocation CaretLoc,
9205 const PartialDiagnostic &PDiag) const {
9206 S.Diag(CaretLoc, PDiag)
9207 << Ambiguous.getFromType() << Ambiguous.getToType();
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00009208 // FIXME: The note limiting machinery is borrowed from
9209 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
9210 // refactoring here.
9211 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9212 unsigned CandsShown = 0;
9213 AmbiguousConversionSequence::const_iterator I, E;
9214 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
9215 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9216 break;
9217 ++CandsShown;
Richard Smithc2bebe92016-05-11 20:37:46 +00009218 S.NoteOverloadCandidate(I->first, I->second);
John McCall0d1da222010-01-12 00:44:57 +00009219 }
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00009220 if (I != E)
9221 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
John McCall12f97bc2010-01-08 04:41:39 +00009222}
9223
Richard Smith17c00b42014-11-12 01:24:00 +00009224static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009225 unsigned I, bool TakingCandidateAddress) {
John McCall6a61b522010-01-13 09:16:55 +00009226 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
9227 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00009228 assert(Cand->Function && "for now, candidate must be a function");
9229 FunctionDecl *Fn = Cand->Function;
9230
9231 // There's a conversion slot for the object argument if this is a
9232 // non-constructor method. Note that 'I' corresponds the
9233 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00009234 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00009235 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00009236 if (I == 0)
9237 isObjectArgument = true;
9238 else
9239 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00009240 }
9241
John McCalle1ac8d12010-01-13 00:25:19 +00009242 std::string FnDesc;
Richard Smithc2bebe92016-05-11 20:37:46 +00009243 OverloadCandidateKind FnKind =
9244 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
John McCalle1ac8d12010-01-13 00:25:19 +00009245
John McCall6a61b522010-01-13 09:16:55 +00009246 Expr *FromExpr = Conv.Bad.FromExpr;
9247 QualType FromTy = Conv.Bad.getFromType();
9248 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00009249
John McCallfb7ad0f2010-02-02 02:42:52 +00009250 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00009251 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00009252 Expr *E = FromExpr->IgnoreParens();
9253 if (isa<UnaryOperator>(E))
9254 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00009255 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00009256
9257 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
9258 << (unsigned) FnKind << FnDesc
9259 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9260 << ToTy << Name << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009261 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCallfb7ad0f2010-02-02 02:42:52 +00009262 return;
9263 }
9264
John McCall6d174642010-01-23 08:10:49 +00009265 // Do some hand-waving analysis to see if the non-viability is due
9266 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00009267 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
9268 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
9269 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
9270 CToTy = RT->getPointeeType();
9271 else {
9272 // TODO: detect and diagnose the full richness of const mismatches.
9273 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
Richard Trieucc3949d2016-02-18 22:34:54 +00009274 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
9275 CFromTy = FromPT->getPointeeType();
9276 CToTy = ToPT->getPointeeType();
9277 }
John McCall47000992010-01-14 03:28:57 +00009278 }
9279
9280 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
9281 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall47000992010-01-14 03:28:57 +00009282 Qualifiers FromQs = CFromTy.getQualifiers();
9283 Qualifiers ToQs = CToTy.getQualifiers();
9284
9285 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
9286 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
9287 << (unsigned) FnKind << FnDesc
9288 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9289 << FromTy
9290 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
9291 << (unsigned) isObjectArgument << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009292 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall47000992010-01-14 03:28:57 +00009293 return;
9294 }
9295
John McCall31168b02011-06-15 23:02:42 +00009296 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00009297 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCall31168b02011-06-15 23:02:42 +00009298 << (unsigned) FnKind << FnDesc
9299 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9300 << FromTy
9301 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
9302 << (unsigned) isObjectArgument << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009303 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall31168b02011-06-15 23:02:42 +00009304 return;
9305 }
9306
Douglas Gregoraec25842011-04-26 23:16:46 +00009307 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
9308 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
9309 << (unsigned) FnKind << FnDesc
9310 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9311 << FromTy
9312 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
9313 << (unsigned) isObjectArgument << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009314 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Douglas Gregoraec25842011-04-26 23:16:46 +00009315 return;
9316 }
9317
Andrey Bokhanko45d41322016-05-11 18:38:21 +00009318 if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
9319 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
9320 << (unsigned) FnKind << FnDesc
9321 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9322 << FromTy << FromQs.hasUnaligned() << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009323 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Andrey Bokhanko45d41322016-05-11 18:38:21 +00009324 return;
9325 }
9326
John McCall47000992010-01-14 03:28:57 +00009327 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
9328 assert(CVR && "unexpected qualifiers mismatch");
9329
9330 if (isObjectArgument) {
9331 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
9332 << (unsigned) FnKind << FnDesc
9333 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9334 << FromTy << (CVR - 1);
9335 } else {
9336 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
9337 << (unsigned) FnKind << FnDesc
9338 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9339 << FromTy << (CVR - 1) << I+1;
9340 }
Richard Smith5179eb72016-06-28 19:03:57 +00009341 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall47000992010-01-14 03:28:57 +00009342 return;
9343 }
9344
Sebastian Redla72462c2011-09-24 17:48:32 +00009345 // Special diagnostic for failure to convert an initializer list, since
9346 // telling the user that it has type void is not useful.
9347 if (FromExpr && isa<InitListExpr>(FromExpr)) {
9348 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
9349 << (unsigned) FnKind << FnDesc
9350 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9351 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009352 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Sebastian Redla72462c2011-09-24 17:48:32 +00009353 return;
9354 }
9355
John McCall6d174642010-01-23 08:10:49 +00009356 // Diagnose references or pointers to incomplete types differently,
9357 // since it's far from impossible that the incompleteness triggered
9358 // the failure.
9359 QualType TempFromTy = FromTy.getNonReferenceType();
9360 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
9361 TempFromTy = PTy->getPointeeType();
9362 if (TempFromTy->isIncompleteType()) {
David Blaikieac928932016-03-04 22:29:11 +00009363 // Emit the generic diagnostic and, optionally, add the hints to it.
John McCall6d174642010-01-23 08:10:49 +00009364 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
9365 << (unsigned) FnKind << FnDesc
9366 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
David Blaikieac928932016-03-04 22:29:11 +00009367 << FromTy << ToTy << (unsigned) isObjectArgument << I+1
9368 << (unsigned) (Cand->Fix.Kind);
9369
Richard Smith5179eb72016-06-28 19:03:57 +00009370 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall6d174642010-01-23 08:10:49 +00009371 return;
9372 }
9373
Douglas Gregor56f2e342010-06-30 23:01:39 +00009374 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009375 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00009376 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
9377 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
9378 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9379 FromPtrTy->getPointeeType()) &&
9380 !FromPtrTy->getPointeeType()->isIncompleteType() &&
9381 !ToPtrTy->getPointeeType()->isIncompleteType() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00009382 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00009383 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009384 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00009385 }
9386 } else if (const ObjCObjectPointerType *FromPtrTy
9387 = FromTy->getAs<ObjCObjectPointerType>()) {
9388 if (const ObjCObjectPointerType *ToPtrTy
9389 = ToTy->getAs<ObjCObjectPointerType>())
9390 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
9391 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
9392 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9393 FromPtrTy->getPointeeType()) &&
9394 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009395 BaseToDerivedConversion = 2;
9396 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009397 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
9398 !FromTy->isIncompleteType() &&
9399 !ToRefTy->getPointeeType()->isIncompleteType() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00009400 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009401 BaseToDerivedConversion = 3;
9402 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
9403 ToTy.getNonReferenceType().getCanonicalType() ==
9404 FromTy.getNonReferenceType().getCanonicalType()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009405 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
9406 << (unsigned) FnKind << FnDesc
9407 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9408 << (unsigned) isObjectArgument << I + 1;
Richard Smith5179eb72016-06-28 19:03:57 +00009409 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009410 return;
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009411 }
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009412 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009413
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009414 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009415 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009416 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00009417 << (unsigned) FnKind << FnDesc
9418 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009419 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009420 << FromTy << ToTy << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009421 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Douglas Gregor56f2e342010-06-30 23:01:39 +00009422 return;
9423 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009424
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00009425 if (isa<ObjCObjectPointerType>(CFromTy) &&
9426 isa<PointerType>(CToTy)) {
9427 Qualifiers FromQs = CFromTy.getQualifiers();
9428 Qualifiers ToQs = CToTy.getQualifiers();
9429 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9430 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
9431 << (unsigned) FnKind << FnDesc
9432 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9433 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009434 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00009435 return;
9436 }
9437 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009438
9439 if (TakingCandidateAddress &&
9440 !checkAddressOfCandidateIsAvailable(S, Cand->Function))
9441 return;
9442
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009443 // Emit the generic diagnostic and, optionally, add the hints to it.
9444 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
9445 FDiag << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00009446 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009447 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
9448 << (unsigned) (Cand->Fix.Kind);
9449
9450 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer490afa62012-01-14 21:05:10 +00009451 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
9452 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009453 FDiag << *HI;
9454 S.Diag(Fn->getLocation(), FDiag);
9455
Richard Smith5179eb72016-06-28 19:03:57 +00009456 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall6a61b522010-01-13 09:16:55 +00009457}
9458
Larisse Voufo98b20f12013-07-19 23:00:19 +00009459/// Additional arity mismatch diagnosis specific to a function overload
9460/// candidates. This is not covered by the more general DiagnoseArityMismatch()
9461/// over a candidate in any candidate set.
Richard Smith17c00b42014-11-12 01:24:00 +00009462static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
9463 unsigned NumArgs) {
John McCall6a61b522010-01-13 09:16:55 +00009464 FunctionDecl *Fn = Cand->Function;
John McCall6a61b522010-01-13 09:16:55 +00009465 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009466
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009467 // With invalid overloaded operators, it's possible that we think we
Larisse Voufo98b20f12013-07-19 23:00:19 +00009468 // have an arity mismatch when in fact it looks like we have the
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009469 // right number of arguments, because only overloaded operators have
9470 // the weird behavior of overloading member and non-member functions.
9471 // Just don't report anything.
9472 if (Fn->isInvalidDecl() &&
9473 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009474 return true;
9475
9476 if (NumArgs < MinParams) {
9477 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
9478 (Cand->FailureKind == ovl_fail_bad_deduction &&
9479 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
9480 } else {
9481 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
9482 (Cand->FailureKind == ovl_fail_bad_deduction &&
9483 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
9484 }
9485
9486 return false;
9487}
9488
9489/// General arity mismatch diagnosis over a candidate in a candidate set.
Richard Smithc2bebe92016-05-11 20:37:46 +00009490static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
9491 unsigned NumFormalArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009492 assert(isa<FunctionDecl>(D) &&
9493 "The templated declaration should at least be a function"
9494 " when diagnosing bad template argument deduction due to too many"
9495 " or too few arguments");
9496
9497 FunctionDecl *Fn = cast<FunctionDecl>(D);
9498
9499 // TODO: treat calls to a missing default constructor as a special case
9500 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
9501 unsigned MinParams = Fn->getMinRequiredArguments();
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009502
John McCall6a61b522010-01-13 09:16:55 +00009503 // at least / at most / exactly
9504 unsigned mode, modeCount;
9505 if (NumFormalArgs < MinParams) {
Alp Toker9cacbab2014-01-20 20:26:09 +00009506 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
9507 FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00009508 mode = 0; // "at least"
9509 else
9510 mode = 2; // "exactly"
9511 modeCount = MinParams;
9512 } else {
Alp Toker9cacbab2014-01-20 20:26:09 +00009513 if (MinParams != FnTy->getNumParams())
John McCall6a61b522010-01-13 09:16:55 +00009514 mode = 1; // "at most"
9515 else
9516 mode = 2; // "exactly"
Alp Toker9cacbab2014-01-20 20:26:09 +00009517 modeCount = FnTy->getNumParams();
John McCall6a61b522010-01-13 09:16:55 +00009518 }
9519
9520 std::string Description;
Richard Smithc2bebe92016-05-11 20:37:46 +00009521 OverloadCandidateKind FnKind =
9522 ClassifyOverloadCandidate(S, Found, Fn, Description);
John McCall6a61b522010-01-13 09:16:55 +00009523
Richard Smith10ff50d2012-05-11 05:16:41 +00009524 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
9525 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
Craig Topperc3ec1492014-05-26 06:22:03 +00009526 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9527 << mode << Fn->getParamDecl(0) << NumFormalArgs;
Richard Smith10ff50d2012-05-11 05:16:41 +00009528 else
9529 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Craig Topperc3ec1492014-05-26 06:22:03 +00009530 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9531 << mode << modeCount << NumFormalArgs;
Richard Smith5179eb72016-06-28 19:03:57 +00009532 MaybeEmitInheritedConstructorNote(S, Found);
John McCalle1ac8d12010-01-13 00:25:19 +00009533}
9534
Larisse Voufo98b20f12013-07-19 23:00:19 +00009535/// Arity mismatch diagnosis specific to a function overload candidate.
Richard Smith17c00b42014-11-12 01:24:00 +00009536static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
9537 unsigned NumFormalArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009538 if (!CheckArityMismatch(S, Cand, NumFormalArgs))
Richard Smithc2bebe92016-05-11 20:37:46 +00009539 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
Larisse Voufo98b20f12013-07-19 23:00:19 +00009540}
Larisse Voufo47c08452013-07-19 22:53:23 +00009541
Richard Smith17c00b42014-11-12 01:24:00 +00009542static TemplateDecl *getDescribedTemplate(Decl *Templated) {
Serge Pavlov7dcc97e2016-04-19 06:19:52 +00009543 if (TemplateDecl *TD = Templated->getDescribedTemplate())
9544 return TD;
Larisse Voufo98b20f12013-07-19 23:00:19 +00009545 llvm_unreachable("Unsupported: Getting the described template declaration"
9546 " for bad deduction diagnosis");
9547}
9548
9549/// Diagnose a failed template-argument deduction.
Richard Smithc2bebe92016-05-11 20:37:46 +00009550static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
Richard Smith17c00b42014-11-12 01:24:00 +00009551 DeductionFailureInfo &DeductionFailure,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009552 unsigned NumArgs,
9553 bool TakingCandidateAddress) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009554 TemplateParameter Param = DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009555 NamedDecl *ParamD;
9556 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
9557 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
9558 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
Larisse Voufo98b20f12013-07-19 23:00:19 +00009559 switch (DeductionFailure.Result) {
John McCall8b9ed552010-02-01 18:53:26 +00009560 case Sema::TDK_Success:
9561 llvm_unreachable("TDK_success while diagnosing bad deduction");
9562
9563 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00009564 assert(ParamD && "no parameter found for incomplete deduction result");
Larisse Voufo98b20f12013-07-19 23:00:19 +00009565 S.Diag(Templated->getLocation(),
9566 diag::note_ovl_candidate_incomplete_deduction)
9567 << ParamD->getDeclName();
Richard Smith5179eb72016-06-28 19:03:57 +00009568 MaybeEmitInheritedConstructorNote(S, Found);
John McCall8b9ed552010-02-01 18:53:26 +00009569 return;
9570 }
9571
John McCall42d7d192010-08-05 09:05:08 +00009572 case Sema::TDK_Underqualified: {
9573 assert(ParamD && "no parameter found for bad qualifiers deduction result");
9574 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
9575
Larisse Voufo98b20f12013-07-19 23:00:19 +00009576 QualType Param = DeductionFailure.getFirstArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00009577
9578 // Param will have been canonicalized, but it should just be a
9579 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00009580 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00009581 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00009582 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00009583 assert(S.Context.hasSameType(Param, NonCanonParam));
9584
9585 // Arg has also been canonicalized, but there's nothing we can do
9586 // about that. It also doesn't matter as much, because it won't
9587 // have any template parameters in it (because deduction isn't
9588 // done on dependent types).
Larisse Voufo98b20f12013-07-19 23:00:19 +00009589 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00009590
Larisse Voufo98b20f12013-07-19 23:00:19 +00009591 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
9592 << ParamD->getDeclName() << Arg << NonCanonParam;
Richard Smith5179eb72016-06-28 19:03:57 +00009593 MaybeEmitInheritedConstructorNote(S, Found);
John McCall42d7d192010-08-05 09:05:08 +00009594 return;
9595 }
9596
9597 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00009598 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009599 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009600 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009601 which = 0;
Richard Smith593d6a12016-12-23 01:30:39 +00009602 else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
9603 // Deduction might have failed because we deduced arguments of two
9604 // different types for a non-type template parameter.
9605 // FIXME: Use a different TDK value for this.
9606 QualType T1 =
9607 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
9608 QualType T2 =
9609 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
9610 if (!S.Context.hasSameType(T1, T2)) {
9611 S.Diag(Templated->getLocation(),
9612 diag::note_ovl_candidate_inconsistent_deduction_types)
9613 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
9614 << *DeductionFailure.getSecondArg() << T2;
9615 MaybeEmitInheritedConstructorNote(S, Found);
9616 return;
9617 }
9618
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009619 which = 1;
Richard Smith593d6a12016-12-23 01:30:39 +00009620 } else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009621 which = 2;
9622 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009623
Larisse Voufo98b20f12013-07-19 23:00:19 +00009624 S.Diag(Templated->getLocation(),
9625 diag::note_ovl_candidate_inconsistent_deduction)
9626 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
9627 << *DeductionFailure.getSecondArg();
Richard Smith5179eb72016-06-28 19:03:57 +00009628 MaybeEmitInheritedConstructorNote(S, Found);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009629 return;
9630 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00009631
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009632 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009633 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009634 if (ParamD->getDeclName())
Larisse Voufo98b20f12013-07-19 23:00:19 +00009635 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009636 diag::note_ovl_candidate_explicit_arg_mismatch_named)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009637 << ParamD->getDeclName();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009638 else {
9639 int index = 0;
9640 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
9641 index = TTP->getIndex();
9642 else if (NonTypeTemplateParmDecl *NTTP
9643 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
9644 index = NTTP->getIndex();
9645 else
9646 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
Larisse Voufo98b20f12013-07-19 23:00:19 +00009647 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009648 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009649 << (index + 1);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009650 }
Richard Smith5179eb72016-06-28 19:03:57 +00009651 MaybeEmitInheritedConstructorNote(S, Found);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009652 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009653
Douglas Gregor02eb4832010-05-08 18:13:28 +00009654 case Sema::TDK_TooManyArguments:
9655 case Sema::TDK_TooFewArguments:
Richard Smithc2bebe92016-05-11 20:37:46 +00009656 DiagnoseArityMismatch(S, Found, Templated, NumArgs);
Douglas Gregor02eb4832010-05-08 18:13:28 +00009657 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00009658
9659 case Sema::TDK_InstantiationDepth:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009660 S.Diag(Templated->getLocation(),
9661 diag::note_ovl_candidate_instantiation_depth);
Richard Smith5179eb72016-06-28 19:03:57 +00009662 MaybeEmitInheritedConstructorNote(S, Found);
Douglas Gregord09efd42010-05-08 20:07:26 +00009663 return;
9664
9665 case Sema::TDK_SubstitutionFailure: {
Richard Smith9ca64612012-05-07 09:03:25 +00009666 // Format the template argument list into the argument string.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009667 SmallString<128> TemplateArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00009668 if (TemplateArgumentList *Args =
Larisse Voufo98b20f12013-07-19 23:00:19 +00009669 DeductionFailure.getTemplateArgumentList()) {
Richard Smith9ca64612012-05-07 09:03:25 +00009670 TemplateArgString = " ";
9671 TemplateArgString += S.getTemplateArgumentBindingsText(
Larisse Voufo98b20f12013-07-19 23:00:19 +00009672 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
Richard Smith9ca64612012-05-07 09:03:25 +00009673 }
9674
Richard Smith6f8d2c62012-05-09 05:17:00 +00009675 // If this candidate was disabled by enable_if, say so.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009676 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
Richard Smith6f8d2c62012-05-09 05:17:00 +00009677 if (PDiag && PDiag->second.getDiagID() ==
9678 diag::err_typename_nested_not_found_enable_if) {
9679 // FIXME: Use the source range of the condition, and the fully-qualified
9680 // name of the enable_if template. These are both present in PDiag.
9681 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
9682 << "'enable_if'" << TemplateArgString;
9683 return;
9684 }
9685
Richard Smith9ca64612012-05-07 09:03:25 +00009686 // Format the SFINAE diagnostic into the argument string.
9687 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
9688 // formatted message in another diagnostic.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009689 SmallString<128> SFINAEArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00009690 SourceRange R;
Richard Smith6f8d2c62012-05-09 05:17:00 +00009691 if (PDiag) {
Richard Smith9ca64612012-05-07 09:03:25 +00009692 SFINAEArgString = ": ";
9693 R = SourceRange(PDiag->first, PDiag->first);
9694 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
9695 }
9696
Larisse Voufo98b20f12013-07-19 23:00:19 +00009697 S.Diag(Templated->getLocation(),
9698 diag::note_ovl_candidate_substitution_failure)
9699 << TemplateArgString << SFINAEArgString << R;
Richard Smith5179eb72016-06-28 19:03:57 +00009700 MaybeEmitInheritedConstructorNote(S, Found);
Douglas Gregord09efd42010-05-08 20:07:26 +00009701 return;
9702 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009703
Richard Smith8c6eeb92013-01-31 04:03:12 +00009704 case Sema::TDK_FailedOverloadResolution: {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009705 OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr());
9706 S.Diag(Templated->getLocation(),
Richard Smith8c6eeb92013-01-31 04:03:12 +00009707 diag::note_ovl_candidate_failed_overload_resolution)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009708 << R.Expression->getName();
Richard Smith8c6eeb92013-01-31 04:03:12 +00009709 return;
9710 }
9711
Richard Smith9b534542015-12-31 02:02:54 +00009712 case Sema::TDK_DeducedMismatch: {
9713 // Format the template argument list into the argument string.
9714 SmallString<128> TemplateArgString;
9715 if (TemplateArgumentList *Args =
9716 DeductionFailure.getTemplateArgumentList()) {
9717 TemplateArgString = " ";
9718 TemplateArgString += S.getTemplateArgumentBindingsText(
9719 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9720 }
9721
9722 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
9723 << (*DeductionFailure.getCallArgIndex() + 1)
9724 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
9725 << TemplateArgString;
9726 break;
9727 }
9728
Richard Trieue3732352013-04-08 21:11:40 +00009729 case Sema::TDK_NonDeducedMismatch: {
Richard Smith44ecdbd2013-01-31 05:19:49 +00009730 // FIXME: Provide a source location to indicate what we couldn't match.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009731 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
9732 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
Richard Trieue3732352013-04-08 21:11:40 +00009733 if (FirstTA.getKind() == TemplateArgument::Template &&
9734 SecondTA.getKind() == TemplateArgument::Template) {
9735 TemplateName FirstTN = FirstTA.getAsTemplate();
9736 TemplateName SecondTN = SecondTA.getAsTemplate();
9737 if (FirstTN.getKind() == TemplateName::Template &&
9738 SecondTN.getKind() == TemplateName::Template) {
9739 if (FirstTN.getAsTemplateDecl()->getName() ==
9740 SecondTN.getAsTemplateDecl()->getName()) {
9741 // FIXME: This fixes a bad diagnostic where both templates are named
9742 // the same. This particular case is a bit difficult since:
9743 // 1) It is passed as a string to the diagnostic printer.
9744 // 2) The diagnostic printer only attempts to find a better
9745 // name for types, not decls.
9746 // Ideally, this should folded into the diagnostic printer.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009747 S.Diag(Templated->getLocation(),
Richard Trieue3732352013-04-08 21:11:40 +00009748 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
9749 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
9750 return;
9751 }
9752 }
9753 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009754
9755 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
9756 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
9757 return;
9758
Faisal Vali2b391ab2013-09-26 19:54:12 +00009759 // FIXME: For generic lambda parameters, check if the function is a lambda
9760 // call operator, and if so, emit a prettier and more informative
9761 // diagnostic that mentions 'auto' and lambda in addition to
9762 // (or instead of?) the canonical template type parameters.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009763 S.Diag(Templated->getLocation(),
9764 diag::note_ovl_candidate_non_deduced_mismatch)
9765 << FirstTA << SecondTA;
Richard Smith44ecdbd2013-01-31 05:19:49 +00009766 return;
Richard Trieue3732352013-04-08 21:11:40 +00009767 }
John McCall8b9ed552010-02-01 18:53:26 +00009768 // TODO: diagnose these individually, then kill off
9769 // note_ovl_candidate_bad_deduction, which is uselessly vague.
Richard Smith44ecdbd2013-01-31 05:19:49 +00009770 case Sema::TDK_MiscellaneousDeductionFailure:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009771 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
Richard Smith5179eb72016-06-28 19:03:57 +00009772 MaybeEmitInheritedConstructorNote(S, Found);
John McCall8b9ed552010-02-01 18:53:26 +00009773 return;
Artem Belevich13e9b4d2016-12-07 19:27:16 +00009774 case Sema::TDK_CUDATargetMismatch:
9775 S.Diag(Templated->getLocation(),
9776 diag::note_cuda_ovl_candidate_target_mismatch);
9777 return;
John McCall8b9ed552010-02-01 18:53:26 +00009778 }
9779}
9780
Larisse Voufo98b20f12013-07-19 23:00:19 +00009781/// Diagnose a failed template-argument deduction, for function calls.
Richard Smith17c00b42014-11-12 01:24:00 +00009782static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009783 unsigned NumArgs,
9784 bool TakingCandidateAddress) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009785 unsigned TDK = Cand->DeductionFailure.Result;
9786 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
9787 if (CheckArityMismatch(S, Cand, NumArgs))
9788 return;
9789 }
Richard Smithc2bebe92016-05-11 20:37:46 +00009790 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009791 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
Larisse Voufo98b20f12013-07-19 23:00:19 +00009792}
9793
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009794/// CUDA: diagnose an invalid call across targets.
Richard Smith17c00b42014-11-12 01:24:00 +00009795static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009796 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
9797 FunctionDecl *Callee = Cand->Function;
9798
9799 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
9800 CalleeTarget = S.IdentifyCUDATarget(Callee);
9801
9802 std::string FnDesc;
Richard Smithc2bebe92016-05-11 20:37:46 +00009803 OverloadCandidateKind FnKind =
9804 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc);
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009805
9806 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
Eli Bendersky9a220fc2014-09-29 20:38:29 +00009807 << (unsigned)FnKind << CalleeTarget << CallerTarget;
9808
9809 // This could be an implicit constructor for which we could not infer the
9810 // target due to a collsion. Diagnose that case.
9811 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
9812 if (Meth != nullptr && Meth->isImplicit()) {
9813 CXXRecordDecl *ParentClass = Meth->getParent();
9814 Sema::CXXSpecialMember CSM;
9815
9816 switch (FnKind) {
9817 default:
9818 return;
9819 case oc_implicit_default_constructor:
9820 CSM = Sema::CXXDefaultConstructor;
9821 break;
9822 case oc_implicit_copy_constructor:
9823 CSM = Sema::CXXCopyConstructor;
9824 break;
9825 case oc_implicit_move_constructor:
9826 CSM = Sema::CXXMoveConstructor;
9827 break;
9828 case oc_implicit_copy_assignment:
9829 CSM = Sema::CXXCopyAssignment;
9830 break;
9831 case oc_implicit_move_assignment:
9832 CSM = Sema::CXXMoveAssignment;
9833 break;
9834 };
9835
9836 bool ConstRHS = false;
9837 if (Meth->getNumParams()) {
9838 if (const ReferenceType *RT =
9839 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
9840 ConstRHS = RT->getPointeeType().isConstQualified();
9841 }
9842 }
9843
9844 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
9845 /* ConstRHS */ ConstRHS,
9846 /* Diagnose */ true);
9847 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009848}
9849
Richard Smith17c00b42014-11-12 01:24:00 +00009850static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009851 FunctionDecl *Callee = Cand->Function;
9852 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
9853
9854 S.Diag(Callee->getLocation(),
9855 diag::note_ovl_candidate_disabled_by_enable_if_attr)
9856 << Attr->getCond()->getSourceRange() << Attr->getMessage();
9857}
9858
Yaxun Liu5b746652016-12-18 05:18:55 +00009859static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) {
9860 FunctionDecl *Callee = Cand->Function;
9861
9862 S.Diag(Callee->getLocation(),
9863 diag::note_ovl_candidate_disabled_by_extension);
9864}
9865
John McCall8b9ed552010-02-01 18:53:26 +00009866/// Generates a 'note' diagnostic for an overload candidate. We've
9867/// already generated a primary error at the call site.
9868///
9869/// It really does need to be a single diagnostic with its caret
9870/// pointed at the candidate declaration. Yes, this creates some
9871/// major challenges of technical writing. Yes, this makes pointing
9872/// out problems with specific arguments quite awkward. It's still
9873/// better than generating twenty screens of text for every failed
9874/// overload.
9875///
9876/// It would be great to be able to express per-candidate problems
9877/// more richly for those diagnostic clients that cared, but we'd
9878/// still have to be just as careful with the default diagnostics.
Richard Smith17c00b42014-11-12 01:24:00 +00009879static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009880 unsigned NumArgs,
9881 bool TakingCandidateAddress) {
John McCall53262c92010-01-12 02:15:36 +00009882 FunctionDecl *Fn = Cand->Function;
9883
John McCall12f97bc2010-01-08 04:41:39 +00009884 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00009885 if (Cand->Viable && (Fn->isDeleted() ||
9886 S.isFunctionConsideredUnavailable(Fn))) {
John McCalle1ac8d12010-01-13 00:25:19 +00009887 std::string FnDesc;
Richard Smithc2bebe92016-05-11 20:37:46 +00009888 OverloadCandidateKind FnKind =
9889 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00009890
9891 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
Richard Smith6f1e2c62012-04-02 20:59:25 +00009892 << FnKind << FnDesc
9893 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
Richard Smith5179eb72016-06-28 19:03:57 +00009894 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCalld3224162010-01-08 00:58:21 +00009895 return;
John McCall12f97bc2010-01-08 04:41:39 +00009896 }
9897
John McCalle1ac8d12010-01-13 00:25:19 +00009898 // We don't really have anything else to say about viable candidates.
9899 if (Cand->Viable) {
Richard Smithc2bebe92016-05-11 20:37:46 +00009900 S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009901 return;
9902 }
John McCall0d1da222010-01-12 00:44:57 +00009903
John McCall6a61b522010-01-13 09:16:55 +00009904 switch (Cand->FailureKind) {
9905 case ovl_fail_too_many_arguments:
9906 case ovl_fail_too_few_arguments:
9907 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00009908
John McCall6a61b522010-01-13 09:16:55 +00009909 case ovl_fail_bad_deduction:
Richard Smithc2bebe92016-05-11 20:37:46 +00009910 return DiagnoseBadDeduction(S, Cand, NumArgs,
9911 TakingCandidateAddress);
John McCall8b9ed552010-02-01 18:53:26 +00009912
John McCall578a1f82014-12-14 01:46:53 +00009913 case ovl_fail_illegal_constructor: {
9914 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
9915 << (Fn->getPrimaryTemplate() ? 1 : 0);
Richard Smith5179eb72016-06-28 19:03:57 +00009916 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall578a1f82014-12-14 01:46:53 +00009917 return;
9918 }
9919
John McCallfe796dd2010-01-23 05:17:32 +00009920 case ovl_fail_trivial_conversion:
9921 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00009922 case ovl_fail_final_conversion_not_exact:
Richard Smithc2bebe92016-05-11 20:37:46 +00009923 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009924
John McCall65eb8792010-02-25 01:37:24 +00009925 case ovl_fail_bad_conversion: {
9926 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009927 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00009928 if (Cand->Conversions[I].isBad())
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009929 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009930
John McCall6a61b522010-01-13 09:16:55 +00009931 // FIXME: this currently happens when we're called from SemaInit
9932 // when user-conversion overload fails. Figure out how to handle
9933 // those conditions and diagnose them well.
Richard Smithc2bebe92016-05-11 20:37:46 +00009934 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009935 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009936
9937 case ovl_fail_bad_target:
9938 return DiagnoseBadTarget(S, Cand);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009939
9940 case ovl_fail_enable_if:
9941 return DiagnoseFailedEnableIfAttr(S, Cand);
George Burgess IV7204ed92016-01-07 02:26:57 +00009942
Yaxun Liu5b746652016-12-18 05:18:55 +00009943 case ovl_fail_ext_disabled:
9944 return DiagnoseOpenCLExtensionDisabled(S, Cand);
9945
George Burgess IV7204ed92016-01-07 02:26:57 +00009946 case ovl_fail_addr_not_available: {
9947 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
9948 (void)Available;
9949 assert(!Available);
9950 break;
9951 }
John McCall65eb8792010-02-25 01:37:24 +00009952 }
John McCalld3224162010-01-08 00:58:21 +00009953}
9954
Richard Smith17c00b42014-11-12 01:24:00 +00009955static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
John McCalld3224162010-01-08 00:58:21 +00009956 // Desugar the type of the surrogate down to a function type,
9957 // retaining as many typedefs as possible while still showing
9958 // the function type (and, therefore, its parameter types).
9959 QualType FnType = Cand->Surrogate->getConversionType();
9960 bool isLValueReference = false;
9961 bool isRValueReference = false;
9962 bool isPointer = false;
9963 if (const LValueReferenceType *FnTypeRef =
9964 FnType->getAs<LValueReferenceType>()) {
9965 FnType = FnTypeRef->getPointeeType();
9966 isLValueReference = true;
9967 } else if (const RValueReferenceType *FnTypeRef =
9968 FnType->getAs<RValueReferenceType>()) {
9969 FnType = FnTypeRef->getPointeeType();
9970 isRValueReference = true;
9971 }
9972 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
9973 FnType = FnTypePtr->getPointeeType();
9974 isPointer = true;
9975 }
9976 // Desugar down to a function type.
9977 FnType = QualType(FnType->getAs<FunctionType>(), 0);
9978 // Reconstruct the pointer/reference as appropriate.
9979 if (isPointer) FnType = S.Context.getPointerType(FnType);
9980 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
9981 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
9982
9983 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
9984 << FnType;
9985}
9986
Richard Smith17c00b42014-11-12 01:24:00 +00009987static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
9988 SourceLocation OpLoc,
9989 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00009990 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalld3224162010-01-08 00:58:21 +00009991 std::string TypeStr("operator");
9992 TypeStr += Opc;
9993 TypeStr += "(";
9994 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramerb0095172012-01-14 16:32:05 +00009995 if (Cand->NumConversions == 1) {
John McCalld3224162010-01-08 00:58:21 +00009996 TypeStr += ")";
9997 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
9998 } else {
9999 TypeStr += ", ";
10000 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
10001 TypeStr += ")";
10002 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
10003 }
10004}
10005
Richard Smith17c00b42014-11-12 01:24:00 +000010006static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
10007 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +000010008 unsigned NoOperands = Cand->NumConversions;
John McCalld3224162010-01-08 00:58:21 +000010009 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
10010 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +000010011 if (ICS.isBad()) break; // all meaningless after first invalid
10012 if (!ICS.isAmbiguous()) continue;
10013
Richard Smithc2bebe92016-05-11 20:37:46 +000010014 ICS.DiagnoseAmbiguousConversion(
10015 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +000010016 }
10017}
10018
Larisse Voufo98b20f12013-07-19 23:00:19 +000010019static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
John McCall3712d9e2010-01-15 23:32:50 +000010020 if (Cand->Function)
10021 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +000010022 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +000010023 return Cand->Surrogate->getLocation();
10024 return SourceLocation();
10025}
10026
Larisse Voufo98b20f12013-07-19 23:00:19 +000010027static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
Chandler Carruth73fddfe2011-09-10 00:51:24 +000010028 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010029 case Sema::TDK_Success:
David Blaikie83d382b2011-09-23 05:06:16 +000010030 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramer8a8051f2011-09-10 21:52:04 +000010031
Douglas Gregorc5c01a62012-09-13 21:01:57 +000010032 case Sema::TDK_Invalid:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010033 case Sema::TDK_Incomplete:
10034 return 1;
10035
10036 case Sema::TDK_Underqualified:
10037 case Sema::TDK_Inconsistent:
10038 return 2;
10039
10040 case Sema::TDK_SubstitutionFailure:
Richard Smith9b534542015-12-31 02:02:54 +000010041 case Sema::TDK_DeducedMismatch:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010042 case Sema::TDK_NonDeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +000010043 case Sema::TDK_MiscellaneousDeductionFailure:
Artem Belevich13e9b4d2016-12-07 19:27:16 +000010044 case Sema::TDK_CUDATargetMismatch:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010045 return 3;
10046
10047 case Sema::TDK_InstantiationDepth:
10048 case Sema::TDK_FailedOverloadResolution:
10049 return 4;
10050
10051 case Sema::TDK_InvalidExplicitArguments:
10052 return 5;
10053
10054 case Sema::TDK_TooManyArguments:
10055 case Sema::TDK_TooFewArguments:
10056 return 6;
10057 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +000010058 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010059}
10060
Richard Smith17c00b42014-11-12 01:24:00 +000010061namespace {
John McCallad2587a2010-01-12 00:48:53 +000010062struct CompareOverloadCandidatesForDisplay {
10063 Sema &S;
Richard Smith0f59cb32015-12-18 21:45:41 +000010064 SourceLocation Loc;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +000010065 size_t NumArgs;
10066
Richard Smith0f59cb32015-12-18 21:45:41 +000010067 CompareOverloadCandidatesForDisplay(Sema &S, SourceLocation Loc, size_t nArgs)
Kaelyn Takatab96b3be2014-05-01 21:15:24 +000010068 : S(S), NumArgs(nArgs) {}
John McCall12f97bc2010-01-08 04:41:39 +000010069
10070 bool operator()(const OverloadCandidate *L,
10071 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +000010072 // Fast-path this check.
10073 if (L == R) return false;
10074
John McCall12f97bc2010-01-08 04:41:39 +000010075 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +000010076 if (L->Viable) {
10077 if (!R->Viable) return true;
10078
10079 // TODO: introduce a tri-valued comparison for overload
10080 // candidates. Would be more worthwhile if we had a sort
10081 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +000010082 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
10083 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +000010084 } else if (R->Viable)
10085 return false;
John McCall12f97bc2010-01-08 04:41:39 +000010086
John McCall3712d9e2010-01-15 23:32:50 +000010087 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +000010088
John McCall3712d9e2010-01-15 23:32:50 +000010089 // Criteria by which we can sort non-viable candidates:
10090 if (!L->Viable) {
10091 // 1. Arity mismatches come after other candidates.
10092 if (L->FailureKind == ovl_fail_too_many_arguments ||
Kaelyn Takatab96b3be2014-05-01 21:15:24 +000010093 L->FailureKind == ovl_fail_too_few_arguments) {
10094 if (R->FailureKind == ovl_fail_too_many_arguments ||
10095 R->FailureKind == ovl_fail_too_few_arguments) {
Kaelyn Takata50c4ffc2014-05-07 00:43:38 +000010096 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
10097 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
10098 if (LDist == RDist) {
10099 if (L->FailureKind == R->FailureKind)
10100 // Sort non-surrogates before surrogates.
10101 return !L->IsSurrogate && R->IsSurrogate;
10102 // Sort candidates requiring fewer parameters than there were
10103 // arguments given after candidates requiring more parameters
10104 // than there were arguments given.
10105 return L->FailureKind == ovl_fail_too_many_arguments;
10106 }
Kaelyn Takatab96b3be2014-05-01 21:15:24 +000010107 return LDist < RDist;
10108 }
John McCall3712d9e2010-01-15 23:32:50 +000010109 return false;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +000010110 }
John McCall3712d9e2010-01-15 23:32:50 +000010111 if (R->FailureKind == ovl_fail_too_many_arguments ||
10112 R->FailureKind == ovl_fail_too_few_arguments)
10113 return true;
John McCall12f97bc2010-01-08 04:41:39 +000010114
John McCallfe796dd2010-01-23 05:17:32 +000010115 // 2. Bad conversions come first and are ordered by the number
10116 // of bad conversions and quality of good conversions.
10117 if (L->FailureKind == ovl_fail_bad_conversion) {
10118 if (R->FailureKind != ovl_fail_bad_conversion)
10119 return true;
10120
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010121 // The conversion that can be fixed with a smaller number of changes,
10122 // comes first.
10123 unsigned numLFixes = L->Fix.NumConversionsFixed;
10124 unsigned numRFixes = R->Fix.NumConversionsFixed;
10125 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
10126 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +000010127 if (numLFixes != numRFixes) {
David Blaikie7a3cbb22015-03-09 02:02:07 +000010128 return numLFixes < numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +000010129 }
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010130
John McCallfe796dd2010-01-23 05:17:32 +000010131 // If there's any ordering between the defined conversions...
10132 // FIXME: this might not be transitive.
Benjamin Kramerb0095172012-01-14 16:32:05 +000010133 assert(L->NumConversions == R->NumConversions);
John McCallfe796dd2010-01-23 05:17:32 +000010134
10135 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +000010136 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramerb0095172012-01-14 16:32:05 +000010137 for (unsigned E = L->NumConversions; I != E; ++I) {
Richard Smith0f59cb32015-12-18 21:45:41 +000010138 switch (CompareImplicitConversionSequences(S, Loc,
John McCall5c32be02010-08-24 20:38:10 +000010139 L->Conversions[I],
10140 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +000010141 case ImplicitConversionSequence::Better:
10142 leftBetter++;
10143 break;
10144
10145 case ImplicitConversionSequence::Worse:
10146 leftBetter--;
10147 break;
10148
10149 case ImplicitConversionSequence::Indistinguishable:
10150 break;
10151 }
10152 }
10153 if (leftBetter > 0) return true;
10154 if (leftBetter < 0) return false;
10155
10156 } else if (R->FailureKind == ovl_fail_bad_conversion)
10157 return false;
10158
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010159 if (L->FailureKind == ovl_fail_bad_deduction) {
10160 if (R->FailureKind != ovl_fail_bad_deduction)
10161 return true;
10162
10163 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10164 return RankDeductionFailure(L->DeductionFailure)
Eli Friedman1e7a0c62011-10-14 23:10:30 +000010165 < RankDeductionFailure(R->DeductionFailure);
Eli Friedmane2c600c2011-10-14 21:52:24 +000010166 } else if (R->FailureKind == ovl_fail_bad_deduction)
10167 return false;
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010168
John McCall3712d9e2010-01-15 23:32:50 +000010169 // TODO: others?
10170 }
10171
10172 // Sort everything else by location.
10173 SourceLocation LLoc = GetLocationForCandidate(L);
10174 SourceLocation RLoc = GetLocationForCandidate(R);
10175
10176 // Put candidates without locations (e.g. builtins) at the end.
10177 if (LLoc.isInvalid()) return false;
10178 if (RLoc.isInvalid()) return true;
10179
10180 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +000010181 }
10182};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010183}
John McCall12f97bc2010-01-08 04:41:39 +000010184
John McCallfe796dd2010-01-23 05:17:32 +000010185/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010186/// computes up to the first. Produces the FixIt set if possible.
Richard Smith17c00b42014-11-12 01:24:00 +000010187static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
10188 ArrayRef<Expr *> Args) {
John McCallfe796dd2010-01-23 05:17:32 +000010189 assert(!Cand->Viable);
10190
10191 // Don't do anything on failures other than bad conversion.
10192 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
10193
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010194 // We only want the FixIts if all the arguments can be corrected.
10195 bool Unfixable = false;
Anna Zaks1b068122011-07-28 19:46:48 +000010196 // Use a implicit copy initialization to check conversion fixes.
10197 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010198
John McCallfe796dd2010-01-23 05:17:32 +000010199 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +000010200 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +000010201 unsigned ConvCount = Cand->NumConversions;
John McCallfe796dd2010-01-23 05:17:32 +000010202 while (true) {
10203 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
10204 ConvIdx++;
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010205 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaks1b068122011-07-28 19:46:48 +000010206 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCallfe796dd2010-01-23 05:17:32 +000010207 break;
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010208 }
John McCallfe796dd2010-01-23 05:17:32 +000010209 }
10210
10211 if (ConvIdx == ConvCount)
10212 return;
10213
John McCall65eb8792010-02-25 01:37:24 +000010214 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
10215 "remaining conversion is initialized?");
10216
Douglas Gregoradc7a702010-04-16 17:45:54 +000010217 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +000010218 // operation somehow.
10219 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +000010220
10221 const FunctionProtoType* Proto;
10222 unsigned ArgIdx = ConvIdx;
10223
10224 if (Cand->IsSurrogate) {
10225 QualType ConvType
10226 = Cand->Surrogate->getConversionType().getNonReferenceType();
10227 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10228 ConvType = ConvPtrType->getPointeeType();
10229 Proto = ConvType->getAs<FunctionProtoType>();
10230 ArgIdx--;
10231 } else if (Cand->Function) {
10232 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
10233 if (isa<CXXMethodDecl>(Cand->Function) &&
10234 !isa<CXXConstructorDecl>(Cand->Function))
10235 ArgIdx--;
10236 } else {
10237 // Builtin binary operator with a bad first conversion.
10238 assert(ConvCount <= 3);
10239 for (; ConvIdx != ConvCount; ++ConvIdx)
10240 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +000010241 = TryCopyInitialization(S, Args[ConvIdx],
10242 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010243 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +000010244 /*InOverloadResolution*/ true,
10245 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +000010246 S.getLangOpts().ObjCAutoRefCount);
John McCallfe796dd2010-01-23 05:17:32 +000010247 return;
10248 }
10249
10250 // Fill in the rest of the conversions.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000010251 unsigned NumParams = Proto->getNumParams();
John McCallfe796dd2010-01-23 05:17:32 +000010252 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000010253 if (ArgIdx < NumParams) {
Alp Toker9cacbab2014-01-20 20:26:09 +000010254 Cand->Conversions[ConvIdx] = TryCopyInitialization(
10255 S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions,
10256 /*InOverloadResolution=*/true,
10257 /*AllowObjCWritebackConversion=*/
10258 S.getLangOpts().ObjCAutoRefCount);
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010259 // Store the FixIt in the candidate if it exists.
10260 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaks1b068122011-07-28 19:46:48 +000010261 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010262 }
John McCallfe796dd2010-01-23 05:17:32 +000010263 else
10264 Cand->Conversions[ConvIdx].setEllipsis();
10265 }
10266}
10267
Douglas Gregor5251f1b2008-10-21 16:13:35 +000010268/// PrintOverloadCandidates - When overload resolution fails, prints
10269/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +000010270/// set.
Richard Smithb2f0f052016-10-10 18:54:32 +000010271void OverloadCandidateSet::NoteCandidates(
10272 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
10273 StringRef Opc, SourceLocation OpLoc,
10274 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
John McCall12f97bc2010-01-08 04:41:39 +000010275 // Sort the candidates by viability and position. Sorting directly would
10276 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010277 SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +000010278 if (OCD == OCD_AllCandidates) Cands.reserve(size());
10279 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
Richard Smithb2f0f052016-10-10 18:54:32 +000010280 if (!Filter(*Cand))
10281 continue;
John McCallfe796dd2010-01-23 05:17:32 +000010282 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +000010283 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +000010284 else if (OCD == OCD_AllCandidates) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010285 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010286 if (Cand->Function || Cand->IsSurrogate)
10287 Cands.push_back(Cand);
10288 // Otherwise, this a non-viable builtin candidate. We do not, in general,
10289 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +000010290 }
10291 }
10292
John McCallad2587a2010-01-12 00:48:53 +000010293 std::sort(Cands.begin(), Cands.end(),
Richard Smith0f59cb32015-12-18 21:45:41 +000010294 CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size()));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010295
John McCall0d1da222010-01-12 00:44:57 +000010296 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +000010297
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010298 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Douglas Gregor79591782012-10-23 23:11:23 +000010299 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010300 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +000010301 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10302 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +000010303
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010304 // Set an arbitrary limit on the number of candidate functions we'll spam
10305 // the user with. FIXME: This limit should depend on details of the
10306 // candidate list.
Douglas Gregor79591782012-10-23 23:11:23 +000010307 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010308 break;
10309 }
10310 ++CandsShown;
10311
John McCalld3224162010-01-08 00:58:21 +000010312 if (Cand->Function)
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010313 NoteFunctionCandidate(S, Cand, Args.size(),
10314 /*TakingCandidateAddress=*/false);
John McCalld3224162010-01-08 00:58:21 +000010315 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +000010316 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010317 else {
10318 assert(Cand->Viable &&
10319 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +000010320 // Generally we only see ambiguities including viable builtin
10321 // operators if overload resolution got screwed up by an
10322 // ambiguous user-defined conversion.
10323 //
10324 // FIXME: It's quite possible for different conversions to see
10325 // different ambiguities, though.
10326 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +000010327 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +000010328 ReportedAmbiguousConversions = true;
10329 }
John McCalld3224162010-01-08 00:58:21 +000010330
John McCall0d1da222010-01-12 00:44:57 +000010331 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +000010332 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +000010333 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +000010334 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010335
10336 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +000010337 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +000010338}
10339
Larisse Voufo98b20f12013-07-19 23:00:19 +000010340static SourceLocation
10341GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
10342 return Cand->Specialization ? Cand->Specialization->getLocation()
10343 : SourceLocation();
10344}
10345
Richard Smith17c00b42014-11-12 01:24:00 +000010346namespace {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010347struct CompareTemplateSpecCandidatesForDisplay {
10348 Sema &S;
10349 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
10350
10351 bool operator()(const TemplateSpecCandidate *L,
10352 const TemplateSpecCandidate *R) {
10353 // Fast-path this check.
10354 if (L == R)
10355 return false;
10356
10357 // Assuming that both candidates are not matches...
10358
10359 // Sort by the ranking of deduction failures.
10360 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10361 return RankDeductionFailure(L->DeductionFailure) <
10362 RankDeductionFailure(R->DeductionFailure);
10363
10364 // Sort everything else by location.
10365 SourceLocation LLoc = GetLocationForCandidate(L);
10366 SourceLocation RLoc = GetLocationForCandidate(R);
10367
10368 // Put candidates without locations (e.g. builtins) at the end.
10369 if (LLoc.isInvalid())
10370 return false;
10371 if (RLoc.isInvalid())
10372 return true;
10373
10374 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10375 }
10376};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010377}
Larisse Voufo98b20f12013-07-19 23:00:19 +000010378
10379/// Diagnose a template argument deduction failure.
10380/// We are treating these failures as overload failures due to bad
10381/// deductions.
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010382void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
10383 bool ForTakingAddress) {
Richard Smithc2bebe92016-05-11 20:37:46 +000010384 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010385 DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010386}
10387
10388void TemplateSpecCandidateSet::destroyCandidates() {
10389 for (iterator i = begin(), e = end(); i != e; ++i) {
10390 i->DeductionFailure.Destroy();
10391 }
10392}
10393
10394void TemplateSpecCandidateSet::clear() {
10395 destroyCandidates();
10396 Candidates.clear();
10397}
10398
10399/// NoteCandidates - When no template specialization match is found, prints
10400/// diagnostic messages containing the non-matching specializations that form
10401/// the candidate set.
10402/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
10403/// OCD == OCD_AllCandidates and Cand->Viable == false.
10404void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
10405 // Sort the candidates by position (assuming no candidate is a match).
10406 // Sorting directly would be prohibitive, so we make a set of pointers
10407 // and sort those.
10408 SmallVector<TemplateSpecCandidate *, 32> Cands;
10409 Cands.reserve(size());
10410 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10411 if (Cand->Specialization)
10412 Cands.push_back(Cand);
Alp Tokerd4733632013-12-05 04:47:09 +000010413 // Otherwise, this is a non-matching builtin candidate. We do not,
Larisse Voufo98b20f12013-07-19 23:00:19 +000010414 // in general, want to list every possible builtin candidate.
10415 }
10416
10417 std::sort(Cands.begin(), Cands.end(),
10418 CompareTemplateSpecCandidatesForDisplay(S));
10419
10420 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
10421 // for generalization purposes (?).
10422 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10423
10424 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
10425 unsigned CandsShown = 0;
10426 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10427 TemplateSpecCandidate *Cand = *I;
10428
10429 // Set an arbitrary limit on the number of candidates we'll spam
10430 // the user with. FIXME: This limit should depend on details of the
10431 // candidate list.
10432 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10433 break;
10434 ++CandsShown;
10435
10436 assert(Cand->Specialization &&
10437 "Non-matching built-in candidates are not added to Cands.");
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010438 Cand->NoteDeductionFailure(S, ForTakingAddress);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010439 }
10440
10441 if (I != E)
10442 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
10443}
10444
Douglas Gregorb491ed32011-02-19 21:32:49 +000010445// [PossiblyAFunctionType] --> [Return]
10446// NonFunctionType --> NonFunctionType
10447// R (A) --> R(A)
10448// R (*)(A) --> R (A)
10449// R (&)(A) --> R (A)
10450// R (S::*)(A) --> R (A)
10451QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
10452 QualType Ret = PossiblyAFunctionType;
10453 if (const PointerType *ToTypePtr =
10454 PossiblyAFunctionType->getAs<PointerType>())
10455 Ret = ToTypePtr->getPointeeType();
10456 else if (const ReferenceType *ToTypeRef =
10457 PossiblyAFunctionType->getAs<ReferenceType>())
10458 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +000010459 else if (const MemberPointerType *MemTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +000010460 PossiblyAFunctionType->getAs<MemberPointerType>())
10461 Ret = MemTypePtr->getPointeeType();
10462 Ret =
10463 Context.getCanonicalType(Ret).getUnqualifiedType();
10464 return Ret;
10465}
Douglas Gregorcd695e52008-11-10 20:40:00 +000010466
Richard Smith9095e5b2016-11-01 01:31:23 +000010467static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
10468 bool Complain = true) {
10469 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
10470 S.DeduceReturnType(FD, Loc, Complain))
10471 return true;
10472
10473 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
10474 if (S.getLangOpts().CPlusPlus1z &&
10475 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
10476 !S.ResolveExceptionSpec(Loc, FPT))
10477 return true;
10478
10479 return false;
10480}
10481
Richard Smith17c00b42014-11-12 01:24:00 +000010482namespace {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010483// A helper class to help with address of function resolution
10484// - allows us to avoid passing around all those ugly parameters
Richard Smith17c00b42014-11-12 01:24:00 +000010485class AddressOfFunctionResolver {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010486 Sema& S;
10487 Expr* SourceExpr;
10488 const QualType& TargetType;
10489 QualType TargetFunctionType; // Extracted function type from target type
10490
10491 bool Complain;
10492 //DeclAccessPair& ResultFunctionAccessPair;
10493 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010494
Douglas Gregorb491ed32011-02-19 21:32:49 +000010495 bool TargetTypeIsNonStaticMemberFunction;
10496 bool FoundNonTemplateFunction;
David Majnemera4f7c7a2013-08-01 06:13:59 +000010497 bool StaticMemberFunctionFromBoundPointer;
George Burgess IV5f2ef452015-10-12 18:40:58 +000010498 bool HasComplained;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010499
Douglas Gregorb491ed32011-02-19 21:32:49 +000010500 OverloadExpr::FindResult OvlExprInfo;
10501 OverloadExpr *OvlExpr;
10502 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010503 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Larisse Voufo98b20f12013-07-19 23:00:19 +000010504 TemplateSpecCandidateSet FailedCandidates;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010505
Douglas Gregorb491ed32011-02-19 21:32:49 +000010506public:
Larisse Voufo98b20f12013-07-19 23:00:19 +000010507 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
10508 const QualType &TargetType, bool Complain)
10509 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
10510 Complain(Complain), Context(S.getASTContext()),
10511 TargetTypeIsNonStaticMemberFunction(
10512 !!TargetType->getAs<MemberPointerType>()),
10513 FoundNonTemplateFunction(false),
David Majnemera4f7c7a2013-08-01 06:13:59 +000010514 StaticMemberFunctionFromBoundPointer(false),
George Burgess IV5f2ef452015-10-12 18:40:58 +000010515 HasComplained(false),
Larisse Voufo98b20f12013-07-19 23:00:19 +000010516 OvlExprInfo(OverloadExpr::find(SourceExpr)),
10517 OvlExpr(OvlExprInfo.Expression),
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010518 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010519 ExtractUnqualifiedFunctionTypeFromTargetType();
Chandler Carruthffce2452011-03-29 08:08:18 +000010520
David Majnemera4f7c7a2013-08-01 06:13:59 +000010521 if (TargetFunctionType->isFunctionType()) {
10522 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
10523 if (!UME->isImplicitAccess() &&
10524 !S.ResolveSingleFunctionTemplateSpecialization(UME))
10525 StaticMemberFunctionFromBoundPointer = true;
10526 } else if (OvlExpr->hasExplicitTemplateArgs()) {
10527 DeclAccessPair dap;
10528 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
10529 OvlExpr, false, &dap)) {
10530 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
10531 if (!Method->isStatic()) {
10532 // If the target type is a non-function type and the function found
10533 // is a non-static member function, pretend as if that was the
10534 // target, it's the only possible type to end up with.
10535 TargetTypeIsNonStaticMemberFunction = true;
Chandler Carruthffce2452011-03-29 08:08:18 +000010536
David Majnemera4f7c7a2013-08-01 06:13:59 +000010537 // And skip adding the function if its not in the proper form.
10538 // We'll diagnose this due to an empty set of functions.
10539 if (!OvlExprInfo.HasFormOfMemberPointer)
10540 return;
Chandler Carruthffce2452011-03-29 08:08:18 +000010541 }
10542
David Majnemera4f7c7a2013-08-01 06:13:59 +000010543 Matches.push_back(std::make_pair(dap, Fn));
Douglas Gregor9b146582009-07-08 20:55:45 +000010544 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010545 return;
Douglas Gregor9b146582009-07-08 20:55:45 +000010546 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010547
10548 if (OvlExpr->hasExplicitTemplateArgs())
James Y Knight04ec5bf2015-12-24 02:59:37 +000010549 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +000010550
Douglas Gregorb491ed32011-02-19 21:32:49 +000010551 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
10552 // C++ [over.over]p4:
10553 // If more than one function is selected, [...]
George Burgess IV2a6150d2015-10-16 01:17:38 +000010554 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010555 if (FoundNonTemplateFunction)
10556 EliminateAllTemplateMatches();
10557 else
10558 EliminateAllExceptMostSpecializedTemplate();
10559 }
10560 }
Artem Belevich94a55e82015-09-22 17:22:59 +000010561
Justin Lebar25c4a812016-03-29 16:24:16 +000010562 if (S.getLangOpts().CUDA && Matches.size() > 1)
Artem Belevich94a55e82015-09-22 17:22:59 +000010563 EliminateSuboptimalCudaMatches();
Douglas Gregorb491ed32011-02-19 21:32:49 +000010564 }
George Burgess IV5f2ef452015-10-12 18:40:58 +000010565
10566 bool hasComplained() const { return HasComplained; }
10567
Douglas Gregorb491ed32011-02-19 21:32:49 +000010568private:
George Burgess IV6da4c202016-03-23 02:33:58 +000010569 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
10570 QualType Discard;
10571 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
Richard Smith3c4f8d22016-10-16 17:54:23 +000010572 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
George Burgess IV2a6150d2015-10-16 01:17:38 +000010573 }
10574
George Burgess IV6da4c202016-03-23 02:33:58 +000010575 /// \return true if A is considered a better overload candidate for the
10576 /// desired type than B.
10577 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
10578 // If A doesn't have exactly the correct type, we don't want to classify it
10579 // as "better" than anything else. This way, the user is required to
10580 // disambiguate for us if there are multiple candidates and no exact match.
10581 return candidateHasExactlyCorrectType(A) &&
10582 (!candidateHasExactlyCorrectType(B) ||
George Burgess IV3dc166912016-05-10 01:59:34 +000010583 compareEnableIfAttrs(S, A, B) == Comparison::Better);
George Burgess IV6da4c202016-03-23 02:33:58 +000010584 }
10585
10586 /// \return true if we were able to eliminate all but one overload candidate,
10587 /// false otherwise.
George Burgess IV2a6150d2015-10-16 01:17:38 +000010588 bool eliminiateSuboptimalOverloadCandidates() {
10589 // Same algorithm as overload resolution -- one pass to pick the "best",
10590 // another pass to be sure that nothing is better than the best.
10591 auto Best = Matches.begin();
10592 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
10593 if (isBetterCandidate(I->second, Best->second))
10594 Best = I;
10595
10596 const FunctionDecl *BestFn = Best->second;
10597 auto IsBestOrInferiorToBest = [this, BestFn](
10598 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
10599 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
10600 };
10601
10602 // Note: We explicitly leave Matches unmodified if there isn't a clear best
10603 // option, so we can potentially give the user a better error
10604 if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest))
10605 return false;
10606 Matches[0] = *Best;
10607 Matches.resize(1);
10608 return true;
10609 }
10610
Douglas Gregorb491ed32011-02-19 21:32:49 +000010611 bool isTargetTypeAFunction() const {
10612 return TargetFunctionType->isFunctionType();
10613 }
10614
10615 // [ToType] [Return]
10616
10617 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
10618 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
10619 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
10620 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
10621 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
10622 }
10623
10624 // return true if any matching specializations were found
10625 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
10626 const DeclAccessPair& CurAccessFunPair) {
10627 if (CXXMethodDecl *Method
10628 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
10629 // Skip non-static function templates when converting to pointer, and
10630 // static when converting to member pointer.
10631 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10632 return false;
10633 }
10634 else if (TargetTypeIsNonStaticMemberFunction)
10635 return false;
10636
10637 // C++ [over.over]p2:
10638 // If the name is a function template, template argument deduction is
10639 // done (14.8.2.2), and if the argument deduction succeeds, the
10640 // resulting template argument list is used to generate a single
10641 // function template specialization, which is added to the set of
10642 // overloaded functions considered.
Craig Topperc3ec1492014-05-26 06:22:03 +000010643 FunctionDecl *Specialization = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +000010644 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregorb491ed32011-02-19 21:32:49 +000010645 if (Sema::TemplateDeductionResult Result
10646 = S.DeduceTemplateArguments(FunctionTemplate,
10647 &OvlExplicitTemplateArgs,
10648 TargetFunctionType, Specialization,
Richard Smithbaa47832016-12-01 02:11:49 +000010649 Info, /*IsAddressOfFunction*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010650 // Make a note of the failed deduction for diagnostics.
10651 FailedCandidates.addCandidate()
Richard Smithc2bebe92016-05-11 20:37:46 +000010652 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
Larisse Voufo98b20f12013-07-19 23:00:19 +000010653 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregorb491ed32011-02-19 21:32:49 +000010654 return false;
10655 }
10656
Douglas Gregor19a41f12013-04-17 08:45:07 +000010657 // Template argument deduction ensures that we have an exact match or
10658 // compatible pointer-to-function arguments that would be adjusted by ICS.
Douglas Gregorb491ed32011-02-19 21:32:49 +000010659 // This function template specicalization works.
Douglas Gregor19a41f12013-04-17 08:45:07 +000010660 assert(S.isSameOrCompatibleFunctionType(
10661 Context.getCanonicalType(Specialization->getType()),
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010662 Context.getCanonicalType(TargetFunctionType)));
George Burgess IV5f21c712015-10-12 19:57:04 +000010663
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010664 if (!S.checkAddressOfFunctionIsAvailable(Specialization))
George Burgess IV5f21c712015-10-12 19:57:04 +000010665 return false;
10666
Douglas Gregorb491ed32011-02-19 21:32:49 +000010667 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
10668 return true;
10669 }
10670
10671 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
10672 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +000010673 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +000010674 // Skip non-static functions when converting to pointer, and static
10675 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +000010676 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10677 return false;
10678 }
10679 else if (TargetTypeIsNonStaticMemberFunction)
10680 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010681
Chandler Carruthc25c6ee2009-12-29 06:17:27 +000010682 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000010683 if (S.getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010684 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
Justin Lebarb0080032016-08-10 01:09:11 +000010685 if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010686 return false;
10687
Richard Smith2a7d4812013-05-04 07:00:32 +000010688 // If any candidate has a placeholder return type, trigger its deduction
10689 // now.
Richard Smith9095e5b2016-11-01 01:31:23 +000010690 if (completeFunctionType(S, FunDecl, SourceExpr->getLocStart(),
10691 Complain)) {
George Burgess IV5f2ef452015-10-12 18:40:58 +000010692 HasComplained |= Complain;
Richard Smith2a7d4812013-05-04 07:00:32 +000010693 return false;
George Burgess IV5f2ef452015-10-12 18:40:58 +000010694 }
Richard Smith2a7d4812013-05-04 07:00:32 +000010695
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010696 if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
George Burgess IV5f21c712015-10-12 19:57:04 +000010697 return false;
10698
George Burgess IV6da4c202016-03-23 02:33:58 +000010699 // If we're in C, we need to support types that aren't exactly identical.
10700 if (!S.getLangOpts().CPlusPlus ||
10701 candidateHasExactlyCorrectType(FunDecl)) {
George Burgess IV5f21c712015-10-12 19:57:04 +000010702 Matches.push_back(std::make_pair(
10703 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +000010704 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010705 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +000010706 }
Mike Stump11289f42009-09-09 15:08:12 +000010707 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010708
10709 return false;
10710 }
10711
10712 bool FindAllFunctionsThatMatchTargetTypeExactly() {
10713 bool Ret = false;
10714
10715 // If the overload expression doesn't have the form of a pointer to
10716 // member, don't try to convert it to a pointer-to-member type.
10717 if (IsInvalidFormOfPointerToMemberFunction())
10718 return false;
10719
10720 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10721 E = OvlExpr->decls_end();
10722 I != E; ++I) {
10723 // Look through any using declarations to find the underlying function.
10724 NamedDecl *Fn = (*I)->getUnderlyingDecl();
10725
10726 // C++ [over.over]p3:
10727 // Non-member functions and static member functions match
10728 // targets of type "pointer-to-function" or "reference-to-function."
10729 // Nonstatic member functions match targets of
10730 // type "pointer-to-member-function."
10731 // Note that according to DR 247, the containing class does not matter.
10732 if (FunctionTemplateDecl *FunctionTemplate
10733 = dyn_cast<FunctionTemplateDecl>(Fn)) {
10734 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
10735 Ret = true;
10736 }
10737 // If we have explicit template arguments supplied, skip non-templates.
10738 else if (!OvlExpr->hasExplicitTemplateArgs() &&
10739 AddMatchingNonTemplateFunction(Fn, I.getPair()))
10740 Ret = true;
10741 }
10742 assert(Ret || Matches.empty());
10743 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010744 }
10745
Douglas Gregorb491ed32011-02-19 21:32:49 +000010746 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +000010747 // [...] and any given function template specialization F1 is
10748 // eliminated if the set contains a second function template
10749 // specialization whose function template is more specialized
10750 // than the function template of F1 according to the partial
10751 // ordering rules of 14.5.5.2.
10752
10753 // The algorithm specified above is quadratic. We instead use a
10754 // two-pass algorithm (similar to the one used to identify the
10755 // best viable function in an overload set) that identifies the
10756 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +000010757
10758 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
10759 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
10760 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010761
Larisse Voufo98b20f12013-07-19 23:00:19 +000010762 // TODO: It looks like FailedCandidates does not serve much purpose
10763 // here, since the no_viable diagnostic has index 0.
10764 UnresolvedSetIterator Result = S.getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +000010765 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +000010766 SourceExpr->getLocStart(), S.PDiag(),
Richard Smith5179eb72016-06-28 19:03:57 +000010767 S.PDiag(diag::err_addr_ovl_ambiguous)
10768 << Matches[0].second->getDeclName(),
10769 S.PDiag(diag::note_ovl_candidate)
10770 << (unsigned)oc_function_template,
Larisse Voufo98b20f12013-07-19 23:00:19 +000010771 Complain, TargetFunctionType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010772
Douglas Gregorb491ed32011-02-19 21:32:49 +000010773 if (Result != MatchesCopy.end()) {
10774 // Make it the first and only element
10775 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
10776 Matches[0].second = cast<FunctionDecl>(*Result);
10777 Matches.resize(1);
George Burgess IV5f2ef452015-10-12 18:40:58 +000010778 } else
10779 HasComplained |= Complain;
John McCall58cc69d2010-01-27 01:50:18 +000010780 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010781
Douglas Gregorb491ed32011-02-19 21:32:49 +000010782 void EliminateAllTemplateMatches() {
10783 // [...] any function template specializations in the set are
10784 // eliminated if the set also contains a non-template function, [...]
10785 for (unsigned I = 0, N = Matches.size(); I != N; ) {
Craig Topperc3ec1492014-05-26 06:22:03 +000010786 if (Matches[I].second->getPrimaryTemplate() == nullptr)
Douglas Gregorb491ed32011-02-19 21:32:49 +000010787 ++I;
10788 else {
10789 Matches[I] = Matches[--N];
Artem Belevich94a55e82015-09-22 17:22:59 +000010790 Matches.resize(N);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010791 }
10792 }
10793 }
10794
Artem Belevich94a55e82015-09-22 17:22:59 +000010795 void EliminateSuboptimalCudaMatches() {
10796 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
10797 }
10798
Douglas Gregorb491ed32011-02-19 21:32:49 +000010799public:
10800 void ComplainNoMatchesFound() const {
10801 assert(Matches.empty());
10802 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
10803 << OvlExpr->getName() << TargetFunctionType
10804 << OvlExpr->getSourceRange();
Richard Smith0d905472013-08-14 00:00:44 +000010805 if (FailedCandidates.empty())
George Burgess IV5f21c712015-10-12 19:57:04 +000010806 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
10807 /*TakingAddress=*/true);
Richard Smith0d905472013-08-14 00:00:44 +000010808 else {
10809 // We have some deduction failure messages. Use them to diagnose
10810 // the function templates, and diagnose the non-template candidates
10811 // normally.
10812 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10813 IEnd = OvlExpr->decls_end();
10814 I != IEnd; ++I)
10815 if (FunctionDecl *Fun =
10816 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010817 if (!functionHasPassObjectSizeParams(Fun))
Richard Smithc2bebe92016-05-11 20:37:46 +000010818 S.NoteOverloadCandidate(*I, Fun, TargetFunctionType,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010819 /*TakingAddress=*/true);
Richard Smith0d905472013-08-14 00:00:44 +000010820 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
10821 }
10822 }
10823
Douglas Gregorb491ed32011-02-19 21:32:49 +000010824 bool IsInvalidFormOfPointerToMemberFunction() const {
10825 return TargetTypeIsNonStaticMemberFunction &&
10826 !OvlExprInfo.HasFormOfMemberPointer;
10827 }
David Majnemera4f7c7a2013-08-01 06:13:59 +000010828
Douglas Gregorb491ed32011-02-19 21:32:49 +000010829 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
10830 // TODO: Should we condition this on whether any functions might
10831 // have matched, or is it more appropriate to do that in callers?
10832 // TODO: a fixit wouldn't hurt.
10833 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
10834 << TargetType << OvlExpr->getSourceRange();
10835 }
David Majnemera4f7c7a2013-08-01 06:13:59 +000010836
10837 bool IsStaticMemberFunctionFromBoundPointer() const {
10838 return StaticMemberFunctionFromBoundPointer;
10839 }
10840
10841 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
10842 S.Diag(OvlExpr->getLocStart(),
10843 diag::err_invalid_form_pointer_member_function)
10844 << OvlExpr->getSourceRange();
10845 }
10846
Douglas Gregorb491ed32011-02-19 21:32:49 +000010847 void ComplainOfInvalidConversion() const {
10848 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
10849 << OvlExpr->getName() << TargetType;
10850 }
10851
10852 void ComplainMultipleMatchesFound() const {
10853 assert(Matches.size() > 1);
10854 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
10855 << OvlExpr->getName()
10856 << OvlExpr->getSourceRange();
George Burgess IV5f21c712015-10-12 19:57:04 +000010857 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
10858 /*TakingAddress=*/true);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010859 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010860
10861 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
10862
Douglas Gregorb491ed32011-02-19 21:32:49 +000010863 int getNumMatches() const { return Matches.size(); }
10864
10865 FunctionDecl* getMatchingFunctionDecl() const {
Craig Topperc3ec1492014-05-26 06:22:03 +000010866 if (Matches.size() != 1) return nullptr;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010867 return Matches[0].second;
10868 }
10869
10870 const DeclAccessPair* getMatchingFunctionAccessPair() const {
Craig Topperc3ec1492014-05-26 06:22:03 +000010871 if (Matches.size() != 1) return nullptr;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010872 return &Matches[0].first;
10873 }
10874};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010875}
Richard Smith17c00b42014-11-12 01:24:00 +000010876
Douglas Gregorb491ed32011-02-19 21:32:49 +000010877/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
10878/// an overloaded function (C++ [over.over]), where @p From is an
10879/// expression with overloaded function type and @p ToType is the type
10880/// we're trying to resolve to. For example:
10881///
10882/// @code
10883/// int f(double);
10884/// int f(int);
10885///
10886/// int (*pfd)(double) = f; // selects f(double)
10887/// @endcode
10888///
10889/// This routine returns the resulting FunctionDecl if it could be
10890/// resolved, and NULL otherwise. When @p Complain is true, this
10891/// routine will emit diagnostics if there is an error.
10892FunctionDecl *
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010893Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
10894 QualType TargetType,
10895 bool Complain,
10896 DeclAccessPair &FoundResult,
10897 bool *pHadMultipleCandidates) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010898 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010899
10900 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
10901 Complain);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010902 int NumMatches = Resolver.getNumMatches();
Craig Topperc3ec1492014-05-26 06:22:03 +000010903 FunctionDecl *Fn = nullptr;
George Burgess IV5f2ef452015-10-12 18:40:58 +000010904 bool ShouldComplain = Complain && !Resolver.hasComplained();
10905 if (NumMatches == 0 && ShouldComplain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010906 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
10907 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
10908 else
10909 Resolver.ComplainNoMatchesFound();
10910 }
George Burgess IV5f2ef452015-10-12 18:40:58 +000010911 else if (NumMatches > 1 && ShouldComplain)
Douglas Gregorb491ed32011-02-19 21:32:49 +000010912 Resolver.ComplainMultipleMatchesFound();
10913 else if (NumMatches == 1) {
10914 Fn = Resolver.getMatchingFunctionDecl();
10915 assert(Fn);
Richard Smith9095e5b2016-11-01 01:31:23 +000010916 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
10917 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010918 FoundResult = *Resolver.getMatchingFunctionAccessPair();
David Majnemera4f7c7a2013-08-01 06:13:59 +000010919 if (Complain) {
10920 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
10921 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
10922 else
10923 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
10924 }
Sebastian Redldf4b80e2009-10-17 21:12:09 +000010925 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010926
10927 if (pHadMultipleCandidates)
10928 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregorb491ed32011-02-19 21:32:49 +000010929 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010930}
10931
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010932/// \brief Given an expression that refers to an overloaded function, try to
George Burgess IV3cde9bf2016-03-19 21:36:10 +000010933/// resolve that function to a single function that can have its address taken.
10934/// This will modify `Pair` iff it returns non-null.
10935///
10936/// This routine can only realistically succeed if all but one candidates in the
10937/// overload set for SrcExpr cannot have their addresses taken.
10938FunctionDecl *
10939Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
10940 DeclAccessPair &Pair) {
10941 OverloadExpr::FindResult R = OverloadExpr::find(E);
10942 OverloadExpr *Ovl = R.Expression;
10943 FunctionDecl *Result = nullptr;
10944 DeclAccessPair DAP;
10945 // Don't use the AddressOfResolver because we're specifically looking for
10946 // cases where we have one overload candidate that lacks
10947 // enable_if/pass_object_size/...
10948 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
10949 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
10950 if (!FD)
10951 return nullptr;
10952
10953 if (!checkAddressOfFunctionIsAvailable(FD))
10954 continue;
10955
10956 // We have more than one result; quit.
10957 if (Result)
10958 return nullptr;
10959 DAP = I.getPair();
10960 Result = FD;
10961 }
10962
10963 if (Result)
10964 Pair = DAP;
10965 return Result;
10966}
10967
George Burgess IVbeca4a32016-06-08 00:34:22 +000010968/// \brief Given an overloaded function, tries to turn it into a non-overloaded
10969/// function reference using resolveAddressOfOnlyViableOverloadCandidate. This
10970/// will perform access checks, diagnose the use of the resultant decl, and, if
10971/// necessary, perform a function-to-pointer decay.
10972///
10973/// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails.
10974/// Otherwise, returns true. This may emit diagnostics and return true.
10975bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate(
10976 ExprResult &SrcExpr) {
10977 Expr *E = SrcExpr.get();
10978 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
10979
10980 DeclAccessPair DAP;
10981 FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP);
10982 if (!Found)
10983 return false;
10984
10985 // Emitting multiple diagnostics for a function that is both inaccessible and
10986 // unavailable is consistent with our behavior elsewhere. So, always check
10987 // for both.
10988 DiagnoseUseOfDecl(Found, E->getExprLoc());
10989 CheckAddressOfMemberAccess(E, DAP);
10990 Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
10991 if (Fixed->getType()->isFunctionType())
10992 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
10993 else
10994 SrcExpr = Fixed;
10995 return true;
10996}
10997
George Burgess IV3cde9bf2016-03-19 21:36:10 +000010998/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010999/// resolve that overloaded function expression down to a single function.
11000///
11001/// This routine can only resolve template-ids that refer to a single function
11002/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011003/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011004/// as described in C++0x [temp.arg.explicit]p3.
Alp Toker67b47ac2013-10-20 18:48:56 +000011005///
11006/// If no template-ids are found, no diagnostics are emitted and NULL is
11007/// returned.
John McCall0009fcc2011-04-26 20:42:42 +000011008FunctionDecl *
11009Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
11010 bool Complain,
11011 DeclAccessPair *FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011012 // C++ [over.over]p1:
11013 // [...] [Note: any redundant set of parentheses surrounding the
11014 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011015 // C++ [over.over]p1:
11016 // [...] The overloaded function name can be preceded by the &
11017 // operator.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011018
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011019 // If we didn't actually find any template-ids, we're done.
John McCall0009fcc2011-04-26 20:42:42 +000011020 if (!ovl->hasExplicitTemplateArgs())
Craig Topperc3ec1492014-05-26 06:22:03 +000011021 return nullptr;
John McCall1acbbb52010-02-02 06:20:04 +000011022
11023 TemplateArgumentListInfo ExplicitTemplateArgs;
James Y Knight04ec5bf2015-12-24 02:59:37 +000011024 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
Larisse Voufo98b20f12013-07-19 23:00:19 +000011025 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011026
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011027 // Look through all of the overloaded functions, searching for one
11028 // whose type matches exactly.
Craig Topperc3ec1492014-05-26 06:22:03 +000011029 FunctionDecl *Matched = nullptr;
John McCall0009fcc2011-04-26 20:42:42 +000011030 for (UnresolvedSetIterator I = ovl->decls_begin(),
11031 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011032 // C++0x [temp.arg.explicit]p3:
11033 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011034 // where deduction is not done, if a template argument list is
11035 // specified and it, along with any default template arguments,
11036 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011037 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +000011038 FunctionTemplateDecl *FunctionTemplate
11039 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011040
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011041 // C++ [over.over]p2:
11042 // If the name is a function template, template argument deduction is
11043 // done (14.8.2.2), and if the argument deduction succeeds, the
11044 // resulting template argument list is used to generate a single
11045 // function template specialization, which is added to the set of
11046 // overloaded functions considered.
Craig Topperc3ec1492014-05-26 06:22:03 +000011047 FunctionDecl *Specialization = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +000011048 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011049 if (TemplateDeductionResult Result
11050 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
Douglas Gregor19a41f12013-04-17 08:45:07 +000011051 Specialization, Info,
Richard Smithbaa47832016-12-01 02:11:49 +000011052 /*IsAddressOfFunction*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000011053 // Make a note of the failed deduction for diagnostics.
11054 // TODO: Actually use the failed-deduction info?
11055 FailedCandidates.addCandidate()
Richard Smithc2bebe92016-05-11 20:37:46 +000011056 .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
Larisse Voufo98b20f12013-07-19 23:00:19 +000011057 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011058 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011059 }
11060
John McCall0009fcc2011-04-26 20:42:42 +000011061 assert(Specialization && "no specialization and no error?");
11062
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011063 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +000011064 if (Matched) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000011065 if (Complain) {
John McCall0009fcc2011-04-26 20:42:42 +000011066 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
11067 << ovl->getName();
11068 NoteAllOverloadCandidates(ovl);
Douglas Gregorb491ed32011-02-19 21:32:49 +000011069 }
Craig Topperc3ec1492014-05-26 06:22:03 +000011070 return nullptr;
John McCall0009fcc2011-04-26 20:42:42 +000011071 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000011072
John McCall0009fcc2011-04-26 20:42:42 +000011073 Matched = Specialization;
11074 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011075 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011076
Richard Smith9095e5b2016-11-01 01:31:23 +000011077 if (Matched &&
11078 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
Craig Topperc3ec1492014-05-26 06:22:03 +000011079 return nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +000011080
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011081 return Matched;
11082}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011083
Douglas Gregor1beec452011-03-12 01:48:56 +000011084
11085
11086
John McCall50a2c2c2011-10-11 23:14:30 +000011087// Resolve and fix an overloaded expression that can be resolved
11088// because it identifies a single function template specialization.
11089//
Douglas Gregor1beec452011-03-12 01:48:56 +000011090// Last three arguments should only be supplied if Complain = true
John McCall50a2c2c2011-10-11 23:14:30 +000011091//
11092// Return true if it was logically possible to so resolve the
11093// expression, regardless of whether or not it succeeded. Always
11094// returns true if 'complain' is set.
11095bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
11096 ExprResult &SrcExpr, bool doFunctionPointerConverion,
Craig Toppere335f252015-10-04 04:53:55 +000011097 bool complain, SourceRange OpRangeForComplaining,
Douglas Gregor1beec452011-03-12 01:48:56 +000011098 QualType DestTypeForComplaining,
John McCall0009fcc2011-04-26 20:42:42 +000011099 unsigned DiagIDForComplaining) {
John McCall50a2c2c2011-10-11 23:14:30 +000011100 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregor1beec452011-03-12 01:48:56 +000011101
John McCall50a2c2c2011-10-11 23:14:30 +000011102 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregor1beec452011-03-12 01:48:56 +000011103
John McCall0009fcc2011-04-26 20:42:42 +000011104 DeclAccessPair found;
11105 ExprResult SingleFunctionExpression;
11106 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
11107 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011108 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall50a2c2c2011-10-11 23:14:30 +000011109 SrcExpr = ExprError();
11110 return true;
11111 }
John McCall0009fcc2011-04-26 20:42:42 +000011112
11113 // It is only correct to resolve to an instance method if we're
11114 // resolving a form that's permitted to be a pointer to member.
11115 // Otherwise we'll end up making a bound member expression, which
11116 // is illegal in all the contexts we resolve like this.
11117 if (!ovl.HasFormOfMemberPointer &&
11118 isa<CXXMethodDecl>(fn) &&
11119 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall50a2c2c2011-10-11 23:14:30 +000011120 if (!complain) return false;
11121
11122 Diag(ovl.Expression->getExprLoc(),
11123 diag::err_bound_member_function)
11124 << 0 << ovl.Expression->getSourceRange();
11125
11126 // TODO: I believe we only end up here if there's a mix of
11127 // static and non-static candidates (otherwise the expression
11128 // would have 'bound member' type, not 'overload' type).
11129 // Ideally we would note which candidate was chosen and why
11130 // the static candidates were rejected.
11131 SrcExpr = ExprError();
11132 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000011133 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +000011134
Sylvestre Ledrua5202662012-07-31 06:56:50 +000011135 // Fix the expression to refer to 'fn'.
John McCall0009fcc2011-04-26 20:42:42 +000011136 SingleFunctionExpression =
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011137 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
John McCall0009fcc2011-04-26 20:42:42 +000011138
11139 // If desired, do function-to-pointer decay.
John McCall50a2c2c2011-10-11 23:14:30 +000011140 if (doFunctionPointerConverion) {
John McCall0009fcc2011-04-26 20:42:42 +000011141 SingleFunctionExpression =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011142 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
John McCall50a2c2c2011-10-11 23:14:30 +000011143 if (SingleFunctionExpression.isInvalid()) {
11144 SrcExpr = ExprError();
11145 return true;
11146 }
11147 }
John McCall0009fcc2011-04-26 20:42:42 +000011148 }
11149
11150 if (!SingleFunctionExpression.isUsable()) {
11151 if (complain) {
11152 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
11153 << ovl.Expression->getName()
11154 << DestTypeForComplaining
11155 << OpRangeForComplaining
11156 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall50a2c2c2011-10-11 23:14:30 +000011157 NoteAllOverloadCandidates(SrcExpr.get());
11158
11159 SrcExpr = ExprError();
11160 return true;
11161 }
11162
11163 return false;
John McCall0009fcc2011-04-26 20:42:42 +000011164 }
11165
John McCall50a2c2c2011-10-11 23:14:30 +000011166 SrcExpr = SingleFunctionExpression;
11167 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000011168}
11169
Douglas Gregorcabea402009-09-22 15:41:20 +000011170/// \brief Add a single candidate to the overload set.
11171static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +000011172 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +000011173 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011174 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000011175 OverloadCandidateSet &CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +000011176 bool PartialOverloading,
11177 bool KnownValid) {
John McCalla0296f72010-03-19 07:35:19 +000011178 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +000011179 if (isa<UsingShadowDecl>(Callee))
11180 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
11181
Douglas Gregorcabea402009-09-22 15:41:20 +000011182 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith95ce4f62011-06-26 22:19:54 +000011183 if (ExplicitTemplateArgs) {
11184 assert(!KnownValid && "Explicit template arguments?");
11185 return;
11186 }
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011187 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
11188 /*SuppressUsedConversions=*/false,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011189 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000011190 return;
John McCalld14a8642009-11-21 08:51:07 +000011191 }
11192
11193 if (FunctionTemplateDecl *FuncTemplate
11194 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +000011195 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011196 ExplicitTemplateArgs, Args, CandidateSet,
11197 /*SuppressUsedConversions=*/false,
11198 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +000011199 return;
11200 }
11201
Richard Smith95ce4f62011-06-26 22:19:54 +000011202 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregorcabea402009-09-22 15:41:20 +000011203}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011204
Douglas Gregorcabea402009-09-22 15:41:20 +000011205/// \brief Add the overload candidates named by callee and/or found by argument
11206/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +000011207void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011208 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000011209 OverloadCandidateSet &CandidateSet,
11210 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +000011211
11212#ifndef NDEBUG
11213 // Verify that ArgumentDependentLookup is consistent with the rules
11214 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +000011215 //
Douglas Gregorcabea402009-09-22 15:41:20 +000011216 // Let X be the lookup set produced by unqualified lookup (3.4.1)
11217 // and let Y be the lookup set produced by argument dependent
11218 // lookup (defined as follows). If X contains
11219 //
11220 // -- a declaration of a class member, or
11221 //
11222 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +000011223 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +000011224 //
11225 // -- a declaration that is neither a function or a function
11226 // template
11227 //
11228 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +000011229
John McCall57500772009-12-16 12:17:52 +000011230 if (ULE->requiresADL()) {
11231 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11232 E = ULE->decls_end(); I != E; ++I) {
11233 assert(!(*I)->getDeclContext()->isRecord());
11234 assert(isa<UsingShadowDecl>(*I) ||
11235 !(*I)->getDeclContext()->isFunctionOrMethod());
11236 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +000011237 }
11238 }
11239#endif
11240
John McCall57500772009-12-16 12:17:52 +000011241 // It would be nice to avoid this copy.
11242 TemplateArgumentListInfo TABuffer;
Craig Topperc3ec1492014-05-26 06:22:03 +000011243 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
John McCall57500772009-12-16 12:17:52 +000011244 if (ULE->hasExplicitTemplateArgs()) {
11245 ULE->copyTemplateArgumentsInto(TABuffer);
11246 ExplicitTemplateArgs = &TABuffer;
11247 }
11248
11249 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11250 E = ULE->decls_end(); I != E; ++I)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011251 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
11252 CandidateSet, PartialOverloading,
11253 /*KnownValid*/ true);
John McCalld14a8642009-11-21 08:51:07 +000011254
John McCall57500772009-12-16 12:17:52 +000011255 if (ULE->requiresADL())
Richard Smith100b24a2014-04-17 01:52:14 +000011256 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011257 Args, ExplicitTemplateArgs,
Richard Smithb6626742012-10-18 17:56:02 +000011258 CandidateSet, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000011259}
John McCalld681c392009-12-16 08:11:27 +000011260
Richard Smith0603bbb2013-06-12 22:56:54 +000011261/// Determine whether a declaration with the specified name could be moved into
11262/// a different namespace.
11263static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
11264 switch (Name.getCXXOverloadedOperator()) {
11265 case OO_New: case OO_Array_New:
11266 case OO_Delete: case OO_Array_Delete:
11267 return false;
11268
11269 default:
11270 return true;
11271 }
11272}
11273
Richard Smith998a5912011-06-05 22:42:48 +000011274/// Attempt to recover from an ill-formed use of a non-dependent name in a
11275/// template, where the non-dependent name was declared after the template
11276/// was defined. This is common in code written for a compilers which do not
11277/// correctly implement two-stage name lookup.
11278///
11279/// Returns true if a viable candidate was found and a diagnostic was issued.
11280static bool
11281DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
11282 const CXXScopeSpec &SS, LookupResult &R,
Richard Smith100b24a2014-04-17 01:52:14 +000011283 OverloadCandidateSet::CandidateSetKind CSK,
Richard Smith998a5912011-06-05 22:42:48 +000011284 TemplateArgumentListInfo *ExplicitTemplateArgs,
Hans Wennborg64937c62015-06-11 21:21:57 +000011285 ArrayRef<Expr *> Args,
11286 bool *DoDiagnoseEmptyLookup = nullptr) {
Richard Smith998a5912011-06-05 22:42:48 +000011287 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
11288 return false;
11289
11290 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewyckyfcd5e7a2012-03-14 20:41:00 +000011291 if (DC->isTransparentContext())
11292 continue;
11293
Richard Smith998a5912011-06-05 22:42:48 +000011294 SemaRef.LookupQualifiedName(R, DC);
11295
11296 if (!R.empty()) {
11297 R.suppressDiagnostics();
11298
11299 if (isa<CXXRecordDecl>(DC)) {
11300 // Don't diagnose names we find in classes; we get much better
11301 // diagnostics for these from DiagnoseEmptyLookup.
11302 R.clear();
Hans Wennborg64937c62015-06-11 21:21:57 +000011303 if (DoDiagnoseEmptyLookup)
11304 *DoDiagnoseEmptyLookup = true;
Richard Smith998a5912011-06-05 22:42:48 +000011305 return false;
11306 }
11307
Richard Smith100b24a2014-04-17 01:52:14 +000011308 OverloadCandidateSet Candidates(FnLoc, CSK);
Richard Smith998a5912011-06-05 22:42:48 +000011309 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
11310 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011311 ExplicitTemplateArgs, Args,
Richard Smith95ce4f62011-06-26 22:19:54 +000011312 Candidates, false, /*KnownValid*/ false);
Richard Smith998a5912011-06-05 22:42:48 +000011313
11314 OverloadCandidateSet::iterator Best;
Richard Smith95ce4f62011-06-26 22:19:54 +000011315 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smith998a5912011-06-05 22:42:48 +000011316 // No viable functions. Don't bother the user with notes for functions
11317 // which don't work and shouldn't be found anyway.
Richard Smith95ce4f62011-06-26 22:19:54 +000011318 R.clear();
Richard Smith998a5912011-06-05 22:42:48 +000011319 return false;
Richard Smith95ce4f62011-06-26 22:19:54 +000011320 }
Richard Smith998a5912011-06-05 22:42:48 +000011321
11322 // Find the namespaces where ADL would have looked, and suggest
11323 // declaring the function there instead.
11324 Sema::AssociatedNamespaceSet AssociatedNamespaces;
11325 Sema::AssociatedClassSet AssociatedClasses;
John McCall7d8b0412012-08-24 20:38:34 +000011326 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
Richard Smith998a5912011-06-05 22:42:48 +000011327 AssociatedNamespaces,
11328 AssociatedClasses);
Chandler Carruthd50f1692011-06-05 23:36:55 +000011329 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smith0603bbb2013-06-12 22:56:54 +000011330 if (canBeDeclaredInNamespace(R.getLookupName())) {
11331 DeclContext *Std = SemaRef.getStdNamespace();
11332 for (Sema::AssociatedNamespaceSet::iterator
11333 it = AssociatedNamespaces.begin(),
11334 end = AssociatedNamespaces.end(); it != end; ++it) {
11335 // Never suggest declaring a function within namespace 'std'.
11336 if (Std && Std->Encloses(*it))
11337 continue;
Richard Smith21bae432012-12-22 02:46:14 +000011338
Richard Smith0603bbb2013-06-12 22:56:54 +000011339 // Never suggest declaring a function within a namespace with a
11340 // reserved name, like __gnu_cxx.
11341 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
11342 if (NS &&
11343 NS->getQualifiedNameAsString().find("__") != std::string::npos)
11344 continue;
11345
11346 SuggestedNamespaces.insert(*it);
11347 }
Richard Smith998a5912011-06-05 22:42:48 +000011348 }
11349
11350 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
11351 << R.getLookupName();
Chandler Carruthd50f1692011-06-05 23:36:55 +000011352 if (SuggestedNamespaces.empty()) {
Richard Smith998a5912011-06-05 22:42:48 +000011353 SemaRef.Diag(Best->Function->getLocation(),
11354 diag::note_not_found_by_two_phase_lookup)
11355 << R.getLookupName() << 0;
Chandler Carruthd50f1692011-06-05 23:36:55 +000011356 } else if (SuggestedNamespaces.size() == 1) {
Richard Smith998a5912011-06-05 22:42:48 +000011357 SemaRef.Diag(Best->Function->getLocation(),
11358 diag::note_not_found_by_two_phase_lookup)
Chandler Carruthd50f1692011-06-05 23:36:55 +000011359 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smith998a5912011-06-05 22:42:48 +000011360 } else {
11361 // FIXME: It would be useful to list the associated namespaces here,
11362 // but the diagnostics infrastructure doesn't provide a way to produce
11363 // a localized representation of a list of items.
11364 SemaRef.Diag(Best->Function->getLocation(),
11365 diag::note_not_found_by_two_phase_lookup)
11366 << R.getLookupName() << 2;
11367 }
11368
11369 // Try to recover by calling this function.
11370 return true;
11371 }
11372
11373 R.clear();
11374 }
11375
11376 return false;
11377}
11378
11379/// Attempt to recover from ill-formed use of a non-dependent operator in a
11380/// template, where the non-dependent operator was declared after the template
11381/// was defined.
11382///
11383/// Returns true if a viable candidate was found and a diagnostic was issued.
11384static bool
11385DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
11386 SourceLocation OpLoc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011387 ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +000011388 DeclarationName OpName =
11389 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
11390 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
11391 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Richard Smith100b24a2014-04-17 01:52:14 +000011392 OverloadCandidateSet::CSK_Operator,
Craig Topperc3ec1492014-05-26 06:22:03 +000011393 /*ExplicitTemplateArgs=*/nullptr, Args);
Richard Smith998a5912011-06-05 22:42:48 +000011394}
11395
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000011396namespace {
Richard Smith88d67f32012-09-25 04:46:05 +000011397class BuildRecoveryCallExprRAII {
11398 Sema &SemaRef;
11399public:
11400 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
11401 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
11402 SemaRef.IsBuildingRecoveryCallExpr = true;
11403 }
11404
11405 ~BuildRecoveryCallExprRAII() {
11406 SemaRef.IsBuildingRecoveryCallExpr = false;
11407 }
11408};
11409
Alexander Kornienkoab9db512015-06-22 23:07:51 +000011410}
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000011411
Kaelyn Takata89c881b2014-10-27 18:07:29 +000011412static std::unique_ptr<CorrectionCandidateCallback>
11413MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
11414 bool HasTemplateArgs, bool AllowTypoCorrection) {
11415 if (!AllowTypoCorrection)
11416 return llvm::make_unique<NoTypoCorrectionCCC>();
11417 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
11418 HasTemplateArgs, ME);
11419}
11420
John McCalld681c392009-12-16 08:11:27 +000011421/// Attempts to recover from a call where no functions were found.
11422///
11423/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +000011424static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +000011425BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +000011426 UnresolvedLookupExpr *ULE,
11427 SourceLocation LParenLoc,
Craig Toppere3d2ecbe2014-06-28 23:22:33 +000011428 MutableArrayRef<Expr *> Args,
Richard Smith998a5912011-06-05 22:42:48 +000011429 SourceLocation RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000011430 bool EmptyLookup, bool AllowTypoCorrection) {
Richard Smith88d67f32012-09-25 04:46:05 +000011431 // Do not try to recover if it is already building a recovery call.
11432 // This stops infinite loops for template instantiations like
11433 //
11434 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
11435 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
11436 //
11437 if (SemaRef.IsBuildingRecoveryCallExpr)
11438 return ExprError();
11439 BuildRecoveryCallExprRAII RCE(SemaRef);
John McCalld681c392009-12-16 08:11:27 +000011440
11441 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +000011442 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +000011443 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCalld681c392009-12-16 08:11:27 +000011444
John McCall57500772009-12-16 12:17:52 +000011445 TemplateArgumentListInfo TABuffer;
Craig Topperc3ec1492014-05-26 06:22:03 +000011446 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
John McCall57500772009-12-16 12:17:52 +000011447 if (ULE->hasExplicitTemplateArgs()) {
11448 ULE->copyTemplateArgumentsInto(TABuffer);
11449 ExplicitTemplateArgs = &TABuffer;
11450 }
11451
John McCalld681c392009-12-16 08:11:27 +000011452 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
11453 Sema::LookupOrdinaryName);
Hans Wennborg64937c62015-06-11 21:21:57 +000011454 bool DoDiagnoseEmptyLookup = EmptyLookup;
Richard Smith998a5912011-06-05 22:42:48 +000011455 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Richard Smith100b24a2014-04-17 01:52:14 +000011456 OverloadCandidateSet::CSK_Normal,
Hans Wennborg64937c62015-06-11 21:21:57 +000011457 ExplicitTemplateArgs, Args,
11458 &DoDiagnoseEmptyLookup) &&
11459 (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup(
11460 S, SS, R,
11461 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
11462 ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
11463 ExplicitTemplateArgs, Args)))
John McCallfaf5fb42010-08-26 23:41:50 +000011464 return ExprError();
John McCalld681c392009-12-16 08:11:27 +000011465
John McCall57500772009-12-16 12:17:52 +000011466 assert(!R.empty() && "lookup results empty despite recovery");
11467
Richard Smith151c4562016-12-20 21:35:28 +000011468 // If recovery created an ambiguity, just bail out.
11469 if (R.isAmbiguous()) {
11470 R.suppressDiagnostics();
11471 return ExprError();
11472 }
11473
John McCall57500772009-12-16 12:17:52 +000011474 // Build an implicit member call if appropriate. Just drop the
11475 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +000011476 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +000011477 if ((*R.begin())->isCXXClassMember())
Aaron Ballman6924dcd2015-09-01 14:49:24 +000011478 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
11479 ExplicitTemplateArgs, S);
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000011480 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnara7945c982012-01-27 09:46:47 +000011481 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000011482 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +000011483 else
11484 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
11485
11486 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +000011487 return ExprError();
John McCall57500772009-12-16 12:17:52 +000011488
11489 // This shouldn't cause an infinite loop because we're giving it
Richard Smith998a5912011-06-05 22:42:48 +000011490 // an expression with viable lookup results, which should never
John McCall57500772009-12-16 12:17:52 +000011491 // end up here.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011492 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011493 MultiExprArg(Args.data(), Args.size()),
11494 RParenLoc);
John McCalld681c392009-12-16 08:11:27 +000011495}
Douglas Gregor4038cf42010-06-08 17:35:15 +000011496
Sam Panzer0f384432012-08-21 00:52:01 +000011497/// \brief Constructs and populates an OverloadedCandidateSet from
11498/// the given function.
11499/// \returns true when an the ExprResult output parameter has been set.
11500bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
11501 UnresolvedLookupExpr *ULE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011502 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011503 SourceLocation RParenLoc,
11504 OverloadCandidateSet *CandidateSet,
11505 ExprResult *Result) {
John McCall57500772009-12-16 12:17:52 +000011506#ifndef NDEBUG
11507 if (ULE->requiresADL()) {
11508 // To do ADL, we must have found an unqualified name.
11509 assert(!ULE->getQualifier() && "qualified name with ADL");
11510
11511 // We don't perform ADL for implicit declarations of builtins.
11512 // Verify that this was correctly set up.
11513 FunctionDecl *F;
11514 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
11515 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
11516 F->getBuiltinID() && F->isImplicit())
David Blaikie83d382b2011-09-23 05:06:16 +000011517 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011518
John McCall57500772009-12-16 12:17:52 +000011519 // We don't perform ADL in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011520 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smithb6626742012-10-18 17:56:02 +000011521 }
John McCall57500772009-12-16 12:17:52 +000011522#endif
11523
John McCall4124c492011-10-17 18:40:02 +000011524 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011525 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
Sam Panzer0f384432012-08-21 00:52:01 +000011526 *Result = ExprError();
11527 return true;
11528 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +000011529
John McCall57500772009-12-16 12:17:52 +000011530 // Add the functions denoted by the callee to the set of candidate
11531 // functions, including those from argument-dependent lookup.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011532 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
John McCalld681c392009-12-16 08:11:27 +000011533
Hans Wennborgb2747382015-06-12 21:23:23 +000011534 if (getLangOpts().MSVCCompat &&
11535 CurContext->isDependentContext() && !isSFINAEContext() &&
Hans Wennborg64937c62015-06-11 21:21:57 +000011536 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
11537
11538 OverloadCandidateSet::iterator Best;
11539 if (CandidateSet->empty() ||
11540 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) ==
11541 OR_No_Viable_Function) {
11542 // In Microsoft mode, if we are inside a template class member function then
11543 // create a type dependent CallExpr. The goal is to postpone name lookup
11544 // to instantiation time to be able to search into type dependent base
11545 // classes.
11546 CallExpr *CE = new (Context) CallExpr(
11547 Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc);
Sebastian Redlb49c46c2011-09-24 17:48:00 +000011548 CE->setTypeDependent(true);
Richard Smithed9b8f02015-09-23 21:30:47 +000011549 CE->setValueDependent(true);
11550 CE->setInstantiationDependent(true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011551 *Result = CE;
Sam Panzer0f384432012-08-21 00:52:01 +000011552 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +000011553 }
Francois Pichetbcf64712011-09-07 00:14:57 +000011554 }
John McCalld681c392009-12-16 08:11:27 +000011555
Hans Wennborg64937c62015-06-11 21:21:57 +000011556 if (CandidateSet->empty())
11557 return false;
11558
John McCall4124c492011-10-17 18:40:02 +000011559 UnbridgedCasts.restore();
Sam Panzer0f384432012-08-21 00:52:01 +000011560 return false;
11561}
John McCall4124c492011-10-17 18:40:02 +000011562
Sam Panzer0f384432012-08-21 00:52:01 +000011563/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
11564/// the completed call expression. If overload resolution fails, emits
11565/// diagnostics and returns ExprError()
11566static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11567 UnresolvedLookupExpr *ULE,
11568 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011569 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011570 SourceLocation RParenLoc,
11571 Expr *ExecConfig,
11572 OverloadCandidateSet *CandidateSet,
11573 OverloadCandidateSet::iterator *Best,
11574 OverloadingResult OverloadResult,
11575 bool AllowTypoCorrection) {
11576 if (CandidateSet->empty())
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011577 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011578 RParenLoc, /*EmptyLookup=*/true,
11579 AllowTypoCorrection);
11580
11581 switch (OverloadResult) {
John McCall57500772009-12-16 12:17:52 +000011582 case OR_Success: {
Sam Panzer0f384432012-08-21 00:52:01 +000011583 FunctionDecl *FDecl = (*Best)->Function;
Sam Panzer0f384432012-08-21 00:52:01 +000011584 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000011585 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
11586 return ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000011587 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011588 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11589 ExecConfig);
John McCall57500772009-12-16 12:17:52 +000011590 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011591
Richard Smith998a5912011-06-05 22:42:48 +000011592 case OR_No_Viable_Function: {
11593 // Try to recover by looking for viable functions which the user might
11594 // have meant to call.
Sam Panzer0f384432012-08-21 00:52:01 +000011595 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011596 Args, RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000011597 /*EmptyLookup=*/false,
11598 AllowTypoCorrection);
Richard Smith998a5912011-06-05 22:42:48 +000011599 if (!Recovery.isInvalid())
11600 return Recovery;
11601
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011602 // If the user passes in a function that we can't take the address of, we
11603 // generally end up emitting really bad error messages. Here, we attempt to
11604 // emit better ones.
11605 for (const Expr *Arg : Args) {
11606 if (!Arg->getType()->isFunctionType())
11607 continue;
11608 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
11609 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
11610 if (FD &&
11611 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
11612 Arg->getExprLoc()))
11613 return ExprError();
11614 }
11615 }
11616
11617 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_no_viable_function_in_call)
11618 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011619 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011620 break;
Richard Smith998a5912011-06-05 22:42:48 +000011621 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011622
11623 case OR_Ambiguous:
Sam Panzer0f384432012-08-21 00:52:01 +000011624 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +000011625 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011626 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011627 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000011628
Sam Panzer0f384432012-08-21 00:52:01 +000011629 case OR_Deleted: {
11630 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
11631 << (*Best)->Function->isDeleted()
11632 << ULE->getName()
11633 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
11634 << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011635 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Argyrios Kyrtzidis3eaa22a2011-11-04 15:58:13 +000011636
Sam Panzer0f384432012-08-21 00:52:01 +000011637 // We emitted an error for the unvailable/deleted function call but keep
11638 // the call in the AST.
11639 FunctionDecl *FDecl = (*Best)->Function;
11640 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011641 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11642 ExecConfig);
Sam Panzer0f384432012-08-21 00:52:01 +000011643 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011644 }
11645
Douglas Gregorb412e172010-07-25 18:17:45 +000011646 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +000011647 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011648}
11649
George Burgess IV7204ed92016-01-07 02:26:57 +000011650static void markUnaddressableCandidatesUnviable(Sema &S,
11651 OverloadCandidateSet &CS) {
11652 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
11653 if (I->Viable &&
11654 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
11655 I->Viable = false;
11656 I->FailureKind = ovl_fail_addr_not_available;
11657 }
11658 }
11659}
11660
Sam Panzer0f384432012-08-21 00:52:01 +000011661/// BuildOverloadedCallExpr - Given the call expression that calls Fn
11662/// (which eventually refers to the declaration Func) and the call
11663/// arguments Args/NumArgs, attempt to resolve the function call down
11664/// to a specific function. If overload resolution succeeds, returns
11665/// the call expression produced by overload resolution.
11666/// Otherwise, emits diagnostics and returns ExprError.
11667ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
11668 UnresolvedLookupExpr *ULE,
11669 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011670 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011671 SourceLocation RParenLoc,
11672 Expr *ExecConfig,
George Burgess IV7204ed92016-01-07 02:26:57 +000011673 bool AllowTypoCorrection,
11674 bool CalleesAddressIsTaken) {
Richard Smith100b24a2014-04-17 01:52:14 +000011675 OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
11676 OverloadCandidateSet::CSK_Normal);
Sam Panzer0f384432012-08-21 00:52:01 +000011677 ExprResult result;
11678
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011679 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
11680 &result))
Sam Panzer0f384432012-08-21 00:52:01 +000011681 return result;
11682
George Burgess IV7204ed92016-01-07 02:26:57 +000011683 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
11684 // functions that aren't addressible are considered unviable.
11685 if (CalleesAddressIsTaken)
11686 markUnaddressableCandidatesUnviable(*this, CandidateSet);
11687
Sam Panzer0f384432012-08-21 00:52:01 +000011688 OverloadCandidateSet::iterator Best;
11689 OverloadingResult OverloadResult =
11690 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
11691
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011692 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011693 RParenLoc, ExecConfig, &CandidateSet,
11694 &Best, OverloadResult,
11695 AllowTypoCorrection);
11696}
11697
John McCall4c4c1df2010-01-26 03:27:55 +000011698static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +000011699 return Functions.size() > 1 ||
11700 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
11701}
11702
Douglas Gregor084d8552009-03-13 23:49:33 +000011703/// \brief Create a unary operation that may resolve to an overloaded
11704/// operator.
11705///
11706/// \param OpLoc The location of the operator itself (e.g., '*').
11707///
Craig Toppera92ffb02015-12-10 08:51:49 +000011708/// \param Opc The UnaryOperatorKind that describes this operator.
Douglas Gregor084d8552009-03-13 23:49:33 +000011709///
James Dennett18348b62012-06-22 08:52:37 +000011710/// \param Fns The set of non-member functions that will be
Douglas Gregor084d8552009-03-13 23:49:33 +000011711/// considered by overload resolution. The caller needs to build this
11712/// set based on the context using, e.g.,
11713/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11714/// set should not contain any member functions; those will be added
11715/// by CreateOverloadedUnaryOp().
11716///
James Dennett91738ff2012-06-22 10:32:46 +000011717/// \param Input The input argument.
John McCalldadc5752010-08-24 06:29:42 +000011718ExprResult
Craig Toppera92ffb02015-12-10 08:51:49 +000011719Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
John McCall4c4c1df2010-01-26 03:27:55 +000011720 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +000011721 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +000011722 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
11723 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
11724 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011725 // TODO: provide better source location info.
11726 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +000011727
John McCall4124c492011-10-17 18:40:02 +000011728 if (checkPlaceholderForOverload(*this, Input))
11729 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011730
Craig Topperc3ec1492014-05-26 06:22:03 +000011731 Expr *Args[2] = { Input, nullptr };
Douglas Gregor084d8552009-03-13 23:49:33 +000011732 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +000011733
Douglas Gregor084d8552009-03-13 23:49:33 +000011734 // For post-increment and post-decrement, add the implicit '0' as
11735 // the second argument, so that we know this is a post-increment or
11736 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +000011737 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +000011738 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +000011739 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
11740 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +000011741 NumArgs = 2;
11742 }
11743
Richard Smithe54c3072013-05-05 15:51:06 +000011744 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
11745
Douglas Gregor084d8552009-03-13 23:49:33 +000011746 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +000011747 if (Fns.empty())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011748 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
11749 VK_RValue, OK_Ordinary, OpLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011750
Craig Topperc3ec1492014-05-26 06:22:03 +000011751 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +000011752 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000011753 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000011754 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000011755 /*ADL*/ true, IsOverloaded(Fns),
11756 Fns.begin(), Fns.end());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011757 return new (Context)
11758 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
11759 VK_RValue, OpLoc, false);
Douglas Gregor084d8552009-03-13 23:49:33 +000011760 }
11761
11762 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000011763 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
Douglas Gregor084d8552009-03-13 23:49:33 +000011764
11765 // Add the candidates from the given function set.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011766 AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000011767
11768 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000011769 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000011770
John McCall4c4c1df2010-01-26 03:27:55 +000011771 // Add candidates from ADL.
Richard Smith100b24a2014-04-17 01:52:14 +000011772 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
Craig Topperc3ec1492014-05-26 06:22:03 +000011773 /*ExplicitTemplateArgs*/nullptr,
11774 CandidateSet);
John McCall4c4c1df2010-01-26 03:27:55 +000011775
Douglas Gregor084d8552009-03-13 23:49:33 +000011776 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011777 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000011778
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011779 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11780
Douglas Gregor084d8552009-03-13 23:49:33 +000011781 // Perform overload resolution.
11782 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011783 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +000011784 case OR_Success: {
11785 // We found a built-in operator or an overloaded operator.
11786 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +000011787
Douglas Gregor084d8552009-03-13 23:49:33 +000011788 if (FnDecl) {
11789 // We matched an overloaded operator. Build a call to that
11790 // operator.
Mike Stump11289f42009-09-09 15:08:12 +000011791
Douglas Gregor084d8552009-03-13 23:49:33 +000011792 // Convert the arguments.
11793 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Craig Topperc3ec1492014-05-26 06:22:03 +000011794 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000011795
John Wiegley01296292011-04-08 18:41:53 +000011796 ExprResult InputRes =
Craig Topperc3ec1492014-05-26 06:22:03 +000011797 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000011798 Best->FoundDecl, Method);
11799 if (InputRes.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000011800 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011801 Input = InputRes.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000011802 } else {
11803 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000011804 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +000011805 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000011806 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +000011807 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011808 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +000011809 Input);
Douglas Gregore6600372009-12-23 17:40:29 +000011810 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000011811 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011812 Input = InputInit.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000011813 }
11814
Douglas Gregor084d8552009-03-13 23:49:33 +000011815 // Build the actual expression node.
Nick Lewycky134af912013-02-07 05:08:22 +000011816 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011817 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011818 if (FnExpr.isInvalid())
11819 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +000011820
Richard Smithc1564702013-11-15 02:58:23 +000011821 // Determine the result type.
Alp Toker314cc812014-01-25 16:55:45 +000011822 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000011823 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11824 ResultTy = ResultTy.getNonLValueExprType(Context);
11825
Eli Friedman030eee42009-11-18 03:58:17 +000011826 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +000011827 CallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011828 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
Lang Hames5de91cc2012-10-02 04:45:10 +000011829 ResultTy, VK, OpLoc, false);
John McCall4fa0d5f2010-05-06 18:15:07 +000011830
Alp Toker314cc812014-01-25 16:55:45 +000011831 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
Anders Carlssonf64a3da2009-10-13 21:19:37 +000011832 return ExprError();
11833
John McCallb268a282010-08-23 23:25:46 +000011834 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +000011835 } else {
11836 // We matched a built-in operator. Convert the arguments, then
11837 // break out so that we will build the appropriate built-in
11838 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000011839 ExprResult InputRes =
11840 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
11841 Best->Conversions[0], AA_Passing);
11842 if (InputRes.isInvalid())
11843 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011844 Input = InputRes.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000011845 break;
Douglas Gregor084d8552009-03-13 23:49:33 +000011846 }
John Wiegley01296292011-04-08 18:41:53 +000011847 }
11848
11849 case OR_No_Viable_Function:
Richard Smith998a5912011-06-05 22:42:48 +000011850 // This is an erroneous use of an operator which can be overloaded by
11851 // a non-member function. Check for non-member operators which were
11852 // defined too late to be candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011853 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
Richard Smith998a5912011-06-05 22:42:48 +000011854 // FIXME: Recover by calling the found function.
11855 return ExprError();
11856
John Wiegley01296292011-04-08 18:41:53 +000011857 // No viable function; fall through to handling this as a
11858 // built-in operator, which will produce an error message for us.
11859 break;
11860
11861 case OR_Ambiguous:
11862 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
11863 << UnaryOperator::getOpcodeStr(Opc)
11864 << Input->getType()
11865 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000011866 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
John Wiegley01296292011-04-08 18:41:53 +000011867 UnaryOperator::getOpcodeStr(Opc), OpLoc);
11868 return ExprError();
11869
11870 case OR_Deleted:
11871 Diag(OpLoc, diag::err_ovl_deleted_oper)
11872 << Best->Function->isDeleted()
11873 << UnaryOperator::getOpcodeStr(Opc)
11874 << getDeletedOrUnavailableSuffix(Best->Function)
11875 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000011876 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000011877 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011878 return ExprError();
11879 }
Douglas Gregor084d8552009-03-13 23:49:33 +000011880
11881 // Either we found no viable overloaded operator or we matched a
11882 // built-in operator. In either case, fall through to trying to
11883 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +000011884 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +000011885}
11886
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011887/// \brief Create a binary operation that may resolve to an overloaded
11888/// operator.
11889///
11890/// \param OpLoc The location of the operator itself (e.g., '+').
11891///
Craig Toppera92ffb02015-12-10 08:51:49 +000011892/// \param Opc The BinaryOperatorKind that describes this operator.
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011893///
James Dennett18348b62012-06-22 08:52:37 +000011894/// \param Fns The set of non-member functions that will be
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011895/// considered by overload resolution. The caller needs to build this
11896/// set based on the context using, e.g.,
11897/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11898/// set should not contain any member functions; those will be added
11899/// by CreateOverloadedBinOp().
11900///
11901/// \param LHS Left-hand argument.
11902/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +000011903ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011904Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Craig Toppera92ffb02015-12-10 08:51:49 +000011905 BinaryOperatorKind Opc,
John McCall4c4c1df2010-01-26 03:27:55 +000011906 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011907 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011908 Expr *Args[2] = { LHS, RHS };
Craig Topperc3ec1492014-05-26 06:22:03 +000011909 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011910
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011911 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
11912 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
11913
11914 // If either side is type-dependent, create an appropriate dependent
11915 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +000011916 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +000011917 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011918 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +000011919 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +000011920 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011921 return new (Context) BinaryOperator(
11922 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
11923 OpLoc, FPFeatures.fp_contract);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011924
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011925 return new (Context) CompoundAssignOperator(
11926 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
11927 Context.DependentTy, Context.DependentTy, OpLoc,
11928 FPFeatures.fp_contract);
Douglas Gregor5287f092009-11-05 00:51:44 +000011929 }
John McCall4c4c1df2010-01-26 03:27:55 +000011930
11931 // FIXME: save results of ADL from here?
Craig Topperc3ec1492014-05-26 06:22:03 +000011932 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011933 // TODO: provide better source location info in DNLoc component.
11934 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +000011935 UnresolvedLookupExpr *Fn
Douglas Gregor0da1d432011-02-28 20:01:57 +000011936 = UnresolvedLookupExpr::Create(Context, NamingClass,
11937 NestedNameSpecifierLoc(), OpNameInfo,
11938 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000011939 Fns.begin(), Fns.end());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011940 return new (Context)
11941 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
11942 VK_RValue, OpLoc, FPFeatures.fp_contract);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011943 }
11944
John McCall4124c492011-10-17 18:40:02 +000011945 // Always do placeholder-like conversions on the RHS.
11946 if (checkPlaceholderForOverload(*this, Args[1]))
11947 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011948
John McCall526ab472011-10-25 17:37:35 +000011949 // Do placeholder-like conversion on the LHS; note that we should
11950 // not get here with a PseudoObject LHS.
11951 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall4124c492011-10-17 18:40:02 +000011952 if (checkPlaceholderForOverload(*this, Args[0]))
11953 return ExprError();
11954
Sebastian Redl6a96bf72009-11-18 23:10:33 +000011955 // If this is the assignment operator, we only perform overload resolution
11956 // if the left-hand side is a class or enumeration type. This is actually
11957 // a hack. The standard requires that we do overload resolution between the
11958 // various built-in candidates, but as DR507 points out, this can lead to
11959 // problems. So we do it this way, which pretty much follows what GCC does.
11960 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +000011961 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +000011962 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011963
John McCalle26a8722010-12-04 08:14:53 +000011964 // If this is the .* operator, which is not overloadable, just
11965 // create a built-in binary operator.
11966 if (Opc == BO_PtrMemD)
11967 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11968
Douglas Gregor084d8552009-03-13 23:49:33 +000011969 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000011970 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011971
11972 // Add the candidates from the given function set.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011973 AddFunctionCandidates(Fns, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011974
11975 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000011976 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011977
Richard Smith0daabd72014-09-23 20:31:39 +000011978 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
11979 // performed for an assignment operator (nor for operator[] nor operator->,
11980 // which don't get here).
11981 if (Opc != BO_Assign)
11982 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
11983 /*ExplicitTemplateArgs*/ nullptr,
11984 CandidateSet);
John McCall4c4c1df2010-01-26 03:27:55 +000011985
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011986 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011987 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011988
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011989 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11990
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011991 // Perform overload resolution.
11992 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011993 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +000011994 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011995 // We found a built-in operator or an overloaded operator.
11996 FunctionDecl *FnDecl = Best->Function;
11997
11998 if (FnDecl) {
11999 // We matched an overloaded operator. Build a call to that
12000 // operator.
12001
12002 // Convert the arguments.
12003 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +000012004 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +000012005 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000012006
Chandler Carruth8e543b32010-12-12 08:17:55 +000012007 ExprResult Arg1 =
12008 PerformCopyInitialization(
12009 InitializedEntity::InitializeParameter(Context,
12010 FnDecl->getParamDecl(0)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012011 SourceLocation(), Args[1]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000012012 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012013 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000012014
John Wiegley01296292011-04-08 18:41:53 +000012015 ExprResult Arg0 =
Craig Topperc3ec1492014-05-26 06:22:03 +000012016 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012017 Best->FoundDecl, Method);
12018 if (Arg0.isInvalid())
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000012019 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012020 Args[0] = Arg0.getAs<Expr>();
12021 Args[1] = RHS = Arg1.getAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012022 } else {
12023 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +000012024 ExprResult Arg0 = PerformCopyInitialization(
12025 InitializedEntity::InitializeParameter(Context,
12026 FnDecl->getParamDecl(0)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012027 SourceLocation(), Args[0]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000012028 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012029 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000012030
Chandler Carruth8e543b32010-12-12 08:17:55 +000012031 ExprResult Arg1 =
12032 PerformCopyInitialization(
12033 InitializedEntity::InitializeParameter(Context,
12034 FnDecl->getParamDecl(1)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012035 SourceLocation(), Args[1]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000012036 if (Arg1.isInvalid())
12037 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012038 Args[0] = LHS = Arg0.getAs<Expr>();
12039 Args[1] = RHS = Arg1.getAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012040 }
12041
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012042 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012043 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000012044 Best->FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012045 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000012046 if (FnExpr.isInvalid())
12047 return ExprError();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012048
Richard Smithc1564702013-11-15 02:58:23 +000012049 // Determine the result type.
Alp Toker314cc812014-01-25 16:55:45 +000012050 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000012051 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12052 ResultTy = ResultTy.getNonLValueExprType(Context);
12053
John McCallb268a282010-08-23 23:25:46 +000012054 CXXOperatorCallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012055 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
Lang Hames5de91cc2012-10-02 04:45:10 +000012056 Args, ResultTy, VK, OpLoc,
12057 FPFeatures.fp_contract);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012058
Alp Toker314cc812014-01-25 16:55:45 +000012059 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000012060 FnDecl))
12061 return ExprError();
12062
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000012063 ArrayRef<const Expr *> ArgsArray(Args, 2);
12064 // Cut off the implicit 'this'.
12065 if (isa<CXXMethodDecl>(FnDecl))
12066 ArgsArray = ArgsArray.slice(1);
Richard Trieu36d0b2b2015-01-13 02:32:02 +000012067
12068 // Check for a self move.
12069 if (Op == OO_Equal)
12070 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
12071
Douglas Gregorb4866e82015-06-19 18:13:19 +000012072 checkCall(FnDecl, nullptr, ArgsArray, isa<CXXMethodDecl>(FnDecl), OpLoc,
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000012073 TheCall->getSourceRange(), VariadicDoesNotApply);
12074
John McCallb268a282010-08-23 23:25:46 +000012075 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012076 } else {
12077 // We matched a built-in operator. Convert the arguments, then
12078 // break out so that we will build the appropriate built-in
12079 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000012080 ExprResult ArgsRes0 =
12081 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
12082 Best->Conversions[0], AA_Passing);
12083 if (ArgsRes0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012084 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012085 Args[0] = ArgsRes0.get();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012086
John Wiegley01296292011-04-08 18:41:53 +000012087 ExprResult ArgsRes1 =
12088 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
12089 Best->Conversions[1], AA_Passing);
12090 if (ArgsRes1.isInvalid())
12091 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012092 Args[1] = ArgsRes1.get();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012093 break;
12094 }
12095 }
12096
Douglas Gregor66950a32009-09-30 21:46:01 +000012097 case OR_No_Viable_Function: {
12098 // C++ [over.match.oper]p9:
12099 // If the operator is the operator , [...] and there are no
12100 // viable functions, then the operator is assumed to be the
12101 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +000012102 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +000012103 break;
12104
Chandler Carruth8e543b32010-12-12 08:17:55 +000012105 // For class as left operand for assignment or compound assigment
12106 // operator do not fall through to handling in built-in, but report that
12107 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +000012108 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012109 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +000012110 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +000012111 Diag(OpLoc, diag::err_ovl_no_viable_oper)
12112 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +000012113 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Eli Friedmana31efa02013-08-28 20:35:35 +000012114 if (Args[0]->getType()->isIncompleteType()) {
12115 Diag(OpLoc, diag::note_assign_lhs_incomplete)
12116 << Args[0]->getType()
12117 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12118 }
Douglas Gregor66950a32009-09-30 21:46:01 +000012119 } else {
Richard Smith998a5912011-06-05 22:42:48 +000012120 // This is an erroneous use of an operator which can be overloaded by
12121 // a non-member function. Check for non-member operators which were
12122 // defined too late to be candidates.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012123 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smith998a5912011-06-05 22:42:48 +000012124 // FIXME: Recover by calling the found function.
12125 return ExprError();
12126
Douglas Gregor66950a32009-09-30 21:46:01 +000012127 // No viable function; try to create a built-in operation, which will
12128 // produce an error. Then, show the non-viable candidates.
12129 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +000012130 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012131 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +000012132 "C++ binary operator overloading is missing candidates!");
12133 if (Result.isInvalid())
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012134 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012135 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012136 return Result;
Douglas Gregor66950a32009-09-30 21:46:01 +000012137 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012138
12139 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000012140 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012141 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +000012142 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +000012143 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012144 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012145 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012146 return ExprError();
12147
12148 case OR_Deleted:
Douglas Gregor74f7d502012-02-15 19:33:52 +000012149 if (isImplicitlyDeleted(Best->Function)) {
12150 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12151 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
Richard Smithde1a4872012-12-28 12:23:24 +000012152 << Context.getRecordType(Method->getParent())
12153 << getSpecialMember(Method);
Richard Smith6f1e2c62012-04-02 20:59:25 +000012154
Richard Smithde1a4872012-12-28 12:23:24 +000012155 // The user probably meant to call this special member. Just
12156 // explain why it's deleted.
12157 NoteDeletedFunction(Method);
12158 return ExprError();
Douglas Gregor74f7d502012-02-15 19:33:52 +000012159 } else {
12160 Diag(OpLoc, diag::err_ovl_deleted_oper)
12161 << Best->Function->isDeleted()
12162 << BinaryOperator::getOpcodeStr(Opc)
12163 << getDeletedOrUnavailableSuffix(Best->Function)
12164 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12165 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012166 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000012167 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012168 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +000012169 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012170
Douglas Gregor66950a32009-09-30 21:46:01 +000012171 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +000012172 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012173}
12174
John McCalldadc5752010-08-24 06:29:42 +000012175ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +000012176Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
12177 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +000012178 Expr *Base, Expr *Idx) {
12179 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +000012180 DeclarationName OpName =
12181 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
12182
12183 // If either side is type-dependent, create an appropriate dependent
12184 // expression.
12185 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12186
Craig Topperc3ec1492014-05-26 06:22:03 +000012187 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000012188 // CHECKME: no 'operator' keyword?
12189 DeclarationNameInfo OpNameInfo(OpName, LLoc);
12190 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +000012191 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000012192 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000012193 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000012194 /*ADL*/ true, /*Overloaded*/ false,
12195 UnresolvedSetIterator(),
12196 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +000012197 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +000012198
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012199 return new (Context)
12200 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
12201 Context.DependentTy, VK_RValue, RLoc, false);
Sebastian Redladba46e2009-10-29 20:17:01 +000012202 }
12203
John McCall4124c492011-10-17 18:40:02 +000012204 // Handle placeholders on both operands.
12205 if (checkPlaceholderForOverload(*this, Args[0]))
12206 return ExprError();
12207 if (checkPlaceholderForOverload(*this, Args[1]))
12208 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012209
Sebastian Redladba46e2009-10-29 20:17:01 +000012210 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000012211 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
Sebastian Redladba46e2009-10-29 20:17:01 +000012212
12213 // Subscript can only be overloaded as a member function.
12214
12215 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000012216 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000012217
12218 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000012219 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000012220
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012221 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12222
Sebastian Redladba46e2009-10-29 20:17:01 +000012223 // Perform overload resolution.
12224 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012225 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +000012226 case OR_Success: {
12227 // We found a built-in operator or an overloaded operator.
12228 FunctionDecl *FnDecl = Best->Function;
12229
12230 if (FnDecl) {
12231 // We matched an overloaded operator. Build a call to that
12232 // operator.
12233
John McCalla0296f72010-03-19 07:35:19 +000012234 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall58cc69d2010-01-27 01:50:18 +000012235
Sebastian Redladba46e2009-10-29 20:17:01 +000012236 // Convert the arguments.
12237 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley01296292011-04-08 18:41:53 +000012238 ExprResult Arg0 =
Craig Topperc3ec1492014-05-26 06:22:03 +000012239 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012240 Best->FoundDecl, Method);
12241 if (Arg0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000012242 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012243 Args[0] = Arg0.get();
Sebastian Redladba46e2009-10-29 20:17:01 +000012244
Anders Carlssona68e51e2010-01-29 18:37:50 +000012245 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000012246 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +000012247 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000012248 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +000012249 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012250 SourceLocation(),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012251 Args[1]);
Anders Carlssona68e51e2010-01-29 18:37:50 +000012252 if (InputInit.isInvalid())
12253 return ExprError();
12254
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012255 Args[1] = InputInit.getAs<Expr>();
Anders Carlssona68e51e2010-01-29 18:37:50 +000012256
Sebastian Redladba46e2009-10-29 20:17:01 +000012257 // Build the actual expression node.
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012258 DeclarationNameInfo OpLocInfo(OpName, LLoc);
12259 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012260 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000012261 Best->FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012262 HadMultipleCandidates,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012263 OpLocInfo.getLoc(),
12264 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000012265 if (FnExpr.isInvalid())
12266 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000012267
Richard Smithc1564702013-11-15 02:58:23 +000012268 // Determine the result type
Alp Toker314cc812014-01-25 16:55:45 +000012269 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000012270 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12271 ResultTy = ResultTy.getNonLValueExprType(Context);
12272
John McCallb268a282010-08-23 23:25:46 +000012273 CXXOperatorCallExpr *TheCall =
12274 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012275 FnExpr.get(), Args,
Lang Hames5de91cc2012-10-02 04:45:10 +000012276 ResultTy, VK, RLoc,
12277 false);
Sebastian Redladba46e2009-10-29 20:17:01 +000012278
Alp Toker314cc812014-01-25 16:55:45 +000012279 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
Sebastian Redladba46e2009-10-29 20:17:01 +000012280 return ExprError();
12281
John McCallb268a282010-08-23 23:25:46 +000012282 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +000012283 } else {
12284 // We matched a built-in operator. Convert the arguments, then
12285 // break out so that we will build the appropriate built-in
12286 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000012287 ExprResult ArgsRes0 =
12288 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
12289 Best->Conversions[0], AA_Passing);
12290 if (ArgsRes0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000012291 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012292 Args[0] = ArgsRes0.get();
John Wiegley01296292011-04-08 18:41:53 +000012293
12294 ExprResult ArgsRes1 =
12295 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
12296 Best->Conversions[1], AA_Passing);
12297 if (ArgsRes1.isInvalid())
12298 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012299 Args[1] = ArgsRes1.get();
Sebastian Redladba46e2009-10-29 20:17:01 +000012300
12301 break;
12302 }
12303 }
12304
12305 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +000012306 if (CandidateSet.empty())
12307 Diag(LLoc, diag::err_ovl_no_oper)
12308 << Args[0]->getType() << /*subscript*/ 0
12309 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12310 else
12311 Diag(LLoc, diag::err_ovl_no_viable_subscript)
12312 << Args[0]->getType()
12313 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012314 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012315 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +000012316 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000012317 }
12318
12319 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000012320 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012321 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +000012322 << Args[0]->getType() << Args[1]->getType()
12323 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012324 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012325 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000012326 return ExprError();
12327
12328 case OR_Deleted:
12329 Diag(LLoc, diag::err_ovl_deleted_oper)
12330 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012331 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +000012332 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012333 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012334 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000012335 return ExprError();
12336 }
12337
12338 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +000012339 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000012340}
12341
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012342/// BuildCallToMemberFunction - Build a call to a member
12343/// function. MemExpr is the expression that refers to the member
12344/// function (and includes the object parameter), Args/NumArgs are the
12345/// arguments to the function call (not including the object
12346/// parameter). The caller needs to validate that the member
John McCall0009fcc2011-04-26 20:42:42 +000012347/// expression refers to a non-static member function or an overloaded
12348/// member function.
John McCalldadc5752010-08-24 06:29:42 +000012349ExprResult
Mike Stump11289f42009-09-09 15:08:12 +000012350Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012351 SourceLocation LParenLoc,
12352 MultiExprArg Args,
12353 SourceLocation RParenLoc) {
John McCall0009fcc2011-04-26 20:42:42 +000012354 assert(MemExprE->getType() == Context.BoundMemberTy ||
12355 MemExprE->getType() == Context.OverloadTy);
12356
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012357 // Dig out the member expression. This holds both the object
12358 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +000012359 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012360
John McCall0009fcc2011-04-26 20:42:42 +000012361 // Determine whether this is a call to a pointer-to-member function.
12362 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
12363 assert(op->getType() == Context.BoundMemberTy);
12364 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
12365
12366 QualType fnType =
12367 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
12368
12369 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
12370 QualType resultType = proto->getCallResultType(Context);
Alp Toker314cc812014-01-25 16:55:45 +000012371 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
John McCall0009fcc2011-04-26 20:42:42 +000012372
12373 // Check that the object type isn't more qualified than the
12374 // member function we're calling.
12375 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
12376
12377 QualType objectType = op->getLHS()->getType();
12378 if (op->getOpcode() == BO_PtrMemI)
12379 objectType = objectType->castAs<PointerType>()->getPointeeType();
12380 Qualifiers objectQuals = objectType.getQualifiers();
12381
12382 Qualifiers difference = objectQuals - funcQuals;
12383 difference.removeObjCGCAttr();
12384 difference.removeAddressSpace();
12385 if (difference) {
12386 std::string qualsString = difference.getAsString();
12387 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
12388 << fnType.getUnqualifiedType()
12389 << qualsString
12390 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
12391 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +000012392
John McCall0009fcc2011-04-26 20:42:42 +000012393 CXXMemberCallExpr *call
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012394 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall0009fcc2011-04-26 20:42:42 +000012395 resultType, valueKind, RParenLoc);
12396
Alp Toker314cc812014-01-25 16:55:45 +000012397 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
Craig Topperc3ec1492014-05-26 06:22:03 +000012398 call, nullptr))
John McCall0009fcc2011-04-26 20:42:42 +000012399 return ExprError();
12400
Craig Topperc3ec1492014-05-26 06:22:03 +000012401 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
John McCall0009fcc2011-04-26 20:42:42 +000012402 return ExprError();
12403
Richard Trieu9be9c682013-06-22 02:30:38 +000012404 if (CheckOtherCall(call, proto))
12405 return ExprError();
12406
John McCall0009fcc2011-04-26 20:42:42 +000012407 return MaybeBindToTemporary(call);
12408 }
12409
David Majnemerced8bdf2015-02-25 17:36:15 +000012410 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
12411 return new (Context)
12412 CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc);
12413
John McCall4124c492011-10-17 18:40:02 +000012414 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012415 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000012416 return ExprError();
12417
John McCall10eae182009-11-30 22:42:35 +000012418 MemberExpr *MemExpr;
Craig Topperc3ec1492014-05-26 06:22:03 +000012419 CXXMethodDecl *Method = nullptr;
12420 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
12421 NestedNameSpecifier *Qualifier = nullptr;
John McCall10eae182009-11-30 22:42:35 +000012422 if (isa<MemberExpr>(NakedMemExpr)) {
12423 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +000012424 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +000012425 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +000012426 Qualifier = MemExpr->getQualifier();
John McCall4124c492011-10-17 18:40:02 +000012427 UnbridgedCasts.restore();
John McCall10eae182009-11-30 22:42:35 +000012428 } else {
12429 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +000012430 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012431
John McCall6e9f8f62009-12-03 04:06:58 +000012432 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +000012433 Expr::Classification ObjectClassification
12434 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
12435 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +000012436
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012437 // Add overload candidates
Richard Smith100b24a2014-04-17 01:52:14 +000012438 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
12439 OverloadCandidateSet::CSK_Normal);
Mike Stump11289f42009-09-09 15:08:12 +000012440
John McCall2d74de92009-12-01 22:10:20 +000012441 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000012442 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCall2d74de92009-12-01 22:10:20 +000012443 if (UnresExpr->hasExplicitTemplateArgs()) {
12444 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12445 TemplateArgs = &TemplateArgsBuffer;
12446 }
12447
John McCall10eae182009-11-30 22:42:35 +000012448 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
12449 E = UnresExpr->decls_end(); I != E; ++I) {
12450
John McCall6e9f8f62009-12-03 04:06:58 +000012451 NamedDecl *Func = *I;
12452 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
12453 if (isa<UsingShadowDecl>(Func))
12454 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
12455
Douglas Gregor02824322011-01-26 19:30:28 +000012456
Francois Pichet64225792011-01-18 05:04:39 +000012457 // Microsoft supports direct constructor calls.
David Blaikiebbafb8a2012-03-11 07:00:24 +000012458 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012459 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012460 Args, CandidateSet);
Francois Pichet64225792011-01-18 05:04:39 +000012461 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +000012462 // If explicit template arguments were provided, we can't call a
12463 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +000012464 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +000012465 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012466
John McCalla0296f72010-03-19 07:35:19 +000012467 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012468 ObjectClassification, Args, CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +000012469 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000012470 } else {
John McCall10eae182009-11-30 22:42:35 +000012471 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +000012472 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012473 ObjectType, ObjectClassification,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012474 Args, CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000012475 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000012476 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000012477 }
Mike Stump11289f42009-09-09 15:08:12 +000012478
John McCall10eae182009-11-30 22:42:35 +000012479 DeclarationName DeclName = UnresExpr->getMemberName();
12480
John McCall4124c492011-10-17 18:40:02 +000012481 UnbridgedCasts.restore();
12482
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012483 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012484 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +000012485 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012486 case OR_Success:
12487 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +000012488 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +000012489 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000012490 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
12491 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000012492 // If FoundDecl is different from Method (such as if one is a template
12493 // and the other a specialization), make sure DiagnoseUseOfDecl is
12494 // called on both.
12495 // FIXME: This would be more comprehensively addressed by modifying
12496 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
12497 // being used.
12498 if (Method != FoundDecl.getDecl() &&
12499 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
12500 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012501 break;
12502
12503 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +000012504 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012505 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000012506 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012507 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012508 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000012509 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012510
12511 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +000012512 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000012513 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012514 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012515 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000012516 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000012517
12518 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +000012519 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +000012520 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012521 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012522 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012523 << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012524 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000012525 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000012526 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012527 }
12528
John McCall16df1e52010-03-30 21:47:33 +000012529 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +000012530
John McCall2d74de92009-12-01 22:10:20 +000012531 // If overload resolution picked a static member, build a
12532 // non-member call based on that function.
12533 if (Method->isStatic()) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012534 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
12535 RParenLoc);
John McCall2d74de92009-12-01 22:10:20 +000012536 }
12537
John McCall10eae182009-11-30 22:42:35 +000012538 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012539 }
12540
Alp Toker314cc812014-01-25 16:55:45 +000012541 QualType ResultType = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000012542 ExprValueKind VK = Expr::getValueKindForType(ResultType);
12543 ResultType = ResultType.getNonLValueExprType(Context);
12544
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012545 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012546 CXXMemberCallExpr *TheCall =
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012547 new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall7decc9e2010-11-18 06:31:45 +000012548 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012549
Anders Carlssonc4859ba2009-10-10 00:06:20 +000012550 // Check for a valid return type.
Alp Toker314cc812014-01-25 16:55:45 +000012551 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +000012552 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +000012553 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012554
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012555 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +000012556 // We only need to do this if there was actually an overload; otherwise
12557 // it was done at lookup.
John Wiegley01296292011-04-08 18:41:53 +000012558 if (!Method->isStatic()) {
12559 ExprResult ObjectArg =
12560 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
12561 FoundDecl, Method);
12562 if (ObjectArg.isInvalid())
12563 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012564 MemExpr->setBase(ObjectArg.get());
John Wiegley01296292011-04-08 18:41:53 +000012565 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012566
12567 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +000012568 const FunctionProtoType *Proto =
12569 Method->getType()->getAs<FunctionProtoType>();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012570 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012571 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +000012572 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012573
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012574 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000012575
Richard Smith55ce3522012-06-25 20:30:08 +000012576 if (CheckFunctionCall(Method, TheCall, Proto))
John McCall2d74de92009-12-01 22:10:20 +000012577 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +000012578
George Burgess IVaea6ade2015-09-25 17:53:16 +000012579 // In the case the method to call was not selected by the overloading
12580 // resolution process, we still need to handle the enable_if attribute. Do
George Burgess IV0d546532016-11-10 21:47:12 +000012581 // that here, so it will not hide previous -- and more relevant -- errors.
George Burgess IVadd6ab52016-11-16 21:31:25 +000012582 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
George Burgess IVaea6ade2015-09-25 17:53:16 +000012583 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
George Burgess IVadd6ab52016-11-16 21:31:25 +000012584 Diag(MemE->getMemberLoc(),
George Burgess IVaea6ade2015-09-25 17:53:16 +000012585 diag::err_ovl_no_viable_member_function_in_call)
12586 << Method << Method->getSourceRange();
12587 Diag(Method->getLocation(),
12588 diag::note_ovl_candidate_disabled_by_enable_if_attr)
12589 << Attr->getCond()->getSourceRange() << Attr->getMessage();
12590 return ExprError();
12591 }
12592 }
12593
Anders Carlsson47061ee2011-05-06 14:25:31 +000012594 if ((isa<CXXConstructorDecl>(CurContext) ||
12595 isa<CXXDestructorDecl>(CurContext)) &&
12596 TheCall->getMethodDecl()->isPure()) {
12597 const CXXMethodDecl *MD = TheCall->getMethodDecl();
12598
Davide Italianoccb37382015-07-14 23:36:10 +000012599 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
12600 MemExpr->performsVirtualDispatch(getLangOpts())) {
12601 Diag(MemExpr->getLocStart(),
Anders Carlsson47061ee2011-05-06 14:25:31 +000012602 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
12603 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
12604 << MD->getParent()->getDeclName();
12605
12606 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Davide Italianoccb37382015-07-14 23:36:10 +000012607 if (getLangOpts().AppleKext)
12608 Diag(MemExpr->getLocStart(),
12609 diag::note_pure_qualified_call_kext)
12610 << MD->getParent()->getDeclName()
12611 << MD->getDeclName();
Chandler Carruth59259262011-06-27 08:31:58 +000012612 }
Anders Carlsson47061ee2011-05-06 14:25:31 +000012613 }
Nico Weber5a9259c2016-01-15 21:45:31 +000012614
12615 if (CXXDestructorDecl *DD =
12616 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
12617 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
Justin Lebard35f7062016-07-12 23:23:01 +000012618 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
Nico Weber5a9259c2016-01-15 21:45:31 +000012619 CheckVirtualDtorCall(DD, MemExpr->getLocStart(), /*IsDelete=*/false,
12620 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
12621 MemExpr->getMemberLoc());
12622 }
12623
John McCallb268a282010-08-23 23:25:46 +000012624 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012625}
12626
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012627/// BuildCallToObjectOfClassType - Build a call to an object of class
12628/// type (C++ [over.call.object]), which can end up invoking an
12629/// overloaded function call operator (@c operator()) or performing a
12630/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +000012631ExprResult
John Wiegley01296292011-04-08 18:41:53 +000012632Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregorb0846b02008-12-06 00:22:45 +000012633 SourceLocation LParenLoc,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012634 MultiExprArg Args,
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012635 SourceLocation RParenLoc) {
John McCall4124c492011-10-17 18:40:02 +000012636 if (checkPlaceholderForOverload(*this, Obj))
12637 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012638 ExprResult Object = Obj;
John McCall4124c492011-10-17 18:40:02 +000012639
12640 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012641 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000012642 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012643
Nico Weberb58e51c2014-11-19 05:21:39 +000012644 assert(Object.get()->getType()->isRecordType() &&
12645 "Requires object type argument");
John Wiegley01296292011-04-08 18:41:53 +000012646 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +000012647
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012648 // C++ [over.call.object]p1:
12649 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +000012650 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012651 // candidate functions includes at least the function call
12652 // operators of T. The function call operators of T are obtained by
12653 // ordinary lookup of the name operator() in the context of
12654 // (E).operator().
Richard Smith100b24a2014-04-17 01:52:14 +000012655 OverloadCandidateSet CandidateSet(LParenLoc,
12656 OverloadCandidateSet::CSK_Operator);
Douglas Gregor91f84212008-12-11 16:49:14 +000012657 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +000012658
John Wiegley01296292011-04-08 18:41:53 +000012659 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012660 diag::err_incomplete_object_call, Object.get()))
Douglas Gregorc473cbb2009-11-15 07:48:03 +000012661 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012662
John McCall27b18f82009-11-17 02:14:36 +000012663 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
12664 LookupQualifiedName(R, Record->getDecl());
12665 R.suppressDiagnostics();
12666
Douglas Gregorc473cbb2009-11-15 07:48:03 +000012667 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +000012668 Oper != OperEnd; ++Oper) {
John Wiegley01296292011-04-08 18:41:53 +000012669 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012670 Object.get()->Classify(Context),
12671 Args, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +000012672 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +000012673 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012674
Douglas Gregorab7897a2008-11-19 22:57:39 +000012675 // C++ [over.call.object]p2:
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012676 // In addition, for each (non-explicit in C++0x) conversion function
12677 // declared in T of the form
Douglas Gregorab7897a2008-11-19 22:57:39 +000012678 //
12679 // operator conversion-type-id () cv-qualifier;
12680 //
12681 // where cv-qualifier is the same cv-qualification as, or a
12682 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +000012683 // denotes the type "pointer to function of (P1,...,Pn) returning
12684 // R", or the type "reference to pointer to function of
12685 // (P1,...,Pn) returning R", or the type "reference to function
12686 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +000012687 // is also considered as a candidate function. Similarly,
12688 // surrogate call functions are added to the set of candidate
12689 // functions for each conversion function declared in an
12690 // accessible base class provided the function is not hidden
12691 // within T by another intervening declaration.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +000012692 const auto &Conversions =
12693 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
12694 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +000012695 NamedDecl *D = *I;
12696 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
12697 if (isa<UsingShadowDecl>(D))
12698 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012699
Douglas Gregor74ba25c2009-10-21 06:18:39 +000012700 // Skip over templated conversion functions; they aren't
12701 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +000012702 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +000012703 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +000012704
John McCall6e9f8f62009-12-03 04:06:58 +000012705 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012706 if (!Conv->isExplicit()) {
12707 // Strip the reference type (if any) and then the pointer type (if
12708 // any) to get down to what might be a function type.
12709 QualType ConvType = Conv->getConversionType().getNonReferenceType();
12710 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
12711 ConvType = ConvPtrType->getPointeeType();
John McCalld14a8642009-11-21 08:51:07 +000012712
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012713 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
12714 {
12715 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012716 Object.get(), Args, CandidateSet);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012717 }
12718 }
Douglas Gregorab7897a2008-11-19 22:57:39 +000012719 }
Mike Stump11289f42009-09-09 15:08:12 +000012720
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012721 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12722
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012723 // Perform overload resolution.
12724 OverloadCandidateSet::iterator Best;
John Wiegley01296292011-04-08 18:41:53 +000012725 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall5c32be02010-08-24 20:38:10 +000012726 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012727 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +000012728 // Overload resolution succeeded; we'll build the appropriate call
12729 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012730 break;
12731
12732 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +000012733 if (CandidateSet.empty())
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012734 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley01296292011-04-08 18:41:53 +000012735 << Object.get()->getType() << /*call*/ 1
12736 << Object.get()->getSourceRange();
John McCall02374852010-01-07 02:04:15 +000012737 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012738 Diag(Object.get()->getLocStart(),
John McCall02374852010-01-07 02:04:15 +000012739 diag::err_ovl_no_viable_object_call)
John Wiegley01296292011-04-08 18:41:53 +000012740 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012741 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012742 break;
12743
12744 case OR_Ambiguous:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012745 Diag(Object.get()->getLocStart(),
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012746 diag::err_ovl_ambiguous_object_call)
John Wiegley01296292011-04-08 18:41:53 +000012747 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012748 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012749 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000012750
12751 case OR_Deleted:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012752 Diag(Object.get()->getLocStart(),
Douglas Gregor171c45a2009-02-18 21:56:37 +000012753 diag::err_ovl_deleted_object_call)
12754 << Best->Function->isDeleted()
John Wiegley01296292011-04-08 18:41:53 +000012755 << Object.get()->getType()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012756 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley01296292011-04-08 18:41:53 +000012757 << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012758 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000012759 break;
Mike Stump11289f42009-09-09 15:08:12 +000012760 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012761
Douglas Gregorb412e172010-07-25 18:17:45 +000012762 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012763 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012764
John McCall4124c492011-10-17 18:40:02 +000012765 UnbridgedCasts.restore();
12766
Craig Topperc3ec1492014-05-26 06:22:03 +000012767 if (Best->Function == nullptr) {
Douglas Gregorab7897a2008-11-19 22:57:39 +000012768 // Since there is no function declaration, this is one of the
12769 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +000012770 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +000012771 = cast<CXXConversionDecl>(
12772 Best->Conversions[0].UserDefined.ConversionFunction);
12773
Craig Topperc3ec1492014-05-26 06:22:03 +000012774 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
12775 Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000012776 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
12777 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000012778 assert(Conv == Best->FoundDecl.getDecl() &&
12779 "Found Decl & conversion-to-functionptr should be same, right?!");
Douglas Gregorab7897a2008-11-19 22:57:39 +000012780 // We selected one of the surrogate functions that converts the
12781 // object parameter to a function pointer. Perform the conversion
12782 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012783
Fariborz Jahanian774cf792009-09-28 18:35:46 +000012784 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +000012785 // and then call it.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012786 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
12787 Conv, HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +000012788 if (Call.isInvalid())
12789 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +000012790 // Record usage of conversion in an implicit cast.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012791 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
12792 CK_UserDefinedConversion, Call.get(),
12793 nullptr, VK_RValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012794
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012795 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +000012796 }
12797
Craig Topperc3ec1492014-05-26 06:22:03 +000012798 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
John McCall49ec2e62010-01-28 01:54:34 +000012799
Douglas Gregorab7897a2008-11-19 22:57:39 +000012800 // We found an overloaded operator(). Build a CXXOperatorCallExpr
12801 // that calls this method, using Object for the implicit object
12802 // parameter and passing along the remaining arguments.
12803 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Nico Weber1fefe412012-11-09 06:06:14 +000012804
12805 // An error diagnostic has already been printed when parsing the declaration.
Nico Weber9512d3f2012-11-09 08:38:04 +000012806 if (Method->isInvalidDecl())
Nico Weber1fefe412012-11-09 06:06:14 +000012807 return ExprError();
12808
Chandler Carruth8e543b32010-12-12 08:17:55 +000012809 const FunctionProtoType *Proto =
12810 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012811
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012812 unsigned NumParams = Proto->getNumParams();
Mike Stump11289f42009-09-09 15:08:12 +000012813
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012814 DeclarationNameInfo OpLocInfo(
12815 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
12816 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Nick Lewycky134af912013-02-07 05:08:22 +000012817 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012818 HadMultipleCandidates,
12819 OpLocInfo.getLoc(),
12820 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000012821 if (NewFn.isInvalid())
12822 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012823
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012824 // Build the full argument list for the method call (the implicit object
12825 // parameter is placed at the beginning of the list).
George Burgess IV215f6e72016-12-13 19:22:56 +000012826 SmallVector<Expr *, 8> MethodArgs(Args.size() + 1);
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012827 MethodArgs[0] = Object.get();
George Burgess IV215f6e72016-12-13 19:22:56 +000012828 std::copy(Args.begin(), Args.end(), MethodArgs.begin() + 1);
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012829
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012830 // Once we've built TheCall, all of the expressions are properly
12831 // owned.
Alp Toker314cc812014-01-25 16:55:45 +000012832 QualType ResultTy = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000012833 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12834 ResultTy = ResultTy.getNonLValueExprType(Context);
12835
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012836 CXXOperatorCallExpr *TheCall = new (Context)
George Burgess IV215f6e72016-12-13 19:22:56 +000012837 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(), MethodArgs, ResultTy,
12838 VK, RParenLoc, false);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012839
Alp Toker314cc812014-01-25 16:55:45 +000012840 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
Anders Carlsson3d5829c2009-10-13 21:49:31 +000012841 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012842
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012843 // We may have default arguments. If so, we need to allocate more
12844 // slots in the call for them.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012845 if (Args.size() < NumParams)
12846 TheCall->setNumArgs(Context, NumParams + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012847
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000012848 bool IsError = false;
12849
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012850 // Initialize the implicit object parameter.
John Wiegley01296292011-04-08 18:41:53 +000012851 ExprResult ObjRes =
Craig Topperc3ec1492014-05-26 06:22:03 +000012852 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012853 Best->FoundDecl, Method);
12854 if (ObjRes.isInvalid())
12855 IsError = true;
12856 else
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012857 Object = ObjRes;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012858 TheCall->setArg(0, Object.get());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000012859
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012860 // Check the argument types.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012861 for (unsigned i = 0; i != NumParams; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012862 Expr *Arg;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012863 if (i < Args.size()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012864 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +000012865
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012866 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012867
John McCalldadc5752010-08-24 06:29:42 +000012868 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012869 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000012870 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012871 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +000012872 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012873
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012874 IsError |= InputInit.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012875 Arg = InputInit.getAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012876 } else {
John McCalldadc5752010-08-24 06:29:42 +000012877 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +000012878 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
12879 if (DefArg.isInvalid()) {
12880 IsError = true;
12881 break;
12882 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012883
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012884 Arg = DefArg.getAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012885 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012886
12887 TheCall->setArg(i + 1, Arg);
12888 }
12889
12890 // If this is a variadic call, handle args passed through "...".
12891 if (Proto->isVariadic()) {
12892 // Promote the arguments (C99 6.5.2.2p7).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012893 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
Craig Topperc3ec1492014-05-26 06:22:03 +000012894 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
12895 nullptr);
John Wiegley01296292011-04-08 18:41:53 +000012896 IsError |= Arg.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012897 TheCall->setArg(i + 1, Arg.get());
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012898 }
12899 }
12900
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000012901 if (IsError) return true;
12902
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012903 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000012904
Richard Smith55ce3522012-06-25 20:30:08 +000012905 if (CheckFunctionCall(Method, TheCall, Proto))
Anders Carlssonbc4c1072009-08-16 01:56:34 +000012906 return true;
12907
John McCalle172be52010-08-24 06:09:16 +000012908 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012909}
12910
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012911/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +000012912/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012913/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +000012914ExprResult
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000012915Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
12916 bool *NoArrowOperatorFound) {
Chandler Carruth8e543b32010-12-12 08:17:55 +000012917 assert(Base->getType()->isRecordType() &&
12918 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +000012919
John McCall4124c492011-10-17 18:40:02 +000012920 if (checkPlaceholderForOverload(*this, Base))
12921 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012922
John McCallbc077cf2010-02-08 23:07:23 +000012923 SourceLocation Loc = Base->getExprLoc();
12924
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012925 // C++ [over.ref]p1:
12926 //
12927 // [...] An expression x->m is interpreted as (x.operator->())->m
12928 // for a class object x of type T if T::operator->() exists and if
12929 // the operator is selected as the best match function by the
12930 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +000012931 DeclarationName OpName =
12932 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
Richard Smith100b24a2014-04-17 01:52:14 +000012933 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
Ted Kremenekc23c7e62009-07-29 21:53:49 +000012934 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +000012935
John McCallbc077cf2010-02-08 23:07:23 +000012936 if (RequireCompleteType(Loc, Base->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012937 diag::err_typecheck_incomplete_tag, Base))
Eli Friedman132e70b2009-11-18 01:28:03 +000012938 return ExprError();
12939
John McCall27b18f82009-11-17 02:14:36 +000012940 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
12941 LookupQualifiedName(R, BaseRecord->getDecl());
12942 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +000012943
12944 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +000012945 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +000012946 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +000012947 None, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +000012948 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012949
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012950 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12951
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012952 // Perform overload resolution.
12953 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012954 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012955 case OR_Success:
12956 // Overload resolution succeeded; we'll build the call below.
12957 break;
12958
12959 case OR_No_Viable_Function:
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012960 if (CandidateSet.empty()) {
12961 QualType BaseType = Base->getType();
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000012962 if (NoArrowOperatorFound) {
12963 // Report this specific error to the caller instead of emitting a
12964 // diagnostic, as requested.
12965 *NoArrowOperatorFound = true;
12966 return ExprError();
12967 }
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000012968 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
12969 << BaseType << Base->getSourceRange();
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012970 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000012971 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012972 << FixItHint::CreateReplacement(OpLoc, ".");
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012973 }
12974 } else
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012975 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +000012976 << "operator->" << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012977 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012978 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012979
12980 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000012981 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
12982 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012983 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012984 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000012985
12986 case OR_Deleted:
12987 Diag(OpLoc, diag::err_ovl_deleted_oper)
12988 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012989 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012990 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012991 << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012992 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012993 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012994 }
12995
Craig Topperc3ec1492014-05-26 06:22:03 +000012996 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
John McCalla0296f72010-03-19 07:35:19 +000012997
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012998 // Convert the object parameter.
12999 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000013000 ExprResult BaseResult =
Craig Topperc3ec1492014-05-26 06:22:03 +000013001 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000013002 Best->FoundDecl, Method);
13003 if (BaseResult.isInvalid())
Douglas Gregord8061562009-08-06 03:17:00 +000013004 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013005 Base = BaseResult.get();
Douglas Gregor9ecea262008-11-21 03:04:22 +000013006
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013007 // Build the operator call.
Nick Lewycky134af912013-02-07 05:08:22 +000013008 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000013009 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000013010 if (FnExpr.isInvalid())
13011 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013012
Alp Toker314cc812014-01-25 16:55:45 +000013013 QualType ResultTy = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000013014 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13015 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +000013016 CXXOperatorCallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013017 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
Lang Hames5de91cc2012-10-02 04:45:10 +000013018 Base, ResultTy, VK, OpLoc, false);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000013019
Alp Toker314cc812014-01-25 16:55:45 +000013020 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000013021 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +000013022
13023 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013024}
13025
Richard Smithbcc22fc2012-03-09 08:00:36 +000013026/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
13027/// a literal operator described by the provided lookup results.
13028ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
13029 DeclarationNameInfo &SuffixInfo,
13030 ArrayRef<Expr*> Args,
13031 SourceLocation LitEndLoc,
13032 TemplateArgumentListInfo *TemplateArgs) {
13033 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smithc67fdd42012-03-07 08:35:16 +000013034
Richard Smith100b24a2014-04-17 01:52:14 +000013035 OverloadCandidateSet CandidateSet(UDSuffixLoc,
13036 OverloadCandidateSet::CSK_Normal);
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000013037 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
13038 /*SuppressUserConversions=*/true);
Richard Smithc67fdd42012-03-07 08:35:16 +000013039
Richard Smithbcc22fc2012-03-09 08:00:36 +000013040 bool HadMultipleCandidates = (CandidateSet.size() > 1);
13041
Richard Smithbcc22fc2012-03-09 08:00:36 +000013042 // Perform overload resolution. This will usually be trivial, but might need
13043 // to perform substitutions for a literal operator template.
13044 OverloadCandidateSet::iterator Best;
13045 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
13046 case OR_Success:
13047 case OR_Deleted:
13048 break;
13049
13050 case OR_No_Viable_Function:
13051 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
13052 << R.getLookupName();
13053 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13054 return ExprError();
13055
13056 case OR_Ambiguous:
13057 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
13058 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
13059 return ExprError();
Richard Smithc67fdd42012-03-07 08:35:16 +000013060 }
13061
Richard Smithbcc22fc2012-03-09 08:00:36 +000013062 FunctionDecl *FD = Best->Function;
Nick Lewycky134af912013-02-07 05:08:22 +000013063 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
13064 HadMultipleCandidates,
Richard Smithbcc22fc2012-03-09 08:00:36 +000013065 SuffixInfo.getLoc(),
13066 SuffixInfo.getInfo());
13067 if (Fn.isInvalid())
13068 return true;
Richard Smithc67fdd42012-03-07 08:35:16 +000013069
13070 // Check the argument types. This should almost always be a no-op, except
13071 // that array-to-pointer decay is applied to string literals.
Richard Smithc67fdd42012-03-07 08:35:16 +000013072 Expr *ConvArgs[2];
Richard Smithe54c3072013-05-05 15:51:06 +000013073 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Richard Smithc67fdd42012-03-07 08:35:16 +000013074 ExprResult InputInit = PerformCopyInitialization(
13075 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
13076 SourceLocation(), Args[ArgIdx]);
13077 if (InputInit.isInvalid())
13078 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013079 ConvArgs[ArgIdx] = InputInit.get();
Richard Smithc67fdd42012-03-07 08:35:16 +000013080 }
13081
Alp Toker314cc812014-01-25 16:55:45 +000013082 QualType ResultTy = FD->getReturnType();
Richard Smithc67fdd42012-03-07 08:35:16 +000013083 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13084 ResultTy = ResultTy.getNonLValueExprType(Context);
13085
Richard Smithc67fdd42012-03-07 08:35:16 +000013086 UserDefinedLiteral *UDL =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013087 new (Context) UserDefinedLiteral(Context, Fn.get(),
Benjamin Kramerc215e762012-08-24 11:54:20 +000013088 llvm::makeArrayRef(ConvArgs, Args.size()),
Richard Smithc67fdd42012-03-07 08:35:16 +000013089 ResultTy, VK, LitEndLoc, UDSuffixLoc);
13090
Alp Toker314cc812014-01-25 16:55:45 +000013091 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
Richard Smithc67fdd42012-03-07 08:35:16 +000013092 return ExprError();
13093
Craig Topperc3ec1492014-05-26 06:22:03 +000013094 if (CheckFunctionCall(FD, UDL, nullptr))
Richard Smithc67fdd42012-03-07 08:35:16 +000013095 return ExprError();
13096
13097 return MaybeBindToTemporary(UDL);
13098}
13099
Sam Panzer0f384432012-08-21 00:52:01 +000013100/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
13101/// given LookupResult is non-empty, it is assumed to describe a member which
13102/// will be invoked. Otherwise, the function will be found via argument
13103/// dependent lookup.
13104/// CallExpr is set to a valid expression and FRS_Success returned on success,
13105/// otherwise CallExpr is set to ExprError() and some non-success value
13106/// is returned.
13107Sema::ForRangeStatus
Richard Smith9f690bd2015-10-27 06:02:45 +000013108Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
13109 SourceLocation RangeLoc,
Sam Panzer0f384432012-08-21 00:52:01 +000013110 const DeclarationNameInfo &NameInfo,
13111 LookupResult &MemberLookup,
13112 OverloadCandidateSet *CandidateSet,
13113 Expr *Range, ExprResult *CallExpr) {
Richard Smith9f690bd2015-10-27 06:02:45 +000013114 Scope *S = nullptr;
13115
Sam Panzer0f384432012-08-21 00:52:01 +000013116 CandidateSet->clear();
13117 if (!MemberLookup.empty()) {
13118 ExprResult MemberRef =
13119 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
13120 /*IsPtr=*/false, CXXScopeSpec(),
13121 /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +000013122 /*FirstQualifierInScope=*/nullptr,
Sam Panzer0f384432012-08-21 00:52:01 +000013123 MemberLookup,
Aaron Ballman6924dcd2015-09-01 14:49:24 +000013124 /*TemplateArgs=*/nullptr, S);
Sam Panzer0f384432012-08-21 00:52:01 +000013125 if (MemberRef.isInvalid()) {
13126 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000013127 return FRS_DiagnosticIssued;
13128 }
Craig Topperc3ec1492014-05-26 06:22:03 +000013129 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
Sam Panzer0f384432012-08-21 00:52:01 +000013130 if (CallExpr->isInvalid()) {
13131 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000013132 return FRS_DiagnosticIssued;
13133 }
13134 } else {
13135 UnresolvedSet<0> FoundNames;
Sam Panzer0f384432012-08-21 00:52:01 +000013136 UnresolvedLookupExpr *Fn =
Craig Topperc3ec1492014-05-26 06:22:03 +000013137 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
Sam Panzer0f384432012-08-21 00:52:01 +000013138 NestedNameSpecifierLoc(), NameInfo,
13139 /*NeedsADL=*/true, /*Overloaded=*/false,
Richard Smithb6626742012-10-18 17:56:02 +000013140 FoundNames.begin(), FoundNames.end());
Sam Panzer0f384432012-08-21 00:52:01 +000013141
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000013142 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
Sam Panzer0f384432012-08-21 00:52:01 +000013143 CandidateSet, CallExpr);
13144 if (CandidateSet->empty() || CandidateSetError) {
13145 *CallExpr = ExprError();
13146 return FRS_NoViableFunction;
13147 }
13148 OverloadCandidateSet::iterator Best;
13149 OverloadingResult OverloadResult =
13150 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
13151
13152 if (OverloadResult == OR_No_Viable_Function) {
13153 *CallExpr = ExprError();
13154 return FRS_NoViableFunction;
13155 }
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000013156 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
Craig Topperc3ec1492014-05-26 06:22:03 +000013157 Loc, nullptr, CandidateSet, &Best,
Sam Panzer0f384432012-08-21 00:52:01 +000013158 OverloadResult,
13159 /*AllowTypoCorrection=*/false);
13160 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
13161 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000013162 return FRS_DiagnosticIssued;
13163 }
13164 }
13165 return FRS_Success;
13166}
13167
13168
Douglas Gregorcd695e52008-11-10 20:40:00 +000013169/// FixOverloadedFunctionReference - E is an expression that refers to
13170/// a C++ overloaded function (possibly with some parentheses and
13171/// perhaps a '&' around it). We have resolved the overloaded function
13172/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +000013173/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +000013174Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +000013175 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +000013176 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000013177 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
13178 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000013179 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000013180 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013181
Douglas Gregor51c538b2009-11-20 19:42:02 +000013182 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013183 }
13184
Douglas Gregor51c538b2009-11-20 19:42:02 +000013185 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000013186 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
13187 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013188 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +000013189 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +000013190 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +000013191 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +000013192 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000013193 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013194
13195 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +000013196 ICE->getCastKind(),
Craig Topperc3ec1492014-05-26 06:22:03 +000013197 SubExpr, nullptr,
John McCall2536c6d2010-08-25 10:28:54 +000013198 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013199 }
13200
Aaron Ballmanff7bd8b2016-09-02 13:45:40 +000013201 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
13202 if (!GSE->isResultDependent()) {
13203 Expr *SubExpr =
13204 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
13205 if (SubExpr == GSE->getResultExpr())
13206 return GSE;
13207
13208 // Replace the resulting type information before rebuilding the generic
13209 // selection expression.
Aaron Ballman8b871d92016-09-02 18:31:31 +000013210 ArrayRef<Expr *> A = GSE->getAssocExprs();
13211 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
Aaron Ballmanff7bd8b2016-09-02 13:45:40 +000013212 unsigned ResultIdx = GSE->getResultIndex();
13213 AssocExprs[ResultIdx] = SubExpr;
13214
13215 return new (Context) GenericSelectionExpr(
13216 Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
13217 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
13218 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
13219 ResultIdx);
13220 }
13221 // Rather than fall through to the unreachable, return the original generic
13222 // selection expression.
13223 return GSE;
13224 }
13225
Douglas Gregor51c538b2009-11-20 19:42:02 +000013226 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +000013227 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +000013228 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +000013229 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13230 if (Method->isStatic()) {
13231 // Do nothing: static member functions aren't any different
13232 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +000013233 } else {
Alp Toker028ed912013-12-06 17:56:43 +000013234 // Fix the subexpression, which really has to be an
John McCalle66edc12009-11-24 19:00:30 +000013235 // UnresolvedLookupExpr holding an overloaded member function
13236 // or template.
John McCall16df1e52010-03-30 21:47:33 +000013237 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13238 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +000013239 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000013240 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +000013241
John McCalld14a8642009-11-21 08:51:07 +000013242 assert(isa<DeclRefExpr>(SubExpr)
13243 && "fixed to something other than a decl ref");
13244 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
13245 && "fixed to a member ref with no nested name qualifier");
13246
13247 // We have taken the address of a pointer to member
13248 // function. Perform the computation here so that we get the
13249 // appropriate pointer to member type.
13250 QualType ClassType
13251 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
13252 QualType MemPtrType
13253 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
David Majnemer02d57cc2016-06-30 03:02:03 +000013254 // Under the MS ABI, lock down the inheritance model now.
13255 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13256 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
John McCalld14a8642009-11-21 08:51:07 +000013257
John McCall7decc9e2010-11-18 06:31:45 +000013258 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
13259 VK_RValue, OK_Ordinary,
13260 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +000013261 }
13262 }
John McCall16df1e52010-03-30 21:47:33 +000013263 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13264 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000013265 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000013266 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013267
John McCalle3027922010-08-25 11:45:40 +000013268 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +000013269 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +000013270 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +000013271 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013272 }
John McCalld14a8642009-11-21 08:51:07 +000013273
Richard Smith84a0b6d2016-10-18 23:39:12 +000013274 // C++ [except.spec]p17:
13275 // An exception-specification is considered to be needed when:
13276 // - in an expression the function is the unique lookup result or the
13277 // selected member of a set of overloaded functions
13278 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13279 ResolveExceptionSpec(E->getExprLoc(), FPT);
13280
John McCalld14a8642009-11-21 08:51:07 +000013281 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +000013282 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000013283 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCalle66edc12009-11-24 19:00:30 +000013284 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +000013285 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
13286 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +000013287 }
13288
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013289 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13290 ULE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000013291 ULE->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013292 Fn,
John McCall113bee02012-03-10 09:33:50 +000013293 /*enclosing*/ false, // FIXME?
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013294 ULE->getNameLoc(),
13295 Fn->getType(),
13296 VK_LValue,
13297 Found.getDecl(),
13298 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000013299 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013300 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
13301 return DRE;
John McCalld14a8642009-11-21 08:51:07 +000013302 }
13303
John McCall10eae182009-11-30 22:42:35 +000013304 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +000013305 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000013306 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCall2d74de92009-12-01 22:10:20 +000013307 if (MemExpr->hasExplicitTemplateArgs()) {
13308 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
13309 TemplateArgs = &TemplateArgsBuffer;
13310 }
John McCall6b51f282009-11-23 01:53:49 +000013311
John McCall2d74de92009-12-01 22:10:20 +000013312 Expr *Base;
13313
John McCall7decc9e2010-11-18 06:31:45 +000013314 // If we're filling in a static method where we used to have an
13315 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +000013316 if (MemExpr->isImplicitAccess()) {
13317 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013318 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13319 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000013320 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013321 Fn,
John McCall113bee02012-03-10 09:33:50 +000013322 /*enclosing*/ false,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013323 MemExpr->getMemberLoc(),
13324 Fn->getType(),
13325 VK_LValue,
13326 Found.getDecl(),
13327 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000013328 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013329 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
13330 return DRE;
Douglas Gregorb15af892010-01-07 23:12:05 +000013331 } else {
13332 SourceLocation Loc = MemExpr->getMemberLoc();
13333 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +000013334 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman73a04092012-01-07 04:59:52 +000013335 CheckCXXThisCapture(Loc);
Douglas Gregorb15af892010-01-07 23:12:05 +000013336 Base = new (Context) CXXThisExpr(Loc,
13337 MemExpr->getBaseType(),
13338 /*isImplicit=*/true);
13339 }
John McCall2d74de92009-12-01 22:10:20 +000013340 } else
John McCallc3007a22010-10-26 07:05:15 +000013341 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +000013342
John McCall4adb38c2011-04-27 00:36:17 +000013343 ExprValueKind valueKind;
13344 QualType type;
13345 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13346 valueKind = VK_LValue;
13347 type = Fn->getType();
13348 } else {
13349 valueKind = VK_RValue;
Yunzhong Gaoeba323a2015-05-01 02:04:32 +000013350 type = Context.BoundMemberTy;
13351 }
13352
13353 MemberExpr *ME = MemberExpr::Create(
13354 Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
13355 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
13356 MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
13357 OK_Ordinary);
13358 ME->setHadMultipleCandidates(true);
13359 MarkMemberReferenced(ME);
13360 return ME;
Douglas Gregor51c538b2009-11-20 19:42:02 +000013361 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013362
John McCallc3007a22010-10-26 07:05:15 +000013363 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregorcd695e52008-11-10 20:40:00 +000013364}
13365
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013366ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +000013367 DeclAccessPair Found,
13368 FunctionDecl *Fn) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000013369 return FixOverloadedFunctionReference(E.get(), Found, Fn);
Douglas Gregor3e1e5272009-12-09 23:02:17 +000013370}