blob: fb378b86af75a3aaa6afbe6460f95b47b8447971 [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;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001803 } else {
1804 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001805 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001806 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001807 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001808
Richard Smitheb7ef2e2016-10-20 21:53:09 +00001809 // The third conversion can be a function pointer conversion or a
1810 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
John McCall31168b02011-06-15 23:02:42 +00001811 bool ObjCLifetimeConversion;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00001812 if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1813 // Function pointer conversions (removing 'noexcept') including removal of
1814 // 'noreturn' (Clang extension).
1815 SCS.Third = ICK_Function_Conversion;
1816 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1817 ObjCLifetimeConversion)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001818 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001819 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001820 FromType = ToType;
1821 } else {
1822 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001823 SCS.Third = ICK_Identity;
Richard Smith9c37e662016-10-20 17:57:33 +00001824 }
Richard Smitheb7ef2e2016-10-20 21:53:09 +00001825
1826 // C++ [over.best.ics]p6:
1827 // [...] Any difference in top-level cv-qualification is
1828 // subsumed by the initialization itself and does not constitute
1829 // a conversion. [...]
1830 QualType CanonFrom = S.Context.getCanonicalType(FromType);
1831 QualType CanonTo = S.Context.getCanonicalType(ToType);
1832 if (CanonFrom.getLocalUnqualifiedType()
1833 == CanonTo.getLocalUnqualifiedType() &&
1834 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1835 FromType = ToType;
1836 CanonFrom = CanonTo;
1837 }
1838
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001839 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001840
George Burgess IV45461812015-10-11 20:13:20 +00001841 if (CanonFrom == CanonTo)
1842 return true;
1843
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001844 // If we have not converted the argument type to the parameter type,
George Burgess IV45461812015-10-11 20:13:20 +00001845 // this is a bad conversion sequence, unless we're resolving an overload in C.
1846 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001847 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001848
George Burgess IV45461812015-10-11 20:13:20 +00001849 ExprResult ER = ExprResult{From};
George Burgess IV2099b542016-09-02 22:59:57 +00001850 Sema::AssignConvertType Conv =
1851 S.CheckSingleAssignmentConstraints(ToType, ER,
1852 /*Diagnose=*/false,
1853 /*DiagnoseCFAudited=*/false,
1854 /*ConvertRHS=*/false);
George Burgess IV6098fd12016-09-03 00:28:25 +00001855 ImplicitConversionKind SecondConv;
George Burgess IV2099b542016-09-02 22:59:57 +00001856 switch (Conv) {
1857 case Sema::Compatible:
George Burgess IV6098fd12016-09-03 00:28:25 +00001858 SecondConv = ICK_C_Only_Conversion;
George Burgess IV2099b542016-09-02 22:59:57 +00001859 break;
1860 // For our purposes, discarding qualifiers is just as bad as using an
1861 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
1862 // qualifiers, as well.
1863 case Sema::CompatiblePointerDiscardsQualifiers:
1864 case Sema::IncompatiblePointer:
1865 case Sema::IncompatiblePointerSign:
George Burgess IV6098fd12016-09-03 00:28:25 +00001866 SecondConv = ICK_Incompatible_Pointer_Conversion;
George Burgess IV2099b542016-09-02 22:59:57 +00001867 break;
1868 default:
George Burgess IV45461812015-10-11 20:13:20 +00001869 return false;
George Burgess IV2099b542016-09-02 22:59:57 +00001870 }
George Burgess IV45461812015-10-11 20:13:20 +00001871
George Burgess IV6098fd12016-09-03 00:28:25 +00001872 // First can only be an lvalue conversion, so we pretend that this was the
1873 // second conversion. First should already be valid from earlier in the
1874 // function.
1875 SCS.Second = SecondConv;
1876 SCS.setToType(1, ToType);
1877
1878 // Third is Identity, because Second should rank us worse than any other
1879 // conversion. This could also be ICK_Qualification, but it's simpler to just
1880 // lump everything in with the second conversion, and we don't gain anything
1881 // from making this ICK_Qualification.
1882 SCS.Third = ICK_Identity;
1883 SCS.setToType(2, ToType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001884 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001885}
George Burgess IV2099b542016-09-02 22:59:57 +00001886
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001887static bool
1888IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1889 QualType &ToType,
1890 bool InOverloadResolution,
1891 StandardConversionSequence &SCS,
1892 bool CStyle) {
1893
1894 const RecordType *UT = ToType->getAsUnionType();
1895 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1896 return false;
1897 // The field to initialize within the transparent union.
1898 RecordDecl *UD = UT->getDecl();
1899 // It's compatible if the expression matches any of the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001900 for (const auto *it : UD->fields()) {
John McCall31168b02011-06-15 23:02:42 +00001901 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1902 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001903 ToType = it->getType();
1904 return true;
1905 }
1906 }
1907 return false;
1908}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001909
1910/// IsIntegralPromotion - Determines whether the conversion from the
1911/// expression From (whose potentially-adjusted type is FromType) to
1912/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1913/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001914bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001915 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001916 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001917 if (!To) {
1918 return false;
1919 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001920
1921 // An rvalue of type char, signed char, unsigned char, short int, or
1922 // unsigned short int can be converted to an rvalue of type int if
1923 // int can represent all the values of the source type; otherwise,
1924 // the source rvalue can be converted to an rvalue of type unsigned
1925 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001926 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1927 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001928 if (// We can promote any signed, promotable integer type to an int
1929 (FromType->isSignedIntegerType() ||
1930 // We can promote any unsigned integer type whose size is
1931 // less than int to an int.
Benjamin Kramer5ff67472016-04-11 08:26:13 +00001932 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001933 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001934 }
1935
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001936 return To->getKind() == BuiltinType::UInt;
1937 }
1938
Richard Smithb9c5a602012-09-13 21:18:54 +00001939 // C++11 [conv.prom]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001940 // A prvalue of an unscoped enumeration type whose underlying type is not
1941 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1942 // following types that can represent all the values of the enumeration
1943 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1944 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001945 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001946 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001947 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001948 // with lowest integer conversion rank (4.13) greater than the rank of long
1949 // long in which all the values of the enumeration can be represented. If
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001950 // there are two such extended types, the signed one is chosen.
Richard Smithb9c5a602012-09-13 21:18:54 +00001951 // C++11 [conv.prom]p4:
1952 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1953 // can be converted to a prvalue of its underlying type. Moreover, if
1954 // integral promotion can be applied to its underlying type, a prvalue of an
1955 // unscoped enumeration type whose underlying type is fixed can also be
1956 // converted to a prvalue of the promoted underlying type.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001957 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1958 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1959 // provided for a scoped enumeration.
1960 if (FromEnumType->getDecl()->isScoped())
1961 return false;
1962
Richard Smithb9c5a602012-09-13 21:18:54 +00001963 // We can perform an integral promotion to the underlying type of the enum,
Richard Smithac8c1752015-03-28 00:31:40 +00001964 // even if that's not the promoted type. Note that the check for promoting
1965 // the underlying type is based on the type alone, and does not consider
1966 // the bitfield-ness of the actual source expression.
Richard Smithb9c5a602012-09-13 21:18:54 +00001967 if (FromEnumType->getDecl()->isFixed()) {
1968 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1969 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
Richard Smithac8c1752015-03-28 00:31:40 +00001970 IsIntegralPromotion(nullptr, Underlying, ToType);
Richard Smithb9c5a602012-09-13 21:18:54 +00001971 }
1972
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001973 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001974 if (ToType->isIntegerType() &&
Richard Smithdb0ac552015-12-18 22:40:25 +00001975 isCompleteType(From->getLocStart(), FromType))
Richard Smith88f4bba2015-03-26 00:16:07 +00001976 return Context.hasSameUnqualifiedType(
1977 ToType, FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001978 }
John McCall56774992009-12-09 09:09:27 +00001979
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001980 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001981 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1982 // to an rvalue a prvalue of the first of the following types that can
1983 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001984 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001985 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001986 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001987 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001988 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001989 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001990 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001991 // Determine whether the type we're converting from is signed or
1992 // unsigned.
David Majnemerfa01a582011-07-22 21:09:04 +00001993 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001994 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001995
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001996 // The types we'll try to promote to, in the appropriate
1997 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001998 QualType PromoteTypes[6] = {
1999 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00002000 Context.LongTy, Context.UnsignedLongTy ,
2001 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002002 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00002003 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002004 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2005 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00002006 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002007 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2008 // We found the type that we can promote to. If this is the
2009 // type we wanted, we have a promotion. Otherwise, no
2010 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002011 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002012 }
2013 }
2014 }
2015
2016 // An rvalue for an integral bit-field (9.6) can be converted to an
2017 // rvalue of type int if int can represent all the values of the
2018 // bit-field; otherwise, it can be converted to unsigned int if
2019 // unsigned int can represent all the values of the bit-field. If
2020 // the bit-field is larger yet, no integral promotion applies to
2021 // it. If the bit-field has an enumerated type, it is treated as any
2022 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00002023 // FIXME: We should delay checking of bit-fields until we actually perform the
2024 // conversion.
Richard Smith88f4bba2015-03-26 00:16:07 +00002025 if (From) {
John McCalld25db7e2013-05-06 21:39:12 +00002026 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
Richard Smith88f4bba2015-03-26 00:16:07 +00002027 llvm::APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00002028 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00002029 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
Richard Smith88f4bba2015-03-26 00:16:07 +00002030 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
Douglas Gregor71235ec2009-05-02 02:18:30 +00002031 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00002032
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00002033 // Are we promoting to an int from a bitfield that fits in an int?
2034 if (BitWidth < ToSize ||
2035 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
2036 return To->getKind() == BuiltinType::Int;
2037 }
Mike Stump11289f42009-09-09 15:08:12 +00002038
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00002039 // Are we promoting to an unsigned int from an unsigned bitfield
2040 // that fits into an unsigned int?
2041 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
2042 return To->getKind() == BuiltinType::UInt;
2043 }
Mike Stump11289f42009-09-09 15:08:12 +00002044
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00002045 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002046 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002047 }
Richard Smith88f4bba2015-03-26 00:16:07 +00002048 }
Mike Stump11289f42009-09-09 15:08:12 +00002049
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002050 // An rvalue of type bool can be converted to an rvalue of type int,
2051 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002052 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002053 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002054 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002055
2056 return false;
2057}
2058
2059/// IsFloatingPointPromotion - Determines whether the conversion from
2060/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2061/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00002062bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00002063 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2064 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002065 /// An rvalue of type float can be converted to an rvalue of type
2066 /// double. (C++ 4.6p1).
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002067 if (FromBuiltin->getKind() == BuiltinType::Float &&
2068 ToBuiltin->getKind() == BuiltinType::Double)
2069 return true;
2070
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002071 // C99 6.3.1.5p1:
2072 // When a float is promoted to double or long double, or a
2073 // double is promoted to long double [...].
David Blaikiebbafb8a2012-03-11 07:00:24 +00002074 if (!getLangOpts().CPlusPlus &&
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002075 (FromBuiltin->getKind() == BuiltinType::Float ||
2076 FromBuiltin->getKind() == BuiltinType::Double) &&
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002077 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2078 ToBuiltin->getKind() == BuiltinType::Float128))
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002079 return true;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002080
2081 // Half can be promoted to float.
Joey Goulydd7f4562013-01-23 11:56:20 +00002082 if (!getLangOpts().NativeHalfType &&
2083 FromBuiltin->getKind() == BuiltinType::Half &&
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002084 ToBuiltin->getKind() == BuiltinType::Float)
2085 return true;
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002086 }
2087
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002088 return false;
2089}
2090
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002091/// \brief Determine if a conversion is a complex promotion.
2092///
2093/// A complex promotion is defined as a complex -> complex conversion
2094/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00002095/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002096bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00002097 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002098 if (!FromComplex)
2099 return false;
2100
John McCall9dd450b2009-09-21 23:43:11 +00002101 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002102 if (!ToComplex)
2103 return false;
2104
2105 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00002106 ToComplex->getElementType()) ||
Craig Topperc3ec1492014-05-26 06:22:03 +00002107 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00002108 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002109}
2110
Douglas Gregor237f96c2008-11-26 23:31:11 +00002111/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2112/// the pointer type FromPtr to a pointer to type ToPointee, with the
2113/// same type qualifiers as FromPtr has on its pointee type. ToType,
2114/// if non-empty, will be a pointer to ToType that may or may not have
2115/// the right set of qualifiers on its pointee.
John McCall31168b02011-06-15 23:02:42 +00002116///
Mike Stump11289f42009-09-09 15:08:12 +00002117static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002118BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002119 QualType ToPointee, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002120 ASTContext &Context,
2121 bool StripObjCLifetime = false) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002122 assert((FromPtr->getTypeClass() == Type::Pointer ||
2123 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2124 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002125
John McCall31168b02011-06-15 23:02:42 +00002126 /// Conversions to 'id' subsume cv-qualifier conversions.
2127 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00002128 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002129
2130 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002131 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00002132 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00002133 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00002134
John McCall31168b02011-06-15 23:02:42 +00002135 if (StripObjCLifetime)
2136 Quals.removeObjCLifetime();
2137
Mike Stump11289f42009-09-09 15:08:12 +00002138 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002139 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00002140 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00002141 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00002142 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002143
2144 // Build a pointer to ToPointee. It has the right qualifiers
2145 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002146 if (isa<ObjCObjectPointerType>(ToType))
2147 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00002148 return Context.getPointerType(ToPointee);
2149 }
2150
2151 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002152 QualType QualifiedCanonToPointee
2153 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002154
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002155 if (isa<ObjCObjectPointerType>(ToType))
2156 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2157 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002158}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002159
Mike Stump11289f42009-09-09 15:08:12 +00002160static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00002161 bool InOverloadResolution,
2162 ASTContext &Context) {
2163 // Handle value-dependent integral null pointer constants correctly.
2164 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2165 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00002166 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00002167 return !InOverloadResolution;
2168
Douglas Gregor56751b52009-09-25 04:25:58 +00002169 return Expr->isNullPointerConstant(Context,
2170 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2171 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00002172}
Mike Stump11289f42009-09-09 15:08:12 +00002173
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002174/// IsPointerConversion - Determines whether the conversion of the
2175/// expression From, which has the (possibly adjusted) type FromType,
2176/// can be converted to the type ToType via a pointer conversion (C++
2177/// 4.10). If so, returns true and places the converted type (that
2178/// might differ from ToType in its cv-qualifiers at some level) into
2179/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00002180///
Douglas Gregora29dc052008-11-27 01:19:21 +00002181/// This routine also supports conversions to and from block pointers
2182/// and conversions with Objective-C's 'id', 'id<protocols...>', and
2183/// pointers to interfaces. FIXME: Once we've determined the
2184/// appropriate overloading rules for Objective-C, we may want to
2185/// split the Objective-C checks into a different routine; however,
2186/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00002187/// conversions, so for now they live here. IncompatibleObjC will be
2188/// set if the conversion is an allowed Objective-C conversion that
2189/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002190bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00002191 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00002192 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00002193 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00002194 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00002195 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2196 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00002197 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00002198
Mike Stump11289f42009-09-09 15:08:12 +00002199 // Conversion from a null pointer constant to any Objective-C pointer type.
2200 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002201 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00002202 ConvertedType = ToType;
2203 return true;
2204 }
2205
Douglas Gregor231d1c62008-11-27 00:15:41 +00002206 // Blocks: Block pointers can be converted to void*.
2207 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002208 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00002209 ConvertedType = ToType;
2210 return true;
2211 }
2212 // Blocks: A null pointer constant can be converted to a block
2213 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00002214 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002215 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00002216 ConvertedType = ToType;
2217 return true;
2218 }
2219
Sebastian Redl576fd422009-05-10 18:38:11 +00002220 // If the left-hand-side is nullptr_t, the right side can be a null
2221 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00002222 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002223 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00002224 ConvertedType = ToType;
2225 return true;
2226 }
2227
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002228 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002229 if (!ToTypePtr)
2230 return false;
2231
2232 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00002233 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002234 ConvertedType = ToType;
2235 return true;
2236 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002237
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002238 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002239 // , including objective-c pointers.
2240 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00002241 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002242 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002243 ConvertedType = BuildSimilarlyQualifiedPointerType(
2244 FromType->getAs<ObjCObjectPointerType>(),
2245 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002246 ToType, Context);
2247 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002248 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002249 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002250 if (!FromTypePtr)
2251 return false;
2252
2253 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002254
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002255 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-08-18 21:25:30 +00002256 // pointer conversion, so don't do all of the work below.
2257 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2258 return false;
2259
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002260 // An rvalue of type "pointer to cv T," where T is an object type,
2261 // can be converted to an rvalue of type "pointer to cv void" (C++
2262 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00002263 if (FromPointeeType->isIncompleteOrObjectType() &&
2264 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002265 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002266 ToPointeeType,
John McCall31168b02011-06-15 23:02:42 +00002267 ToType, Context,
2268 /*StripObjCLifetime=*/true);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002269 return true;
2270 }
2271
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002272 // MSVC allows implicit function to void* type conversion.
David Majnemer6bf02822015-10-31 08:42:14 +00002273 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002274 ToPointeeType->isVoidType()) {
2275 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2276 ToPointeeType,
2277 ToType, Context);
2278 return true;
2279 }
2280
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002281 // When we're overloading in C, we allow a special kind of pointer
2282 // conversion for compatible-but-not-identical pointee types.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002283 if (!getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002284 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002285 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002286 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00002287 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002288 return true;
2289 }
2290
Douglas Gregor5c407d92008-10-23 00:40:37 +00002291 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002292 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00002293 // An rvalue of type "pointer to cv D," where D is a class type,
2294 // can be converted to an rvalue of type "pointer to cv B," where
2295 // B is a base class (clause 10) of D. If B is an inaccessible
2296 // (clause 11) or ambiguous (10.2) base class of D, a program that
2297 // necessitates this conversion is ill-formed. The result of the
2298 // conversion is a pointer to the base class sub-object of the
2299 // derived class object. The null pointer value is converted to
2300 // the null pointer value of the destination type.
2301 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00002302 // Note that we do not check for ambiguity or inaccessibility
2303 // here. That is handled by CheckPointerConversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002304 if (getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002305 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00002306 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00002307 IsDerivedFrom(From->getLocStart(), FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002308 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002309 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002310 ToType, Context);
2311 return true;
2312 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002313
Fariborz Jahanianbc2ee932011-04-14 20:33:36 +00002314 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2315 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2316 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2317 ToPointeeType,
2318 ToType, Context);
2319 return true;
2320 }
2321
Douglas Gregora119f102008-12-19 19:13:09 +00002322 return false;
2323}
Douglas Gregoraec25842011-04-26 23:16:46 +00002324
2325/// \brief Adopt the given qualifiers for the given type.
2326static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2327 Qualifiers TQs = T.getQualifiers();
2328
2329 // Check whether qualifiers already match.
2330 if (TQs == Qs)
2331 return T;
2332
2333 if (Qs.compatiblyIncludes(TQs))
2334 return Context.getQualifiedType(T, Qs);
2335
2336 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2337}
Douglas Gregora119f102008-12-19 19:13:09 +00002338
2339/// isObjCPointerConversion - Determines whether this is an
2340/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2341/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00002342bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00002343 QualType& ConvertedType,
2344 bool &IncompatibleObjC) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002345 if (!getLangOpts().ObjC1)
Douglas Gregora119f102008-12-19 19:13:09 +00002346 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002347
Douglas Gregoraec25842011-04-26 23:16:46 +00002348 // The set of qualifiers on the type we're converting from.
2349 Qualifiers FromQualifiers = FromType.getQualifiers();
2350
Steve Naroff7cae42b2009-07-10 23:34:53 +00002351 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00002352 const ObjCObjectPointerType* ToObjCPtr =
2353 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00002354 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00002355 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002356
Steve Naroff7cae42b2009-07-10 23:34:53 +00002357 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002358 // If the pointee types are the same (ignoring qualifications),
2359 // then this is not a pointer conversion.
2360 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2361 FromObjCPtr->getPointeeType()))
2362 return false;
2363
Douglas Gregorab209d82015-07-07 03:58:42 +00002364 // Conversion between Objective-C pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00002365 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002366 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2367 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002368 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002369 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2370 FromObjCPtr->getPointeeType()))
2371 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002372 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002373 ToObjCPtr->getPointeeType(),
2374 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002375 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002376 return true;
2377 }
2378
2379 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2380 // Okay: this is some kind of implicit downcast of Objective-C
2381 // interfaces, which is permitted. However, we're going to
2382 // complain about it.
2383 IncompatibleObjC = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002384 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002385 ToObjCPtr->getPointeeType(),
2386 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002387 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002388 return true;
2389 }
Mike Stump11289f42009-09-09 15:08:12 +00002390 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00002391 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00002392 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002393 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002394 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002395 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002396 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002397 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002398 // to a block pointer type.
2399 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002400 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002401 return true;
2402 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002403 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002404 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002405 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002406 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002407 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002408 // pointer to any object.
Douglas Gregoraec25842011-04-26 23:16:46 +00002409 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002410 return true;
2411 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002412 else
Douglas Gregora119f102008-12-19 19:13:09 +00002413 return false;
2414
Douglas Gregor033f56d2008-12-23 00:53:59 +00002415 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002416 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002417 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00002418 else if (const BlockPointerType *FromBlockPtr =
2419 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00002420 FromPointeeType = FromBlockPtr->getPointeeType();
2421 else
Douglas Gregora119f102008-12-19 19:13:09 +00002422 return false;
2423
Douglas Gregora119f102008-12-19 19:13:09 +00002424 // If we have pointers to pointers, recursively check whether this
2425 // is an Objective-C conversion.
2426 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2427 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2428 IncompatibleObjC)) {
2429 // We always complain about this conversion.
2430 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002431 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002432 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002433 return true;
2434 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002435 // Allow conversion of pointee being objective-c pointer to another one;
2436 // as in I* to id.
2437 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2438 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2439 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2440 IncompatibleObjC)) {
John McCall31168b02011-06-15 23:02:42 +00002441
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002442 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002443 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002444 return true;
2445 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002446
Douglas Gregor033f56d2008-12-23 00:53:59 +00002447 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00002448 // differences in the argument and result types are in Objective-C
2449 // pointer conversions. If so, we permit the conversion (but
2450 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00002451 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002452 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002453 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002454 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002455 if (FromFunctionType && ToFunctionType) {
2456 // If the function types are exactly the same, this isn't an
2457 // Objective-C pointer conversion.
2458 if (Context.getCanonicalType(FromPointeeType)
2459 == Context.getCanonicalType(ToPointeeType))
2460 return false;
2461
2462 // Perform the quick checks that will tell us whether these
2463 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002464 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Douglas Gregora119f102008-12-19 19:13:09 +00002465 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2466 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2467 return false;
2468
2469 bool HasObjCConversion = false;
Alp Toker314cc812014-01-25 16:55:45 +00002470 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2471 Context.getCanonicalType(ToFunctionType->getReturnType())) {
Douglas Gregora119f102008-12-19 19:13:09 +00002472 // Okay, the types match exactly. Nothing to do.
Alp Toker314cc812014-01-25 16:55:45 +00002473 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2474 ToFunctionType->getReturnType(),
Douglas Gregora119f102008-12-19 19:13:09 +00002475 ConvertedType, IncompatibleObjC)) {
2476 // Okay, we have an Objective-C pointer conversion.
2477 HasObjCConversion = true;
2478 } else {
2479 // Function types are too different. Abort.
2480 return false;
2481 }
Mike Stump11289f42009-09-09 15:08:12 +00002482
Douglas Gregora119f102008-12-19 19:13:09 +00002483 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002484 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Douglas Gregora119f102008-12-19 19:13:09 +00002485 ArgIdx != NumArgs; ++ArgIdx) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002486 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2487 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Douglas Gregora119f102008-12-19 19:13:09 +00002488 if (Context.getCanonicalType(FromArgType)
2489 == Context.getCanonicalType(ToArgType)) {
2490 // Okay, the types match exactly. Nothing to do.
2491 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2492 ConvertedType, IncompatibleObjC)) {
2493 // Okay, we have an Objective-C pointer conversion.
2494 HasObjCConversion = true;
2495 } else {
2496 // Argument types are too different. Abort.
2497 return false;
2498 }
2499 }
2500
2501 if (HasObjCConversion) {
2502 // We had an Objective-C conversion. Allow this pointer
2503 // conversion, but complain about it.
Douglas Gregoraec25842011-04-26 23:16:46 +00002504 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002505 IncompatibleObjC = true;
2506 return true;
2507 }
2508 }
2509
Sebastian Redl72b597d2009-01-25 19:43:20 +00002510 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002511}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002512
John McCall31168b02011-06-15 23:02:42 +00002513/// \brief Determine whether this is an Objective-C writeback conversion,
2514/// used for parameter passing when performing automatic reference counting.
2515///
2516/// \param FromType The type we're converting form.
2517///
2518/// \param ToType The type we're converting to.
2519///
2520/// \param ConvertedType The type that will be produced after applying
2521/// this conversion.
2522bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2523 QualType &ConvertedType) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002524 if (!getLangOpts().ObjCAutoRefCount ||
John McCall31168b02011-06-15 23:02:42 +00002525 Context.hasSameUnqualifiedType(FromType, ToType))
2526 return false;
2527
2528 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2529 QualType ToPointee;
2530 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2531 ToPointee = ToPointer->getPointeeType();
2532 else
2533 return false;
2534
2535 Qualifiers ToQuals = ToPointee.getQualifiers();
2536 if (!ToPointee->isObjCLifetimeType() ||
2537 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall18ce25e2012-02-08 00:46:36 +00002538 !ToQuals.withoutObjCLifetime().empty())
John McCall31168b02011-06-15 23:02:42 +00002539 return false;
2540
2541 // Argument must be a pointer to __strong to __weak.
2542 QualType FromPointee;
2543 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2544 FromPointee = FromPointer->getPointeeType();
2545 else
2546 return false;
2547
2548 Qualifiers FromQuals = FromPointee.getQualifiers();
2549 if (!FromPointee->isObjCLifetimeType() ||
2550 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2551 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2552 return false;
2553
2554 // Make sure that we have compatible qualifiers.
2555 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2556 if (!ToQuals.compatiblyIncludes(FromQuals))
2557 return false;
2558
2559 // Remove qualifiers from the pointee type we're converting from; they
2560 // aren't used in the compatibility check belong, and we'll be adding back
2561 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2562 FromPointee = FromPointee.getUnqualifiedType();
2563
2564 // The unqualified form of the pointee types must be compatible.
2565 ToPointee = ToPointee.getUnqualifiedType();
2566 bool IncompatibleObjC;
2567 if (Context.typesAreCompatible(FromPointee, ToPointee))
2568 FromPointee = ToPointee;
2569 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2570 IncompatibleObjC))
2571 return false;
2572
2573 /// \brief Construct the type we're converting to, which is a pointer to
2574 /// __autoreleasing pointee.
2575 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2576 ConvertedType = Context.getPointerType(FromPointee);
2577 return true;
2578}
2579
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002580bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2581 QualType& ConvertedType) {
2582 QualType ToPointeeType;
2583 if (const BlockPointerType *ToBlockPtr =
2584 ToType->getAs<BlockPointerType>())
2585 ToPointeeType = ToBlockPtr->getPointeeType();
2586 else
2587 return false;
2588
2589 QualType FromPointeeType;
2590 if (const BlockPointerType *FromBlockPtr =
2591 FromType->getAs<BlockPointerType>())
2592 FromPointeeType = FromBlockPtr->getPointeeType();
2593 else
2594 return false;
2595 // We have pointer to blocks, check whether the only
2596 // differences in the argument and result types are in Objective-C
2597 // pointer conversions. If so, we permit the conversion.
2598
2599 const FunctionProtoType *FromFunctionType
2600 = FromPointeeType->getAs<FunctionProtoType>();
2601 const FunctionProtoType *ToFunctionType
2602 = ToPointeeType->getAs<FunctionProtoType>();
2603
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002604 if (!FromFunctionType || !ToFunctionType)
2605 return false;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002606
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002607 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002608 return true;
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002609
2610 // Perform the quick checks that will tell us whether these
2611 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002612 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002613 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2614 return false;
2615
2616 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2617 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2618 if (FromEInfo != ToEInfo)
2619 return false;
2620
2621 bool IncompatibleObjC = false;
Alp Toker314cc812014-01-25 16:55:45 +00002622 if (Context.hasSameType(FromFunctionType->getReturnType(),
2623 ToFunctionType->getReturnType())) {
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002624 // Okay, the types match exactly. Nothing to do.
2625 } else {
Alp Toker314cc812014-01-25 16:55:45 +00002626 QualType RHS = FromFunctionType->getReturnType();
2627 QualType LHS = ToFunctionType->getReturnType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002628 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002629 !RHS.hasQualifiers() && LHS.hasQualifiers())
2630 LHS = LHS.getUnqualifiedType();
2631
2632 if (Context.hasSameType(RHS,LHS)) {
2633 // OK exact match.
2634 } else if (isObjCPointerConversion(RHS, LHS,
2635 ConvertedType, IncompatibleObjC)) {
2636 if (IncompatibleObjC)
2637 return false;
2638 // Okay, we have an Objective-C pointer conversion.
2639 }
2640 else
2641 return false;
2642 }
2643
2644 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002645 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002646 ArgIdx != NumArgs; ++ArgIdx) {
2647 IncompatibleObjC = false;
Alp Toker9cacbab2014-01-20 20:26:09 +00002648 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2649 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002650 if (Context.hasSameType(FromArgType, ToArgType)) {
2651 // Okay, the types match exactly. Nothing to do.
2652 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2653 ConvertedType, IncompatibleObjC)) {
2654 if (IncompatibleObjC)
2655 return false;
2656 // Okay, we have an Objective-C pointer conversion.
2657 } else
2658 // Argument types are too different. Abort.
2659 return false;
2660 }
John McCall18afab72016-03-01 00:49:02 +00002661 if (!Context.doFunctionTypesMatchOnExtParameterInfos(FromFunctionType,
2662 ToFunctionType))
Fariborz Jahanian97676972011-09-28 21:52:05 +00002663 return false;
Fariborz Jahanian600ba202011-09-28 20:22:05 +00002664
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002665 ConvertedType = ToType;
2666 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002667}
2668
Richard Trieucaff2472011-11-23 22:32:32 +00002669enum {
2670 ft_default,
2671 ft_different_class,
2672 ft_parameter_arity,
2673 ft_parameter_mismatch,
2674 ft_return_type,
Richard Smith3c4f8d22016-10-16 17:54:23 +00002675 ft_qualifer_mismatch,
2676 ft_noexcept
Richard Trieucaff2472011-11-23 22:32:32 +00002677};
2678
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002679/// Attempts to get the FunctionProtoType from a Type. Handles
2680/// MemberFunctionPointers properly.
2681static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2682 if (auto *FPT = FromType->getAs<FunctionProtoType>())
2683 return FPT;
2684
2685 if (auto *MPT = FromType->getAs<MemberPointerType>())
2686 return MPT->getPointeeType()->getAs<FunctionProtoType>();
2687
2688 return nullptr;
2689}
2690
Richard Trieucaff2472011-11-23 22:32:32 +00002691/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2692/// function types. Catches different number of parameter, mismatch in
2693/// parameter types, and different return types.
2694void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2695 QualType FromType, QualType ToType) {
Richard Trieu96ed5b62011-12-13 23:19:45 +00002696 // If either type is not valid, include no extra info.
2697 if (FromType.isNull() || ToType.isNull()) {
2698 PDiag << ft_default;
2699 return;
2700 }
2701
Richard Trieucaff2472011-11-23 22:32:32 +00002702 // Get the function type from the pointers.
2703 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2704 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2705 *ToMember = ToType->getAs<MemberPointerType>();
Richard Trieu9098c9f2014-05-22 01:39:16 +00002706 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
Richard Trieucaff2472011-11-23 22:32:32 +00002707 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2708 << QualType(FromMember->getClass(), 0);
2709 return;
2710 }
2711 FromType = FromMember->getPointeeType();
2712 ToType = ToMember->getPointeeType();
Richard Trieucaff2472011-11-23 22:32:32 +00002713 }
2714
Richard Trieu96ed5b62011-12-13 23:19:45 +00002715 if (FromType->isPointerType())
2716 FromType = FromType->getPointeeType();
2717 if (ToType->isPointerType())
2718 ToType = ToType->getPointeeType();
2719
2720 // Remove references.
Richard Trieucaff2472011-11-23 22:32:32 +00002721 FromType = FromType.getNonReferenceType();
2722 ToType = ToType.getNonReferenceType();
2723
Richard Trieucaff2472011-11-23 22:32:32 +00002724 // Don't print extra info for non-specialized template functions.
2725 if (FromType->isInstantiationDependentType() &&
2726 !FromType->getAs<TemplateSpecializationType>()) {
2727 PDiag << ft_default;
2728 return;
2729 }
2730
Richard Trieu96ed5b62011-12-13 23:19:45 +00002731 // No extra info for same types.
2732 if (Context.hasSameType(FromType, ToType)) {
2733 PDiag << ft_default;
2734 return;
2735 }
2736
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002737 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2738 *ToFunction = tryGetFunctionProtoType(ToType);
Richard Trieucaff2472011-11-23 22:32:32 +00002739
2740 // Both types need to be function types.
2741 if (!FromFunction || !ToFunction) {
2742 PDiag << ft_default;
2743 return;
2744 }
2745
Alp Toker9cacbab2014-01-20 20:26:09 +00002746 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2747 PDiag << ft_parameter_arity << ToFunction->getNumParams()
2748 << FromFunction->getNumParams();
Richard Trieucaff2472011-11-23 22:32:32 +00002749 return;
2750 }
2751
2752 // Handle different parameter types.
2753 unsigned ArgPos;
Alp Toker9cacbab2014-01-20 20:26:09 +00002754 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
Richard Trieucaff2472011-11-23 22:32:32 +00002755 PDiag << ft_parameter_mismatch << ArgPos + 1
Alp Toker9cacbab2014-01-20 20:26:09 +00002756 << ToFunction->getParamType(ArgPos)
2757 << FromFunction->getParamType(ArgPos);
Richard Trieucaff2472011-11-23 22:32:32 +00002758 return;
2759 }
2760
2761 // Handle different return type.
Alp Toker314cc812014-01-25 16:55:45 +00002762 if (!Context.hasSameType(FromFunction->getReturnType(),
2763 ToFunction->getReturnType())) {
2764 PDiag << ft_return_type << ToFunction->getReturnType()
2765 << FromFunction->getReturnType();
Richard Trieucaff2472011-11-23 22:32:32 +00002766 return;
2767 }
2768
2769 unsigned FromQuals = FromFunction->getTypeQuals(),
2770 ToQuals = ToFunction->getTypeQuals();
2771 if (FromQuals != ToQuals) {
2772 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2773 return;
2774 }
2775
Richard Smith3c4f8d22016-10-16 17:54:23 +00002776 // Handle exception specification differences on canonical type (in C++17
2777 // onwards).
2778 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2779 ->isNothrow(Context) !=
2780 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2781 ->isNothrow(Context)) {
2782 PDiag << ft_noexcept;
2783 return;
2784 }
2785
Richard Trieucaff2472011-11-23 22:32:32 +00002786 // Unable to find a difference, so add no extra info.
2787 PDiag << ft_default;
2788}
2789
Alp Toker9cacbab2014-01-20 20:26:09 +00002790/// FunctionParamTypesAreEqual - This routine checks two function proto types
Douglas Gregor2039ca02011-12-15 17:15:07 +00002791/// for equality of their argument types. Caller has already checked that
Eli Friedman5f508952013-06-18 22:41:37 +00002792/// they have same number of arguments. If the parameters are different,
2793/// ArgPos will have the parameter index of the first different parameter.
Alp Toker9cacbab2014-01-20 20:26:09 +00002794bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2795 const FunctionProtoType *NewType,
2796 unsigned *ArgPos) {
2797 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2798 N = NewType->param_type_begin(),
2799 E = OldType->param_type_end();
2800 O && (O != E); ++O, ++N) {
Richard Trieu4b03d982013-08-09 21:42:32 +00002801 if (!Context.hasSameType(O->getUnqualifiedType(),
2802 N->getUnqualifiedType())) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002803 if (ArgPos)
2804 *ArgPos = O - OldType->param_type_begin();
Larisse Voufo4154f462013-08-06 03:57:41 +00002805 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002806 }
2807 }
2808 return true;
2809}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002810
Douglas Gregor39c16d42008-10-24 04:54:22 +00002811/// CheckPointerConversion - Check the pointer conversion from the
2812/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00002813/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00002814/// conversions for which IsPointerConversion has already returned
2815/// true. It returns true and produces a diagnostic if there was an
2816/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002817bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002818 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002819 CXXCastPath& BasePath,
George Burgess IV60bc9722016-01-13 23:36:34 +00002820 bool IgnoreBaseAccess,
2821 bool Diagnose) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002822 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00002823 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002824
John McCall8cb679e2010-11-15 09:13:47 +00002825 Kind = CK_BitCast;
2826
George Burgess IV60bc9722016-01-13 23:36:34 +00002827 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
Argyrios Kyrtzidis3e3305d2014-02-02 05:26:43 +00002828 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
George Burgess IV60bc9722016-01-13 23:36:34 +00002829 Expr::NPCK_ZeroExpression) {
David Blaikie1c7c8f72012-08-08 17:33:31 +00002830 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2831 DiagRuntimeBehavior(From->getExprLoc(), From,
2832 PDiag(diag::warn_impcast_bool_to_null_pointer)
2833 << ToType << From->getSourceRange());
2834 else if (!isUnevaluatedContext())
2835 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2836 << ToType << From->getSourceRange();
2837 }
John McCall9320b872011-09-09 05:25:32 +00002838 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2839 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002840 QualType FromPointeeType = FromPtrType->getPointeeType(),
2841 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00002842
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002843 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2844 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002845 // We must have a derived-to-base conversion. Check an
2846 // ambiguous or inaccessible conversion.
George Burgess IV60bc9722016-01-13 23:36:34 +00002847 unsigned InaccessibleID = 0;
2848 unsigned AmbigiousID = 0;
2849 if (Diagnose) {
2850 InaccessibleID = diag::err_upcast_to_inaccessible_base;
2851 AmbigiousID = diag::err_ambiguous_derived_to_base_conv;
2852 }
2853 if (CheckDerivedToBaseConversion(
2854 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID,
2855 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
2856 &BasePath, IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002857 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002858
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002859 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00002860 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002861 }
David Majnemer6bf02822015-10-31 08:42:14 +00002862
George Burgess IV60bc9722016-01-13 23:36:34 +00002863 if (Diagnose && !IsCStyleOrFunctionalCast &&
2864 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
David Majnemer6bf02822015-10-31 08:42:14 +00002865 assert(getLangOpts().MSVCCompat &&
2866 "this should only be possible with MSVCCompat!");
2867 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
2868 << From->getSourceRange();
2869 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00002870 }
John McCall9320b872011-09-09 05:25:32 +00002871 } else if (const ObjCObjectPointerType *ToPtrType =
2872 ToType->getAs<ObjCObjectPointerType>()) {
2873 if (const ObjCObjectPointerType *FromPtrType =
2874 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002875 // Objective-C++ conversions are always okay.
2876 // FIXME: We should have a different class of conversions for the
2877 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00002878 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002879 return false;
John McCall9320b872011-09-09 05:25:32 +00002880 } else if (FromType->isBlockPointerType()) {
2881 Kind = CK_BlockPointerToObjCPointerCast;
2882 } else {
2883 Kind = CK_CPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00002884 }
John McCall9320b872011-09-09 05:25:32 +00002885 } else if (ToType->isBlockPointerType()) {
2886 if (!FromType->isBlockPointerType())
2887 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002888 }
John McCall8cb679e2010-11-15 09:13:47 +00002889
2890 // We shouldn't fall into this case unless it's valid for other
2891 // reasons.
2892 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2893 Kind = CK_NullToPointer;
2894
Douglas Gregor39c16d42008-10-24 04:54:22 +00002895 return false;
2896}
2897
Sebastian Redl72b597d2009-01-25 19:43:20 +00002898/// IsMemberPointerConversion - Determines whether the conversion of the
2899/// expression From, which has the (possibly adjusted) type FromType, can be
2900/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2901/// If so, returns true and places the converted type (that might differ from
2902/// ToType in its cv-qualifiers at some level) into ConvertedType.
2903bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002904 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00002905 bool InOverloadResolution,
2906 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002907 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002908 if (!ToTypePtr)
2909 return false;
2910
2911 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00002912 if (From->isNullPointerConstant(Context,
2913 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2914 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002915 ConvertedType = ToType;
2916 return true;
2917 }
2918
2919 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002920 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002921 if (!FromTypePtr)
2922 return false;
2923
2924 // A pointer to member of B can be converted to a pointer to member of D,
2925 // where D is derived from B (C++ 4.11p2).
2926 QualType FromClass(FromTypePtr->getClass(), 0);
2927 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002928
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002929 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00002930 IsDerivedFrom(From->getLocStart(), ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002931 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2932 ToClass.getTypePtr());
2933 return true;
2934 }
2935
2936 return false;
2937}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002938
Sebastian Redl72b597d2009-01-25 19:43:20 +00002939/// CheckMemberPointerConversion - Check the member pointer conversion from the
2940/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002941/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002942/// for which IsMemberPointerConversion has already returned true. It returns
2943/// true and produces a diagnostic if there was an error, or returns false
2944/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002945bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002946 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002947 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002948 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002949 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002950 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00002951 if (!FromPtrType) {
2952 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002953 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00002954 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00002955 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00002956 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00002957 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00002958 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00002959
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002960 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00002961 assert(ToPtrType && "No member pointer cast has a target type "
2962 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002963
Sebastian Redled8f2002009-01-28 18:33:18 +00002964 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2965 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002966
Sebastian Redled8f2002009-01-28 18:33:18 +00002967 // FIXME: What about dependent types?
2968 assert(FromClass->isRecordType() && "Pointer into non-class.");
2969 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002970
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002971 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002972 /*DetectVirtual=*/true);
Richard Smith0f59cb32015-12-18 21:45:41 +00002973 bool DerivationOkay =
2974 IsDerivedFrom(From->getLocStart(), ToClass, FromClass, Paths);
Sebastian Redled8f2002009-01-28 18:33:18 +00002975 assert(DerivationOkay &&
2976 "Should not have been called if derivation isn't OK.");
2977 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002978
Sebastian Redled8f2002009-01-28 18:33:18 +00002979 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2980 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002981 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2982 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2983 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2984 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002985 }
Sebastian Redled8f2002009-01-28 18:33:18 +00002986
Douglas Gregor89ee6822009-02-28 01:32:25 +00002987 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002988 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2989 << FromClass << ToClass << QualType(VBase, 0)
2990 << From->getSourceRange();
2991 return true;
2992 }
2993
John McCall5b0829a2010-02-10 09:31:12 +00002994 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00002995 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2996 Paths.front(),
2997 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00002998
Anders Carlssond7923c62009-08-22 23:33:40 +00002999 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00003000 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00003001 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00003002 return false;
3003}
3004
Douglas Gregorc9f019a2013-11-08 02:04:24 +00003005/// Determine whether the lifetime conversion between the two given
3006/// qualifiers sets is nontrivial.
3007static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3008 Qualifiers ToQuals) {
3009 // Converting anything to const __unsafe_unretained is trivial.
3010 if (ToQuals.hasConst() &&
3011 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3012 return false;
3013
3014 return true;
3015}
3016
Douglas Gregor9a657932008-10-21 23:43:52 +00003017/// IsQualificationConversion - Determines whether the conversion from
3018/// an rvalue of type FromType to ToType is a qualification conversion
3019/// (C++ 4.4).
John McCall31168b02011-06-15 23:02:42 +00003020///
3021/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3022/// when the qualification conversion involves a change in the Objective-C
3023/// object lifetime.
Mike Stump11289f42009-09-09 15:08:12 +00003024bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003025Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00003026 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor9a657932008-10-21 23:43:52 +00003027 FromType = Context.getCanonicalType(FromType);
3028 ToType = Context.getCanonicalType(ToType);
John McCall31168b02011-06-15 23:02:42 +00003029 ObjCLifetimeConversion = false;
3030
Douglas Gregor9a657932008-10-21 23:43:52 +00003031 // If FromType and ToType are the same type, this is not a
3032 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00003033 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00003034 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00003035
Douglas Gregor9a657932008-10-21 23:43:52 +00003036 // (C++ 4.4p4):
3037 // A conversion can add cv-qualifiers at levels other than the first
3038 // in multi-level pointers, subject to the following rules: [...]
3039 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00003040 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003041 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00003042 // Within each iteration of the loop, we check the qualifiers to
3043 // determine if this still looks like a qualification
3044 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003045 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00003046 // until there are no more pointers or pointers-to-members left to
3047 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003048 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00003049
Douglas Gregor90609aa2011-04-25 18:40:17 +00003050 Qualifiers FromQuals = FromType.getQualifiers();
3051 Qualifiers ToQuals = ToType.getQualifiers();
Andrey Bokhanko45d41322016-05-11 18:38:21 +00003052
3053 // Ignore __unaligned qualifier if this type is void.
3054 if (ToType.getUnqualifiedType()->isVoidType())
3055 FromQuals.removeUnaligned();
Douglas Gregor90609aa2011-04-25 18:40:17 +00003056
John McCall31168b02011-06-15 23:02:42 +00003057 // Objective-C ARC:
3058 // Check Objective-C lifetime conversions.
3059 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
3060 UnwrappedAnyPointer) {
3061 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00003062 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3063 ObjCLifetimeConversion = true;
John McCall31168b02011-06-15 23:02:42 +00003064 FromQuals.removeObjCLifetime();
3065 ToQuals.removeObjCLifetime();
3066 } else {
3067 // Qualification conversions cannot cast between different
3068 // Objective-C lifetime qualifiers.
3069 return false;
3070 }
3071 }
3072
Douglas Gregorf30053d2011-05-08 06:09:53 +00003073 // Allow addition/removal of GC attributes but not changing GC attributes.
3074 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3075 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3076 FromQuals.removeObjCGCAttr();
3077 ToQuals.removeObjCGCAttr();
3078 }
3079
Douglas Gregor9a657932008-10-21 23:43:52 +00003080 // -- for every j > 0, if const is in cv 1,j then const is in cv
3081 // 2,j, and similarly for volatile.
Douglas Gregor90609aa2011-04-25 18:40:17 +00003082 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor9a657932008-10-21 23:43:52 +00003083 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003084
Douglas Gregor9a657932008-10-21 23:43:52 +00003085 // -- if the cv 1,j and cv 2,j are different, then const is in
3086 // every cv for 0 < k < j.
Douglas Gregor90609aa2011-04-25 18:40:17 +00003087 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003088 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00003089 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003090
Douglas Gregor9a657932008-10-21 23:43:52 +00003091 // Keep track of whether all prior cv-qualifiers in the "to" type
3092 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00003093 PreviousToQualsIncludeConst
Douglas Gregor90609aa2011-04-25 18:40:17 +00003094 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003095 }
Douglas Gregor9a657932008-10-21 23:43:52 +00003096
3097 // We are left with FromType and ToType being the pointee types
3098 // after unwrapping the original FromType and ToType the same number
3099 // of types. If we unwrapped any pointers, and if FromType and
3100 // ToType have the same unqualified type (since we checked
3101 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003102 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00003103}
3104
Douglas Gregorc79862f2012-04-12 17:51:55 +00003105/// \brief - Determine whether this is a conversion from a scalar type to an
3106/// atomic type.
3107///
3108/// If successful, updates \c SCS's second and third steps in the conversion
3109/// sequence to finish the conversion.
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00003110static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3111 bool InOverloadResolution,
3112 StandardConversionSequence &SCS,
3113 bool CStyle) {
Douglas Gregorc79862f2012-04-12 17:51:55 +00003114 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3115 if (!ToAtomic)
3116 return false;
3117
3118 StandardConversionSequence InnerSCS;
3119 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3120 InOverloadResolution, InnerSCS,
3121 CStyle, /*AllowObjCWritebackConversion=*/false))
3122 return false;
3123
3124 SCS.Second = InnerSCS.Second;
3125 SCS.setToType(1, InnerSCS.getToType(1));
3126 SCS.Third = InnerSCS.Third;
3127 SCS.QualificationIncludesObjCLifetime
3128 = InnerSCS.QualificationIncludesObjCLifetime;
3129 SCS.setToType(2, InnerSCS.getToType(2));
3130 return true;
3131}
3132
Sebastian Redle5417162012-03-27 18:33:03 +00003133static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3134 CXXConstructorDecl *Constructor,
3135 QualType Type) {
3136 const FunctionProtoType *CtorType =
3137 Constructor->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00003138 if (CtorType->getNumParams() > 0) {
3139 QualType FirstArg = CtorType->getParamType(0);
Sebastian Redle5417162012-03-27 18:33:03 +00003140 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3141 return true;
3142 }
3143 return false;
3144}
3145
Sebastian Redl82ace982012-02-11 23:51:08 +00003146static OverloadingResult
3147IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3148 CXXRecordDecl *To,
3149 UserDefinedConversionSequence &User,
3150 OverloadCandidateSet &CandidateSet,
3151 bool AllowExplicit) {
Richard Smithc2bebe92016-05-11 20:37:46 +00003152 for (auto *D : S.LookupConstructors(To)) {
3153 auto Info = getConstructorInfo(D);
Richard Smith5179eb72016-06-28 19:03:57 +00003154 if (!Info)
Richard Smithc2bebe92016-05-11 20:37:46 +00003155 continue;
Sebastian Redl82ace982012-02-11 23:51:08 +00003156
Richard Smithc2bebe92016-05-11 20:37:46 +00003157 bool Usable = !Info.Constructor->isInvalidDecl() &&
3158 S.isInitListConstructor(Info.Constructor) &&
3159 (AllowExplicit || !Info.Constructor->isExplicit());
Sebastian Redl82ace982012-02-11 23:51:08 +00003160 if (Usable) {
Sebastian Redle5417162012-03-27 18:33:03 +00003161 // If the first argument is (a reference to) the target type,
3162 // suppress conversions.
Richard Smithc2bebe92016-05-11 20:37:46 +00003163 bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3164 S.Context, Info.Constructor, ToType);
3165 if (Info.ConstructorTmpl)
3166 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3167 /*ExplicitArgs*/ nullptr, From,
3168 CandidateSet, SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00003169 else
Richard Smithc2bebe92016-05-11 20:37:46 +00003170 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3171 CandidateSet, SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00003172 }
3173 }
3174
3175 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3176
3177 OverloadCandidateSet::iterator Best;
Fariborz Jahaniandcf06f42015-04-14 17:21:58 +00003178 switch (auto Result =
3179 CandidateSet.BestViableFunction(S, From->getLocStart(),
3180 Best, true)) {
3181 case OR_Deleted:
Sebastian Redl82ace982012-02-11 23:51:08 +00003182 case OR_Success: {
3183 // Record the standard conversion we used and the conversion function.
3184 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Sebastian Redl82ace982012-02-11 23:51:08 +00003185 QualType ThisType = Constructor->getThisType(S.Context);
3186 // Initializer lists don't have conversions as such.
3187 User.Before.setAsIdentityConversion();
3188 User.HadMultipleCandidates = HadMultipleCandidates;
3189 User.ConversionFunction = Constructor;
3190 User.FoundConversionFunction = Best->FoundDecl;
3191 User.After.setAsIdentityConversion();
3192 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3193 User.After.setAllToTypes(ToType);
Fariborz Jahaniandcf06f42015-04-14 17:21:58 +00003194 return Result;
Sebastian Redl82ace982012-02-11 23:51:08 +00003195 }
3196
3197 case OR_No_Viable_Function:
3198 return OR_No_Viable_Function;
Sebastian Redl82ace982012-02-11 23:51:08 +00003199 case OR_Ambiguous:
3200 return OR_Ambiguous;
3201 }
3202
3203 llvm_unreachable("Invalid OverloadResult!");
3204}
3205
Douglas Gregor576e98c2009-01-30 23:27:23 +00003206/// Determines whether there is a user-defined conversion sequence
3207/// (C++ [over.ics.user]) that converts expression From to the type
3208/// ToType. If such a conversion exists, User will contain the
3209/// user-defined conversion sequence that performs such a conversion
3210/// and this routine will return true. Otherwise, this routine returns
3211/// false and User is unspecified.
3212///
Douglas Gregor576e98c2009-01-30 23:27:23 +00003213/// \param AllowExplicit true if the conversion should consider C++0x
3214/// "explicit" conversion functions as well as non-explicit conversion
3215/// functions (C++0x [class.conv.fct]p2).
Douglas Gregor4b60a152013-11-07 22:34:54 +00003216///
3217/// \param AllowObjCConversionOnExplicit true if the conversion should
3218/// allow an extra Objective-C pointer conversion on uses of explicit
3219/// constructors. Requires \c AllowExplicit to also be set.
John McCall5c32be02010-08-24 20:38:10 +00003220static OverloadingResult
3221IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl82ace982012-02-11 23:51:08 +00003222 UserDefinedConversionSequence &User,
3223 OverloadCandidateSet &CandidateSet,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003224 bool AllowExplicit,
3225 bool AllowObjCConversionOnExplicit) {
Douglas Gregor2ee1d992013-11-08 01:20:25 +00003226 assert(AllowExplicit || !AllowObjCConversionOnExplicit);
Douglas Gregor4b60a152013-11-07 22:34:54 +00003227
Douglas Gregor5ab11652010-04-17 22:01:05 +00003228 // Whether we will only visit constructors.
3229 bool ConstructorsOnly = false;
3230
3231 // If the type we are conversion to is a class type, enumerate its
3232 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003233 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00003234 // C++ [over.match.ctor]p1:
3235 // When objects of class type are direct-initialized (8.5), or
3236 // copy-initialized from an expression of the same or a
3237 // derived class type (8.5), overload resolution selects the
3238 // constructor. [...] For copy-initialization, the candidate
3239 // functions are all the converting constructors (12.3.1) of
3240 // that class. The argument list is the expression-list within
3241 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00003242 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00003243 (From->getType()->getAs<RecordType>() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00003244 S.IsDerivedFrom(From->getLocStart(), From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00003245 ConstructorsOnly = true;
3246
Richard Smithdb0ac552015-12-18 22:40:25 +00003247 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003248 // We're not going to find any constructors.
3249 } else if (CXXRecordDecl *ToRecordDecl
3250 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003251
3252 Expr **Args = &From;
3253 unsigned NumArgs = 1;
3254 bool ListInitializing = false;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003255 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003256 // But first, see if there is an init-list-constructor that will work.
Sebastian Redl82ace982012-02-11 23:51:08 +00003257 OverloadingResult Result = IsInitializerListConstructorConversion(
3258 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3259 if (Result != OR_No_Viable_Function)
3260 return Result;
3261 // Never mind.
3262 CandidateSet.clear();
3263
3264 // If we're list-initializing, we pass the individual elements as
3265 // arguments, not the entire list.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003266 Args = InitList->getInits();
3267 NumArgs = InitList->getNumInits();
3268 ListInitializing = true;
3269 }
3270
Richard Smithc2bebe92016-05-11 20:37:46 +00003271 for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3272 auto Info = getConstructorInfo(D);
Richard Smith5179eb72016-06-28 19:03:57 +00003273 if (!Info)
Richard Smithc2bebe92016-05-11 20:37:46 +00003274 continue;
John McCalla0296f72010-03-19 07:35:19 +00003275
Richard Smithc2bebe92016-05-11 20:37:46 +00003276 bool Usable = !Info.Constructor->isInvalidDecl();
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003277 if (ListInitializing)
Richard Smithc2bebe92016-05-11 20:37:46 +00003278 Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit());
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003279 else
Richard Smithc2bebe92016-05-11 20:37:46 +00003280 Usable = Usable &&
3281 Info.Constructor->isConvertingConstructor(AllowExplicit);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003282 if (Usable) {
Sebastian Redld9170b02012-03-20 21:24:14 +00003283 bool SuppressUserConversions = !ConstructorsOnly;
3284 if (SuppressUserConversions && ListInitializing) {
3285 SuppressUserConversions = false;
3286 if (NumArgs == 1) {
3287 // If the first argument is (a reference to) the target type,
3288 // suppress conversions.
Sebastian Redle5417162012-03-27 18:33:03 +00003289 SuppressUserConversions = isFirstArgumentCompatibleWithType(
Richard Smithc2bebe92016-05-11 20:37:46 +00003290 S.Context, Info.Constructor, ToType);
Sebastian Redld9170b02012-03-20 21:24:14 +00003291 }
3292 }
Richard Smithc2bebe92016-05-11 20:37:46 +00003293 if (Info.ConstructorTmpl)
3294 S.AddTemplateOverloadCandidate(
3295 Info.ConstructorTmpl, Info.FoundDecl,
3296 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3297 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003298 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00003299 // Allow one user-defined conversion when user specifies a
3300 // From->ToType conversion via an static cast (c-style, etc).
Richard Smithc2bebe92016-05-11 20:37:46 +00003301 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003302 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003303 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003304 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00003305 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003306 }
3307 }
3308
Douglas Gregor5ab11652010-04-17 22:01:05 +00003309 // Enumerate conversion functions, if we're allowed to.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003310 if (ConstructorsOnly || isa<InitListExpr>(From)) {
Richard Smithdb0ac552015-12-18 22:40:25 +00003311 } else if (!S.isCompleteType(From->getLocStart(), From->getType())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003312 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00003313 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00003314 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00003315 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003316 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3317 // Add all of the conversion functions as candidates.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00003318 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3319 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00003320 DeclAccessPair FoundDecl = I.getPair();
3321 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003322 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3323 if (isa<UsingShadowDecl>(D))
3324 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3325
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003326 CXXConversionDecl *Conv;
3327 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00003328 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3329 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003330 else
John McCallda4458e2010-03-31 01:36:47 +00003331 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003332
3333 if (AllowExplicit || !Conv->isExplicit()) {
3334 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00003335 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3336 ActingContext, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003337 CandidateSet,
3338 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003339 else
John McCall5c32be02010-08-24 20:38:10 +00003340 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003341 From, ToType, CandidateSet,
3342 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003343 }
3344 }
3345 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00003346 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003347
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003348 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3349
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003350 OverloadCandidateSet::iterator Best;
Richard Smith48372b62015-01-27 03:30:40 +00003351 switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(),
3352 Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00003353 case OR_Success:
Richard Smith48372b62015-01-27 03:30:40 +00003354 case OR_Deleted:
John McCall5c32be02010-08-24 20:38:10 +00003355 // Record the standard conversion we used and the conversion function.
3356 if (CXXConstructorDecl *Constructor
3357 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3358 // C++ [over.ics.user]p1:
3359 // If the user-defined conversion is specified by a
3360 // constructor (12.3.1), the initial standard conversion
3361 // sequence converts the source type to the type required by
3362 // the argument of the constructor.
3363 //
3364 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003365 if (isa<InitListExpr>(From)) {
3366 // Initializer lists don't have conversions as such.
3367 User.Before.setAsIdentityConversion();
3368 } else {
3369 if (Best->Conversions[0].isEllipsis())
3370 User.EllipsisConversion = true;
3371 else {
3372 User.Before = Best->Conversions[0].Standard;
3373 User.EllipsisConversion = false;
3374 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003375 }
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003376 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003377 User.ConversionFunction = Constructor;
John McCall30909032011-09-21 08:36:56 +00003378 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003379 User.After.setAsIdentityConversion();
3380 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3381 User.After.setAllToTypes(ToType);
Richard Smith48372b62015-01-27 03:30:40 +00003382 return Result;
David Blaikie8a40f702012-01-17 06:56:22 +00003383 }
3384 if (CXXConversionDecl *Conversion
John McCall5c32be02010-08-24 20:38:10 +00003385 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3386 // C++ [over.ics.user]p1:
3387 //
3388 // [...] If the user-defined conversion is specified by a
3389 // conversion function (12.3.2), the initial standard
3390 // conversion sequence converts the source type to the
3391 // implicit object parameter of the conversion function.
3392 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003393 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003394 User.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00003395 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003396 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00003397
John McCall5c32be02010-08-24 20:38:10 +00003398 // C++ [over.ics.user]p2:
3399 // The second standard conversion sequence converts the
3400 // result of the user-defined conversion to the target type
3401 // for the sequence. Since an implicit conversion sequence
3402 // is an initialization, the special rules for
3403 // initialization by user-defined conversion apply when
3404 // selecting the best user-defined conversion for a
3405 // user-defined conversion sequence (see 13.3.3 and
3406 // 13.3.3.1).
3407 User.After = Best->FinalConversion;
Richard Smith48372b62015-01-27 03:30:40 +00003408 return Result;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003409 }
David Blaikie8a40f702012-01-17 06:56:22 +00003410 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003411
John McCall5c32be02010-08-24 20:38:10 +00003412 case OR_No_Viable_Function:
3413 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003414
John McCall5c32be02010-08-24 20:38:10 +00003415 case OR_Ambiguous:
3416 return OR_Ambiguous;
3417 }
3418
David Blaikie8a40f702012-01-17 06:56:22 +00003419 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003420}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003421
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003422bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00003423Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003424 ImplicitConversionSequence ICS;
Richard Smith100b24a2014-04-17 01:52:14 +00003425 OverloadCandidateSet CandidateSet(From->getExprLoc(),
3426 OverloadCandidateSet::CSK_Normal);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003427 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00003428 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003429 CandidateSet, false, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00003430 if (OvResult == OR_Ambiguous)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003431 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3432 << From->getType() << ToType << From->getSourceRange();
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003433 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
Larisse Voufo70bb43a2013-06-27 03:36:30 +00003434 if (!RequireCompleteType(From->getLocStart(), ToType,
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003435 diag::err_typecheck_nonviable_condition_incomplete,
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003436 From->getType(), From->getSourceRange()))
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003437 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
Nick Lewycky08426e22015-08-25 22:18:46 +00003438 << false << From->getType() << From->getSourceRange() << ToType;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003439 } else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003440 return false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003441 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003442 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003443}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003444
Douglas Gregor2837aa22012-02-22 17:32:19 +00003445/// \brief Compare the user-defined conversion functions or constructors
3446/// of two user-defined conversion sequences to determine whether any ordering
3447/// is possible.
3448static ImplicitConversionSequence::CompareKind
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003449compareConversionFunctions(Sema &S, FunctionDecl *Function1,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003450 FunctionDecl *Function2) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003451 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
Douglas Gregor2837aa22012-02-22 17:32:19 +00003452 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003453
Douglas Gregor2837aa22012-02-22 17:32:19 +00003454 // Objective-C++:
3455 // If both conversion functions are implicitly-declared conversions from
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003456 // a lambda closure type to a function pointer and a block pointer,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003457 // respectively, always prefer the conversion to a function pointer,
3458 // because the function pointer is more lightweight and is more likely
3459 // to keep code working.
Ted Kremenek8d265c22014-04-01 07:23:18 +00003460 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003461 if (!Conv1)
3462 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003463
Douglas Gregor2837aa22012-02-22 17:32:19 +00003464 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3465 if (!Conv2)
3466 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003467
Douglas Gregor2837aa22012-02-22 17:32:19 +00003468 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3469 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3470 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3471 if (Block1 != Block2)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003472 return Block1 ? ImplicitConversionSequence::Worse
3473 : ImplicitConversionSequence::Better;
Douglas Gregor2837aa22012-02-22 17:32:19 +00003474 }
3475
3476 return ImplicitConversionSequence::Indistinguishable;
3477}
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003478
3479static bool hasDeprecatedStringLiteralToCharPtrConversion(
3480 const ImplicitConversionSequence &ICS) {
3481 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3482 (ICS.isUserDefined() &&
3483 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3484}
3485
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003486/// CompareImplicitConversionSequences - Compare two implicit
3487/// conversion sequences to determine whether one is better than the
3488/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00003489static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +00003490CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +00003491 const ImplicitConversionSequence& ICS1,
3492 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003493{
3494 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3495 // conversion sequences (as defined in 13.3.3.1)
3496 // -- a standard conversion sequence (13.3.3.1.1) is a better
3497 // conversion sequence than a user-defined conversion sequence or
3498 // an ellipsis conversion sequence, and
3499 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3500 // conversion sequence than an ellipsis conversion sequence
3501 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00003502 //
John McCall0d1da222010-01-12 00:44:57 +00003503 // C++0x [over.best.ics]p10:
3504 // For the purpose of ranking implicit conversion sequences as
3505 // described in 13.3.3.2, the ambiguous conversion sequence is
3506 // treated as a user-defined sequence that is indistinguishable
3507 // from any other user-defined conversion sequence.
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003508
3509 // String literal to 'char *' conversion has been deprecated in C++03. It has
3510 // been removed from C++11. We still accept this conversion, if it happens at
3511 // the best viable function. Otherwise, this conversion is considered worse
3512 // than ellipsis conversion. Consider this as an extension; this is not in the
3513 // standard. For example:
3514 //
3515 // int &f(...); // #1
3516 // void f(char*); // #2
3517 // void g() { int &r = f("foo"); }
3518 //
3519 // In C++03, we pick #2 as the best viable function.
3520 // In C++11, we pick #1 as the best viable function, because ellipsis
3521 // conversion is better than string-literal to char* conversion (since there
3522 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3523 // convert arguments, #2 would be the best viable function in C++11.
3524 // If the best viable function has this conversion, a warning will be issued
3525 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3526
3527 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3528 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3529 hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3530 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3531 ? ImplicitConversionSequence::Worse
3532 : ImplicitConversionSequence::Better;
3533
Douglas Gregor5ab11652010-04-17 22:01:05 +00003534 if (ICS1.getKindRank() < ICS2.getKindRank())
3535 return ImplicitConversionSequence::Better;
David Blaikie8a40f702012-01-17 06:56:22 +00003536 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor5ab11652010-04-17 22:01:05 +00003537 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003538
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00003539 // The following checks require both conversion sequences to be of
3540 // the same kind.
3541 if (ICS1.getKind() != ICS2.getKind())
3542 return ImplicitConversionSequence::Indistinguishable;
3543
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003544 ImplicitConversionSequence::CompareKind Result =
3545 ImplicitConversionSequence::Indistinguishable;
3546
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003547 // Two implicit conversion sequences of the same form are
3548 // indistinguishable conversion sequences unless one of the
3549 // following rules apply: (C++ 13.3.3.2p3):
Larisse Voufo19d08672015-01-27 18:47:05 +00003550
3551 // List-initialization sequence L1 is a better conversion sequence than
3552 // list-initialization sequence L2 if:
3553 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3554 // if not that,
NAKAMURA Takumib01d86b2015-02-25 11:02:00 +00003555 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
Larisse Voufo19d08672015-01-27 18:47:05 +00003556 // and N1 is smaller than N2.,
3557 // even if one of the other rules in this paragraph would otherwise apply.
3558 if (!ICS1.isBad()) {
3559 if (ICS1.isStdInitializerListElement() &&
3560 !ICS2.isStdInitializerListElement())
3561 return ImplicitConversionSequence::Better;
3562 if (!ICS1.isStdInitializerListElement() &&
3563 ICS2.isStdInitializerListElement())
3564 return ImplicitConversionSequence::Worse;
3565 }
3566
John McCall0d1da222010-01-12 00:44:57 +00003567 if (ICS1.isStandard())
Larisse Voufo19d08672015-01-27 18:47:05 +00003568 // Standard conversion sequence S1 is a better conversion sequence than
3569 // standard conversion sequence S2 if [...]
Richard Smith0f59cb32015-12-18 21:45:41 +00003570 Result = CompareStandardConversionSequences(S, Loc,
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003571 ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00003572 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003573 // User-defined conversion sequence U1 is a better conversion
3574 // sequence than another user-defined conversion sequence U2 if
3575 // they contain the same user-defined conversion function or
3576 // constructor and if the second standard conversion sequence of
3577 // U1 is better than the second standard conversion sequence of
3578 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00003579 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003580 ICS2.UserDefined.ConversionFunction)
Richard Smith0f59cb32015-12-18 21:45:41 +00003581 Result = CompareStandardConversionSequences(S, Loc,
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003582 ICS1.UserDefined.After,
3583 ICS2.UserDefined.After);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003584 else
3585 Result = compareConversionFunctions(S,
3586 ICS1.UserDefined.ConversionFunction,
3587 ICS2.UserDefined.ConversionFunction);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003588 }
3589
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003590 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003591}
3592
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003593static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3594 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3595 Qualifiers Quals;
3596 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003597 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003598 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003599
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003600 return Context.hasSameUnqualifiedType(T1, T2);
3601}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003602
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003603// Per 13.3.3.2p3, compare the given standard conversion sequences to
3604// determine if one is a proper subset of the other.
3605static ImplicitConversionSequence::CompareKind
3606compareStandardConversionSubsets(ASTContext &Context,
3607 const StandardConversionSequence& SCS1,
3608 const StandardConversionSequence& SCS2) {
3609 ImplicitConversionSequence::CompareKind Result
3610 = ImplicitConversionSequence::Indistinguishable;
3611
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003612 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00003613 // any non-identity conversion sequence
Douglas Gregor377c1092011-06-05 06:15:20 +00003614 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3615 return ImplicitConversionSequence::Better;
3616 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3617 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003618
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003619 if (SCS1.Second != SCS2.Second) {
3620 if (SCS1.Second == ICK_Identity)
3621 Result = ImplicitConversionSequence::Better;
3622 else if (SCS2.Second == ICK_Identity)
3623 Result = ImplicitConversionSequence::Worse;
3624 else
3625 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003626 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003627 return ImplicitConversionSequence::Indistinguishable;
3628
3629 if (SCS1.Third == SCS2.Third) {
3630 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3631 : ImplicitConversionSequence::Indistinguishable;
3632 }
3633
3634 if (SCS1.Third == ICK_Identity)
3635 return Result == ImplicitConversionSequence::Worse
3636 ? ImplicitConversionSequence::Indistinguishable
3637 : ImplicitConversionSequence::Better;
3638
3639 if (SCS2.Third == ICK_Identity)
3640 return Result == ImplicitConversionSequence::Better
3641 ? ImplicitConversionSequence::Indistinguishable
3642 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003643
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003644 return ImplicitConversionSequence::Indistinguishable;
3645}
3646
Douglas Gregore696ebb2011-01-26 14:52:12 +00003647/// \brief Determine whether one of the given reference bindings is better
3648/// than the other based on what kind of bindings they are.
Richard Smith19172c42014-07-14 02:28:44 +00003649static bool
3650isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3651 const StandardConversionSequence &SCS2) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003652 // C++0x [over.ics.rank]p3b4:
3653 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3654 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003655 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00003656 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003657 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00003658 // reference*.
3659 //
3660 // FIXME: Rvalue references. We're going rogue with the above edits,
3661 // because the semantics in the current C++0x working paper (N3225 at the
3662 // time of this writing) break the standard definition of std::forward
3663 // and std::reference_wrapper when dealing with references to functions.
3664 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00003665 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3666 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3667 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003668
Douglas Gregore696ebb2011-01-26 14:52:12 +00003669 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3670 SCS2.IsLvalueReference) ||
3671 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
Richard Smith19172c42014-07-14 02:28:44 +00003672 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
Douglas Gregore696ebb2011-01-26 14:52:12 +00003673}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003674
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003675/// CompareStandardConversionSequences - Compare two standard
3676/// conversion sequences to determine whether one is better than the
3677/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00003678static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +00003679CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +00003680 const StandardConversionSequence& SCS1,
3681 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003682{
3683 // Standard conversion sequence S1 is a better conversion sequence
3684 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3685
3686 // -- S1 is a proper subsequence of S2 (comparing the conversion
3687 // sequences in the canonical form defined by 13.3.3.1.1,
3688 // excluding any Lvalue Transformation; the identity conversion
3689 // sequence is considered to be a subsequence of any
3690 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003691 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00003692 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003693 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003694
3695 // -- the rank of S1 is better than the rank of S2 (by the rules
3696 // defined below), or, if not that,
3697 ImplicitConversionRank Rank1 = SCS1.getRank();
3698 ImplicitConversionRank Rank2 = SCS2.getRank();
3699 if (Rank1 < Rank2)
3700 return ImplicitConversionSequence::Better;
3701 else if (Rank2 < Rank1)
3702 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003703
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003704 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3705 // are indistinguishable unless one of the following rules
3706 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00003707
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003708 // A conversion that is not a conversion of a pointer, or
3709 // pointer to member, to bool is better than another conversion
3710 // that is such a conversion.
3711 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3712 return SCS2.isPointerConversionToBool()
3713 ? ImplicitConversionSequence::Better
3714 : ImplicitConversionSequence::Worse;
3715
Douglas Gregor5c407d92008-10-23 00:40:37 +00003716 // C++ [over.ics.rank]p4b2:
3717 //
3718 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003719 // conversion of B* to A* is better than conversion of B* to
3720 // void*, and conversion of A* to void* is better than conversion
3721 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00003722 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003723 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00003724 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003725 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003726 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3727 // Exactly one of the conversion sequences is a conversion to
3728 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003729 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3730 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003731 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3732 // Neither conversion sequence converts to a void pointer; compare
3733 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003734 if (ImplicitConversionSequence::CompareKind DerivedCK
Richard Smith0f59cb32015-12-18 21:45:41 +00003735 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003736 return DerivedCK;
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003737 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3738 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003739 // Both conversion sequences are conversions to void
3740 // pointers. Compare the source types to determine if there's an
3741 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00003742 QualType FromType1 = SCS1.getFromType();
3743 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003744
3745 // Adjust the types we're converting from via the array-to-pointer
3746 // conversion, if we need to.
3747 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003748 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003749 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003750 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003751
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003752 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3753 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003754
Richard Smith0f59cb32015-12-18 21:45:41 +00003755 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003756 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00003757 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003758 return ImplicitConversionSequence::Worse;
3759
3760 // Objective-C++: If one interface is more specific than the
3761 // other, it is the better one.
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003762 const ObjCObjectPointerType* FromObjCPtr1
3763 = FromType1->getAs<ObjCObjectPointerType>();
3764 const ObjCObjectPointerType* FromObjCPtr2
3765 = FromType2->getAs<ObjCObjectPointerType>();
3766 if (FromObjCPtr1 && FromObjCPtr2) {
3767 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3768 FromObjCPtr2);
3769 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3770 FromObjCPtr1);
3771 if (AssignLeft != AssignRight) {
3772 return AssignLeft? ImplicitConversionSequence::Better
3773 : ImplicitConversionSequence::Worse;
3774 }
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003775 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003776 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003777
3778 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3779 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00003780 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00003781 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003782 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003783
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003784 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003785 // Check for a better reference binding based on the kind of bindings.
3786 if (isBetterReferenceBindingKind(SCS1, SCS2))
3787 return ImplicitConversionSequence::Better;
3788 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3789 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003790
Sebastian Redlb28b4072009-03-22 23:49:27 +00003791 // C++ [over.ics.rank]p3b4:
3792 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3793 // which the references refer are the same type except for
3794 // top-level cv-qualifiers, and the type to which the reference
3795 // initialized by S2 refers is more cv-qualified than the type
3796 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003797 QualType T1 = SCS1.getToType(2);
3798 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003799 T1 = S.Context.getCanonicalType(T1);
3800 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003801 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003802 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3803 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003804 if (UnqualT1 == UnqualT2) {
John McCall31168b02011-06-15 23:02:42 +00003805 // Objective-C++ ARC: If the references refer to objects with different
3806 // lifetimes, prefer bindings that don't change lifetime.
3807 if (SCS1.ObjCLifetimeConversionBinding !=
3808 SCS2.ObjCLifetimeConversionBinding) {
3809 return SCS1.ObjCLifetimeConversionBinding
3810 ? ImplicitConversionSequence::Worse
3811 : ImplicitConversionSequence::Better;
3812 }
3813
Chandler Carruth8e543b32010-12-12 08:17:55 +00003814 // If the type is an array type, promote the element qualifiers to the
3815 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003816 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003817 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003818 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003819 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003820 if (T2.isMoreQualifiedThan(T1))
3821 return ImplicitConversionSequence::Better;
3822 else if (T1.isMoreQualifiedThan(T2))
John McCall31168b02011-06-15 23:02:42 +00003823 return ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003824 }
3825 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003826
Francois Pichet08d2fa02011-09-18 21:37:37 +00003827 // In Microsoft mode, prefer an integral conversion to a
3828 // floating-to-integral conversion if the integral conversion
3829 // is between types of the same size.
3830 // For example:
3831 // void f(float);
3832 // void f(int);
3833 // int main {
3834 // long a;
3835 // f(a);
3836 // }
3837 // Here, MSVC will call f(int) instead of generating a compile error
3838 // as clang will do in standard mode.
Alp Tokerbfa39342014-01-14 12:51:41 +00003839 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3840 SCS2.Second == ICK_Floating_Integral &&
Francois Pichet08d2fa02011-09-18 21:37:37 +00003841 S.Context.getTypeSize(SCS1.getFromType()) ==
Alp Tokerbfa39342014-01-14 12:51:41 +00003842 S.Context.getTypeSize(SCS1.getToType(2)))
Francois Pichet08d2fa02011-09-18 21:37:37 +00003843 return ImplicitConversionSequence::Better;
3844
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003845 return ImplicitConversionSequence::Indistinguishable;
3846}
3847
3848/// CompareQualificationConversions - Compares two standard conversion
3849/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00003850/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
Richard Smith17c00b42014-11-12 01:24:00 +00003851static ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003852CompareQualificationConversions(Sema &S,
3853 const StandardConversionSequence& SCS1,
3854 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00003855 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003856 // -- S1 and S2 differ only in their qualification conversion and
3857 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3858 // cv-qualification signature of type T1 is a proper subset of
3859 // the cv-qualification signature of type T2, and S1 is not the
3860 // deprecated string literal array-to-pointer conversion (4.2).
3861 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3862 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3863 return ImplicitConversionSequence::Indistinguishable;
3864
3865 // FIXME: the example in the standard doesn't use a qualification
3866 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003867 QualType T1 = SCS1.getToType(2);
3868 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003869 T1 = S.Context.getCanonicalType(T1);
3870 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003871 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003872 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3873 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003874
3875 // If the types are the same, we won't learn anything by unwrapped
3876 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003877 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003878 return ImplicitConversionSequence::Indistinguishable;
3879
Chandler Carruth607f38e2009-12-29 07:16:59 +00003880 // If the type is an array type, promote the element qualifiers to the type
3881 // for comparison.
3882 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003883 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003884 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003885 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003886
Mike Stump11289f42009-09-09 15:08:12 +00003887 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003888 = ImplicitConversionSequence::Indistinguishable;
John McCall31168b02011-06-15 23:02:42 +00003889
3890 // Objective-C++ ARC:
3891 // Prefer qualification conversions not involving a change in lifetime
3892 // to qualification conversions that do not change lifetime.
3893 if (SCS1.QualificationIncludesObjCLifetime !=
3894 SCS2.QualificationIncludesObjCLifetime) {
3895 Result = SCS1.QualificationIncludesObjCLifetime
3896 ? ImplicitConversionSequence::Worse
3897 : ImplicitConversionSequence::Better;
3898 }
3899
John McCall5c32be02010-08-24 20:38:10 +00003900 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003901 // Within each iteration of the loop, we check the qualifiers to
3902 // determine if this still looks like a qualification
3903 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003904 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003905 // until there are no more pointers or pointers-to-members left
3906 // to unwrap. This essentially mimics what
3907 // IsQualificationConversion does, but here we're checking for a
3908 // strict subset of qualifiers.
3909 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3910 // The qualifiers are the same, so this doesn't tell us anything
3911 // about how the sequences rank.
3912 ;
3913 else if (T2.isMoreQualifiedThan(T1)) {
3914 // T1 has fewer qualifiers, so it could be the better sequence.
3915 if (Result == ImplicitConversionSequence::Worse)
3916 // Neither has qualifiers that are a subset of the other's
3917 // qualifiers.
3918 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003919
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003920 Result = ImplicitConversionSequence::Better;
3921 } else if (T1.isMoreQualifiedThan(T2)) {
3922 // T2 has fewer qualifiers, so it could be the better sequence.
3923 if (Result == ImplicitConversionSequence::Better)
3924 // Neither has qualifiers that are a subset of the other's
3925 // qualifiers.
3926 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003927
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003928 Result = ImplicitConversionSequence::Worse;
3929 } else {
3930 // Qualifiers are disjoint.
3931 return ImplicitConversionSequence::Indistinguishable;
3932 }
3933
3934 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00003935 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003936 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003937 }
3938
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003939 // Check that the winning standard conversion sequence isn't using
3940 // the deprecated string literal array to pointer conversion.
3941 switch (Result) {
3942 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003943 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003944 Result = ImplicitConversionSequence::Indistinguishable;
3945 break;
3946
3947 case ImplicitConversionSequence::Indistinguishable:
3948 break;
3949
3950 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003951 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003952 Result = ImplicitConversionSequence::Indistinguishable;
3953 break;
3954 }
3955
3956 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003957}
3958
Douglas Gregor5c407d92008-10-23 00:40:37 +00003959/// CompareDerivedToBaseConversions - Compares two standard conversion
3960/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00003961/// various kinds of derived-to-base conversions (C++
3962/// [over.ics.rank]p4b3). As part of these checks, we also look at
3963/// conversions between Objective-C interface types.
Richard Smith17c00b42014-11-12 01:24:00 +00003964static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +00003965CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +00003966 const StandardConversionSequence& SCS1,
3967 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00003968 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003969 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00003970 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003971 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003972
3973 // Adjust the types we're converting from via the array-to-pointer
3974 // conversion, if we need to.
3975 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003976 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003977 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003978 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003979
3980 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00003981 FromType1 = S.Context.getCanonicalType(FromType1);
3982 ToType1 = S.Context.getCanonicalType(ToType1);
3983 FromType2 = S.Context.getCanonicalType(FromType2);
3984 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003985
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003986 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00003987 //
3988 // If class B is derived directly or indirectly from class A and
3989 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00003990 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003991 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00003992 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00003993 SCS2.Second == ICK_Pointer_Conversion &&
3994 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3995 FromType1->isPointerType() && FromType2->isPointerType() &&
3996 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003997 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003998 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00003999 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004000 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00004001 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004002 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00004003 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004004 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00004005
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004006 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00004007 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004008 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00004009 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004010 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00004011 return ImplicitConversionSequence::Worse;
4012 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004013
4014 // -- conversion of B* to A* is better than conversion of C* to A*,
4015 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004016 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004017 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004018 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004019 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00004020 }
4021 } else if (SCS1.Second == ICK_Pointer_Conversion &&
4022 SCS2.Second == ICK_Pointer_Conversion) {
4023 const ObjCObjectPointerType *FromPtr1
4024 = FromType1->getAs<ObjCObjectPointerType>();
4025 const ObjCObjectPointerType *FromPtr2
4026 = FromType2->getAs<ObjCObjectPointerType>();
4027 const ObjCObjectPointerType *ToPtr1
4028 = ToType1->getAs<ObjCObjectPointerType>();
4029 const ObjCObjectPointerType *ToPtr2
4030 = ToType2->getAs<ObjCObjectPointerType>();
4031
4032 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4033 // Apply the same conversion ranking rules for Objective-C pointer types
4034 // that we do for C++ pointers to class types. However, we employ the
4035 // Objective-C pseudo-subtyping relationship used for assignment of
4036 // Objective-C pointer types.
4037 bool FromAssignLeft
4038 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4039 bool FromAssignRight
4040 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4041 bool ToAssignLeft
4042 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4043 bool ToAssignRight
4044 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4045
4046 // A conversion to an a non-id object pointer type or qualified 'id'
4047 // type is better than a conversion to 'id'.
4048 if (ToPtr1->isObjCIdType() &&
4049 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4050 return ImplicitConversionSequence::Worse;
4051 if (ToPtr2->isObjCIdType() &&
4052 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4053 return ImplicitConversionSequence::Better;
4054
4055 // A conversion to a non-id object pointer type is better than a
4056 // conversion to a qualified 'id' type
4057 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4058 return ImplicitConversionSequence::Worse;
4059 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4060 return ImplicitConversionSequence::Better;
4061
4062 // A conversion to an a non-Class object pointer type or qualified 'Class'
4063 // type is better than a conversion to 'Class'.
4064 if (ToPtr1->isObjCClassType() &&
4065 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4066 return ImplicitConversionSequence::Worse;
4067 if (ToPtr2->isObjCClassType() &&
4068 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4069 return ImplicitConversionSequence::Better;
4070
4071 // A conversion to a non-Class object pointer type is better than a
4072 // conversion to a qualified 'Class' type.
4073 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4074 return ImplicitConversionSequence::Worse;
4075 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4076 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00004077
Douglas Gregor058d3de2011-01-31 18:51:41 +00004078 // -- "conversion of C* to B* is better than conversion of C* to A*,"
4079 if (S.Context.hasSameType(FromType1, FromType2) &&
4080 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4081 (ToAssignLeft != ToAssignRight))
4082 return ToAssignLeft? ImplicitConversionSequence::Worse
4083 : ImplicitConversionSequence::Better;
4084
4085 // -- "conversion of B* to A* is better than conversion of C* to A*,"
4086 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4087 (FromAssignLeft != FromAssignRight))
4088 return FromAssignLeft? ImplicitConversionSequence::Better
4089 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004090 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00004091 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00004092
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00004093 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004094 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4095 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4096 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004097 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004098 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004099 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004100 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004101 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004102 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004103 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004104 ToType2->getAs<MemberPointerType>();
4105 const Type *FromPointeeType1 = FromMemPointer1->getClass();
4106 const Type *ToPointeeType1 = ToMemPointer1->getClass();
4107 const Type *FromPointeeType2 = FromMemPointer2->getClass();
4108 const Type *ToPointeeType2 = ToMemPointer2->getClass();
4109 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4110 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4111 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4112 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00004113 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004114 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004115 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004116 return ImplicitConversionSequence::Worse;
Richard Smith0f59cb32015-12-18 21:45:41 +00004117 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004118 return ImplicitConversionSequence::Better;
4119 }
4120 // conversion of B::* to C::* is better than conversion of A::* to C::*
4121 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004122 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004123 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004124 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004125 return ImplicitConversionSequence::Worse;
4126 }
4127 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004128
Douglas Gregor5ab11652010-04-17 22:01:05 +00004129 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00004130 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00004131 // -- binding of an expression of type C to a reference of type
4132 // B& is better than binding an expression of type C to a
4133 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00004134 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4135 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004136 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004137 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004138 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004139 return ImplicitConversionSequence::Worse;
4140 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004141
Douglas Gregor2fe98832008-11-03 19:09:14 +00004142 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00004143 // -- binding of an expression of type B to a reference of type
4144 // A& is better than binding an expression of type C to a
4145 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00004146 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4147 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004148 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004149 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004150 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004151 return ImplicitConversionSequence::Worse;
4152 }
4153 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004154
Douglas Gregor5c407d92008-10-23 00:40:37 +00004155 return ImplicitConversionSequence::Indistinguishable;
4156}
4157
Douglas Gregor45bb4832013-03-26 23:36:30 +00004158/// \brief Determine whether the given type is valid, e.g., it is not an invalid
4159/// C++ class.
4160static bool isTypeValid(QualType T) {
4161 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4162 return !Record->isInvalidDecl();
4163
4164 return true;
4165}
4166
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004167/// CompareReferenceRelationship - Compare the two types T1 and T2 to
4168/// determine whether they are reference-related,
4169/// reference-compatible, reference-compatible with added
4170/// qualification, or incompatible, for use in C++ initialization by
4171/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4172/// type, and the first type (T1) is the pointee type of the reference
4173/// type being initialized.
4174Sema::ReferenceCompareResult
4175Sema::CompareReferenceRelationship(SourceLocation Loc,
4176 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004177 bool &DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004178 bool &ObjCConversion,
4179 bool &ObjCLifetimeConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004180 assert(!OrigT1->isReferenceType() &&
4181 "T1 must be the pointee type of the reference type");
4182 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4183
4184 QualType T1 = Context.getCanonicalType(OrigT1);
4185 QualType T2 = Context.getCanonicalType(OrigT2);
4186 Qualifiers T1Quals, T2Quals;
4187 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4188 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4189
4190 // C++ [dcl.init.ref]p4:
4191 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4192 // reference-related to "cv2 T2" if T1 is the same type as T2, or
4193 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004194 DerivedToBase = false;
4195 ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004196 ObjCLifetimeConversion = false;
Richard Smith1be59c52016-10-22 01:32:19 +00004197 QualType ConvertedT2;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004198 if (UnqualT1 == UnqualT2) {
4199 // Nothing to do.
Richard Smithdb0ac552015-12-18 22:40:25 +00004200 } else if (isCompleteType(Loc, OrigT2) &&
Douglas Gregor45bb4832013-03-26 23:36:30 +00004201 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00004202 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004203 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004204 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4205 UnqualT2->isObjCObjectOrInterfaceType() &&
4206 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4207 ObjCConversion = true;
Richard Smith1be59c52016-10-22 01:32:19 +00004208 else if (UnqualT2->isFunctionType() &&
4209 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2))
4210 // C++1z [dcl.init.ref]p4:
4211 // cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept
4212 // function" and T1 is "function"
4213 //
4214 // We extend this to also apply to 'noreturn', so allow any function
4215 // conversion between function types.
4216 return Ref_Compatible;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004217 else
4218 return Ref_Incompatible;
4219
4220 // At this point, we know that T1 and T2 are reference-related (at
4221 // least).
4222
4223 // If the type is an array type, promote the element qualifiers to the type
4224 // for comparison.
4225 if (isa<ArrayType>(T1) && T1Quals)
4226 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4227 if (isa<ArrayType>(T2) && T2Quals)
4228 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4229
4230 // C++ [dcl.init.ref]p4:
4231 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4232 // reference-related to T2 and cv1 is the same cv-qualification
4233 // as, or greater cv-qualification than, cv2. For purposes of
4234 // overload resolution, cases for which cv1 is greater
4235 // cv-qualification than cv2 are identified as
4236 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregord517d552011-04-28 17:56:11 +00004237 //
4238 // Note that we also require equivalence of Objective-C GC and address-space
4239 // qualifiers when performing these computations, so that e.g., an int in
4240 // address space 1 is not reference-compatible with an int in address
4241 // space 2.
John McCall31168b02011-06-15 23:02:42 +00004242 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4243 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00004244 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4245 ObjCLifetimeConversion = true;
4246
John McCall31168b02011-06-15 23:02:42 +00004247 T1Quals.removeObjCLifetime();
4248 T2Quals.removeObjCLifetime();
John McCall31168b02011-06-15 23:02:42 +00004249 }
4250
Andrey Bokhanko45d41322016-05-11 18:38:21 +00004251 // MS compiler ignores __unaligned qualifier for references; do the same.
4252 T1Quals.removeUnaligned();
4253 T2Quals.removeUnaligned();
4254
Richard Smithce766292016-10-21 23:01:55 +00004255 if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004256 return Ref_Compatible;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004257 else
4258 return Ref_Related;
4259}
4260
Douglas Gregor836a7e82010-08-11 02:15:33 +00004261/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00004262/// with DeclType. Return true if something definite is found.
4263static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00004264FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4265 QualType DeclType, SourceLocation DeclLoc,
4266 Expr *Init, QualType T2, bool AllowRvalues,
4267 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004268 assert(T2->isRecordType() && "Can only find conversions of record types.");
4269 CXXRecordDecl *T2RecordDecl
4270 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4271
Richard Smith100b24a2014-04-17 01:52:14 +00004272 OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal);
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004273 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4274 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004275 NamedDecl *D = *I;
4276 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4277 if (isa<UsingShadowDecl>(D))
4278 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4279
4280 FunctionTemplateDecl *ConvTemplate
4281 = dyn_cast<FunctionTemplateDecl>(D);
4282 CXXConversionDecl *Conv;
4283 if (ConvTemplate)
4284 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4285 else
4286 Conv = cast<CXXConversionDecl>(D);
4287
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004288 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00004289 // explicit conversions, skip it.
4290 if (!AllowExplicit && Conv->isExplicit())
4291 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004292
Douglas Gregor836a7e82010-08-11 02:15:33 +00004293 if (AllowRvalues) {
4294 bool DerivedToBase = false;
4295 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004296 bool ObjCLifetimeConversion = false;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004297
4298 // If we are initializing an rvalue reference, don't permit conversion
4299 // functions that return lvalues.
4300 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4301 const ReferenceType *RefType
4302 = Conv->getConversionType()->getAs<LValueReferenceType>();
4303 if (RefType && !RefType->getPointeeType()->isFunctionType())
4304 continue;
4305 }
4306
Douglas Gregor836a7e82010-08-11 02:15:33 +00004307 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00004308 S.CompareReferenceRelationship(
4309 DeclLoc,
4310 Conv->getConversionType().getNonReferenceType()
4311 .getUnqualifiedType(),
4312 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCall31168b02011-06-15 23:02:42 +00004313 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth8e543b32010-12-12 08:17:55 +00004314 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00004315 continue;
4316 } else {
4317 // If the conversion function doesn't return a reference type,
4318 // it can't be considered for this conversion. An rvalue reference
4319 // is only acceptable if its referencee is a function type.
4320
4321 const ReferenceType *RefType =
4322 Conv->getConversionType()->getAs<ReferenceType>();
4323 if (!RefType ||
4324 (!RefType->isLValueReferenceType() &&
4325 !RefType->getPointeeType()->isFunctionType()))
4326 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00004327 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004328
Douglas Gregor836a7e82010-08-11 02:15:33 +00004329 if (ConvTemplate)
4330 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004331 Init, DeclType, CandidateSet,
4332 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor836a7e82010-08-11 02:15:33 +00004333 else
4334 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004335 DeclType, CandidateSet,
4336 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redld92badf2010-06-30 18:13:39 +00004337 }
4338
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004339 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4340
Sebastian Redld92badf2010-06-30 18:13:39 +00004341 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00004342 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004343 case OR_Success:
4344 // C++ [over.ics.ref]p1:
4345 //
4346 // [...] If the parameter binds directly to the result of
4347 // applying a conversion function to the argument
4348 // expression, the implicit conversion sequence is a
4349 // user-defined conversion sequence (13.3.3.1.2), with the
4350 // second standard conversion sequence either an identity
4351 // conversion or, if the conversion function returns an
4352 // entity of a type that is a derived class of the parameter
4353 // type, a derived-to-base Conversion.
4354 if (!Best->FinalConversion.DirectBinding)
4355 return false;
4356
4357 ICS.setUserDefined();
4358 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4359 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004360 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redld92badf2010-06-30 18:13:39 +00004361 ICS.UserDefined.ConversionFunction = Best->Function;
John McCall30909032011-09-21 08:36:56 +00004362 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redld92badf2010-06-30 18:13:39 +00004363 ICS.UserDefined.EllipsisConversion = false;
4364 assert(ICS.UserDefined.After.ReferenceBinding &&
4365 ICS.UserDefined.After.DirectBinding &&
4366 "Expected a direct reference binding!");
4367 return true;
4368
4369 case OR_Ambiguous:
4370 ICS.setAmbiguous();
4371 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4372 Cand != CandidateSet.end(); ++Cand)
4373 if (Cand->Viable)
Richard Smithc2bebe92016-05-11 20:37:46 +00004374 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
Sebastian Redld92badf2010-06-30 18:13:39 +00004375 return true;
4376
4377 case OR_No_Viable_Function:
4378 case OR_Deleted:
4379 // There was no suitable conversion, or we found a deleted
4380 // conversion; continue with other checks.
4381 return false;
4382 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004383
David Blaikie8a40f702012-01-17 06:56:22 +00004384 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redld92badf2010-06-30 18:13:39 +00004385}
4386
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004387/// \brief Compute an implicit conversion sequence for reference
4388/// initialization.
4389static ImplicitConversionSequence
Sebastian Redldf888642011-12-03 14:54:30 +00004390TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004391 SourceLocation DeclLoc,
4392 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00004393 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004394 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4395
4396 // Most paths end in a failed conversion.
4397 ImplicitConversionSequence ICS;
4398 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4399
4400 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4401 QualType T2 = Init->getType();
4402
4403 // If the initializer is the address of an overloaded function, try
4404 // to resolve the overloaded function. If all goes well, T2 is the
4405 // type of the resulting function.
4406 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4407 DeclAccessPair Found;
4408 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4409 false, Found))
4410 T2 = Fn->getType();
4411 }
4412
4413 // Compute some basic properties of the types and the initializer.
4414 bool isRValRef = DeclType->isRValueReferenceType();
4415 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004416 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004417 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00004418 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004419 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004420 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004421 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004422
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004423
Sebastian Redld92badf2010-06-30 18:13:39 +00004424 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00004425 // A reference to type "cv1 T1" is initialized by an expression
4426 // of type "cv2 T2" as follows:
4427
Sebastian Redld92badf2010-06-30 18:13:39 +00004428 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00004429 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004430 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4431 // reference-compatible with "cv2 T2," or
4432 //
4433 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
Richard Smithce766292016-10-21 23:01:55 +00004434 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004435 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00004436 // When a parameter of reference type binds directly (8.5.3)
4437 // to an argument expression, the implicit conversion sequence
4438 // is the identity conversion, unless the argument expression
4439 // has a type that is a derived class of the parameter type,
4440 // in which case the implicit conversion sequence is a
4441 // derived-to-base Conversion (13.3.3.1).
4442 ICS.setStandard();
4443 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004444 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4445 : ObjCConversion? ICK_Compatible_Conversion
4446 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00004447 ICS.Standard.Third = ICK_Identity;
4448 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4449 ICS.Standard.setToType(0, T2);
4450 ICS.Standard.setToType(1, T1);
4451 ICS.Standard.setToType(2, T1);
4452 ICS.Standard.ReferenceBinding = true;
4453 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004454 ICS.Standard.IsLvalueReference = !isRValRef;
4455 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4456 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004457 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004458 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Craig Topperc3ec1492014-05-26 06:22:03 +00004459 ICS.Standard.CopyConstructor = nullptr;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004460 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004461
Sebastian Redld92badf2010-06-30 18:13:39 +00004462 // Nothing more to do: the inaccessibility/ambiguity check for
4463 // derived-to-base conversions is suppressed when we're
4464 // computing the implicit conversion sequence (C++
4465 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004466 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00004467 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004468
Sebastian Redld92badf2010-06-30 18:13:39 +00004469 // -- has a class type (i.e., T2 is a class type), where T1 is
4470 // not reference-related to T2, and can be implicitly
4471 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4472 // is reference-compatible with "cv3 T3" 92) (this
4473 // conversion is selected by enumerating the applicable
4474 // conversion functions (13.3.1.6) and choosing the best
4475 // one through overload resolution (13.3)),
4476 if (!SuppressUserConversions && T2->isRecordType() &&
Richard Smithdb0ac552015-12-18 22:40:25 +00004477 S.isCompleteType(DeclLoc, T2) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00004478 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00004479 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4480 Init, T2, /*AllowRvalues=*/false,
4481 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00004482 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004483 }
4484 }
4485
Sebastian Redld92badf2010-06-30 18:13:39 +00004486 // -- Otherwise, the reference shall be an lvalue reference to a
4487 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00004488 // shall be an rvalue reference.
Richard Smithce4f6082012-05-24 04:29:20 +00004489 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004490 return ICS;
4491
Douglas Gregorf143cd52011-01-24 16:14:37 +00004492 // -- If the initializer expression
4493 //
4494 // -- is an xvalue, class prvalue, array prvalue or function
John McCall31168b02011-06-15 23:02:42 +00004495 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Richard Smithce766292016-10-21 23:01:55 +00004496 if (RefRelationship == Sema::Ref_Compatible &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004497 (InitCategory.isXValue() ||
Richard Smithce766292016-10-21 23:01:55 +00004498 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4499 (InitCategory.isLValue() && T2->isFunctionType()))) {
Douglas Gregorf143cd52011-01-24 16:14:37 +00004500 ICS.setStandard();
4501 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004502 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004503 : ObjCConversion? ICK_Compatible_Conversion
4504 : ICK_Identity;
4505 ICS.Standard.Third = ICK_Identity;
4506 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4507 ICS.Standard.setToType(0, T2);
4508 ICS.Standard.setToType(1, T1);
4509 ICS.Standard.setToType(2, T1);
4510 ICS.Standard.ReferenceBinding = true;
4511 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4512 // binding unless we're binding to a class prvalue.
4513 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4514 // allow the use of rvalue references in C++98/03 for the benefit of
4515 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004516 ICS.Standard.DirectBinding =
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004517 S.getLangOpts().CPlusPlus11 ||
Richard Smithb94afe12014-07-14 19:54:05 +00004518 !(InitCategory.isPRValue() || T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00004519 ICS.Standard.IsLvalueReference = !isRValRef;
4520 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004521 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00004522 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004523 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Craig Topperc3ec1492014-05-26 06:22:03 +00004524 ICS.Standard.CopyConstructor = nullptr;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004525 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004526 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00004527 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004528
Douglas Gregorf143cd52011-01-24 16:14:37 +00004529 // -- has a class type (i.e., T2 is a class type), where T1 is not
4530 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004531 // an xvalue, class prvalue, or function lvalue of type
4532 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00004533 // "cv3 T3",
4534 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004535 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00004536 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004537 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004538 // class subobject).
4539 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
Richard Smithdb0ac552015-12-18 22:40:25 +00004540 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004541 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4542 Init, T2, /*AllowRvalues=*/true,
4543 AllowExplicit)) {
4544 // In the second case, if the reference is an rvalue reference
4545 // and the second standard conversion sequence of the
4546 // user-defined conversion sequence includes an lvalue-to-rvalue
4547 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004548 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004549 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4550 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4551
Douglas Gregor95273c32011-01-21 16:36:05 +00004552 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00004553 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004554
Richard Smith19172c42014-07-14 02:28:44 +00004555 // A temporary of function type cannot be created; don't even try.
4556 if (T1->isFunctionType())
4557 return ICS;
4558
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004559 // -- Otherwise, a temporary of type "cv1 T1" is created and
4560 // initialized from the initializer expression using the
4561 // rules for a non-reference copy initialization (8.5). The
4562 // reference is then bound to the temporary. If T1 is
4563 // reference-related to T2, cv1 must be the same
4564 // cv-qualification as, or greater cv-qualification than,
4565 // cv2; otherwise, the program is ill-formed.
4566 if (RefRelationship == Sema::Ref_Related) {
4567 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4568 // we would be reference-compatible or reference-compatible with
4569 // added qualification. But that wasn't the case, so the reference
4570 // initialization fails.
John McCall31168b02011-06-15 23:02:42 +00004571 //
4572 // Note that we only want to check address spaces and cvr-qualifiers here.
Andrey Bokhanko45d41322016-05-11 18:38:21 +00004573 // ObjC GC, lifetime and unaligned qualifiers aren't important.
John McCall31168b02011-06-15 23:02:42 +00004574 Qualifiers T1Quals = T1.getQualifiers();
4575 Qualifiers T2Quals = T2.getQualifiers();
4576 T1Quals.removeObjCGCAttr();
4577 T1Quals.removeObjCLifetime();
4578 T2Quals.removeObjCGCAttr();
4579 T2Quals.removeObjCLifetime();
Andrey Bokhanko45d41322016-05-11 18:38:21 +00004580 // MS compiler ignores __unaligned qualifier for references; do the same.
4581 T1Quals.removeUnaligned();
4582 T2Quals.removeUnaligned();
John McCall31168b02011-06-15 23:02:42 +00004583 if (!T1Quals.compatiblyIncludes(T2Quals))
4584 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004585 }
4586
4587 // If at least one of the types is a class type, the types are not
4588 // related, and we aren't allowed any user conversions, the
4589 // reference binding fails. This case is important for breaking
4590 // recursion, since TryImplicitConversion below will attempt to
4591 // create a temporary through the use of a copy constructor.
4592 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4593 (T1->isRecordType() || T2->isRecordType()))
4594 return ICS;
4595
Douglas Gregorcba72b12011-01-21 05:18:22 +00004596 // If T1 is reference-related to T2 and the reference is an rvalue
4597 // reference, the initializer expression shall not be an lvalue.
4598 if (RefRelationship >= Sema::Ref_Related &&
4599 isRValRef && Init->Classify(S.Context).isLValue())
4600 return ICS;
4601
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004602 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004603 // When a parameter of reference type is not bound directly to
4604 // an argument expression, the conversion sequence is the one
4605 // required to convert the argument expression to the
4606 // underlying type of the reference according to
4607 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4608 // to copy-initializing a temporary of the underlying type with
4609 // the argument expression. Any difference in top-level
4610 // cv-qualification is subsumed by the initialization itself
4611 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00004612 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4613 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004614 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004615 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004616 /*AllowObjCWritebackConversion=*/false,
4617 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004618
4619 // Of course, that's still a reference binding.
4620 if (ICS.isStandard()) {
4621 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004622 ICS.Standard.IsLvalueReference = !isRValRef;
Richard Smith19172c42014-07-14 02:28:44 +00004623 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004624 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004625 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004626 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004627 } else if (ICS.isUserDefined()) {
Richard Smith19172c42014-07-14 02:28:44 +00004628 const ReferenceType *LValRefType =
4629 ICS.UserDefined.ConversionFunction->getReturnType()
4630 ->getAs<LValueReferenceType>();
4631
4632 // C++ [over.ics.ref]p3:
4633 // Except for an implicit object parameter, for which see 13.3.1, a
4634 // standard conversion sequence cannot be formed if it requires [...]
4635 // binding an rvalue reference to an lvalue other than a function
4636 // lvalue.
4637 // Note that the function case is not possible here.
4638 if (DeclType->isRValueReferenceType() && LValRefType) {
4639 // FIXME: This is the wrong BadConversionSequence. The problem is binding
4640 // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4641 // reference to an rvalue!
4642 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4643 return ICS;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004644 }
Richard Smith19172c42014-07-14 02:28:44 +00004645
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004646 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004647 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
Richard Smith19172c42014-07-14 02:28:44 +00004648 ICS.UserDefined.After.BindsToFunctionLvalue = false;
4649 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004650 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4651 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004652 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00004653
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004654 return ICS;
4655}
4656
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004657static ImplicitConversionSequence
4658TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4659 bool SuppressUserConversions,
4660 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004661 bool AllowObjCWritebackConversion,
4662 bool AllowExplicit = false);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004663
4664/// TryListConversion - Try to copy-initialize a value of type ToType from the
4665/// initializer list From.
4666static ImplicitConversionSequence
4667TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4668 bool SuppressUserConversions,
4669 bool InOverloadResolution,
4670 bool AllowObjCWritebackConversion) {
4671 // C++11 [over.ics.list]p1:
4672 // When an argument is an initializer list, it is not an expression and
4673 // special rules apply for converting it to a parameter type.
4674
4675 ImplicitConversionSequence Result;
4676 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4677
Sebastian Redl09edce02012-01-23 22:09:39 +00004678 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004679 // initialized from init lists.
Richard Smithdb0ac552015-12-18 22:40:25 +00004680 if (!S.isCompleteType(From->getLocStart(), ToType))
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004681 return Result;
4682
Larisse Voufo19d08672015-01-27 18:47:05 +00004683 // Per DR1467:
4684 // If the parameter type is a class X and the initializer list has a single
4685 // element of type cv U, where U is X or a class derived from X, the
4686 // implicit conversion sequence is the one required to convert the element
4687 // to the parameter type.
4688 //
4689 // Otherwise, if the parameter type is a character array [... ]
4690 // and the initializer list has a single element that is an
4691 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4692 // implicit conversion sequence is the identity conversion.
4693 if (From->getNumInits() == 1) {
4694 if (ToType->isRecordType()) {
4695 QualType InitType = From->getInit(0)->getType();
4696 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00004697 S.IsDerivedFrom(From->getLocStart(), InitType, ToType))
Larisse Voufo19d08672015-01-27 18:47:05 +00004698 return TryCopyInitialization(S, From->getInit(0), ToType,
4699 SuppressUserConversions,
4700 InOverloadResolution,
4701 AllowObjCWritebackConversion);
4702 }
Richard Smith1bbaba82015-01-27 23:23:39 +00004703 // FIXME: Check the other conditions here: array of character type,
4704 // initializer is a string literal.
4705 if (ToType->isArrayType()) {
Larisse Voufo19d08672015-01-27 18:47:05 +00004706 InitializedEntity Entity =
4707 InitializedEntity::InitializeParameter(S.Context, ToType,
4708 /*Consumed=*/false);
4709 if (S.CanPerformCopyInitialization(Entity, From)) {
4710 Result.setStandard();
4711 Result.Standard.setAsIdentityConversion();
4712 Result.Standard.setFromType(ToType);
4713 Result.Standard.setAllToTypes(ToType);
4714 return Result;
4715 }
4716 }
4717 }
4718
4719 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004720 // C++11 [over.ics.list]p2:
4721 // If the parameter type is std::initializer_list<X> or "array of X" and
4722 // all the elements can be implicitly converted to X, the implicit
4723 // conversion sequence is the worst conversion necessary to convert an
4724 // element of the list to X.
Larisse Voufo19d08672015-01-27 18:47:05 +00004725 //
4726 // C++14 [over.ics.list]p3:
NAKAMURA Takumib01d86b2015-02-25 11:02:00 +00004727 // Otherwise, if the parameter type is "array of N X", if the initializer
Larisse Voufo19d08672015-01-27 18:47:05 +00004728 // list has exactly N elements or if it has fewer than N elements and X is
4729 // default-constructible, and if all the elements of the initializer list
4730 // can be implicitly converted to X, the implicit conversion sequence is
4731 // the worst conversion necessary to convert an element of the list to X.
Richard Smith1bbaba82015-01-27 23:23:39 +00004732 //
4733 // FIXME: We're missing a lot of these checks.
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004734 bool toStdInitializerList = false;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004735 QualType X;
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004736 if (ToType->isArrayType())
Richard Smith0db1ea52012-12-09 06:48:56 +00004737 X = S.Context.getAsArrayType(ToType)->getElementType();
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004738 else
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004739 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004740 if (!X.isNull()) {
4741 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4742 Expr *Init = From->getInit(i);
4743 ImplicitConversionSequence ICS =
4744 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4745 InOverloadResolution,
4746 AllowObjCWritebackConversion);
4747 // If a single element isn't convertible, fail.
4748 if (ICS.isBad()) {
4749 Result = ICS;
4750 break;
4751 }
4752 // Otherwise, look for the worst conversion.
4753 if (Result.isBad() ||
Richard Smith0f59cb32015-12-18 21:45:41 +00004754 CompareImplicitConversionSequences(S, From->getLocStart(), ICS,
4755 Result) ==
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004756 ImplicitConversionSequence::Worse)
4757 Result = ICS;
4758 }
Douglas Gregor0f5c1c02012-04-04 23:09:20 +00004759
4760 // For an empty list, we won't have computed any conversion sequence.
4761 // Introduce the identity conversion sequence.
4762 if (From->getNumInits() == 0) {
4763 Result.setStandard();
4764 Result.Standard.setAsIdentityConversion();
4765 Result.Standard.setFromType(ToType);
4766 Result.Standard.setAllToTypes(ToType);
4767 }
4768
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004769 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004770 return Result;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004771 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004772
Larisse Voufo19d08672015-01-27 18:47:05 +00004773 // C++14 [over.ics.list]p4:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004774 // C++11 [over.ics.list]p3:
4775 // Otherwise, if the parameter is a non-aggregate class X and overload
4776 // resolution chooses a single best constructor [...] the implicit
4777 // conversion sequence is a user-defined conversion sequence. If multiple
4778 // constructors are viable but none is better than the others, the
4779 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004780 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4781 // This function can deal with initializer lists.
Richard Smitha93f1022013-09-06 22:30:28 +00004782 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4783 /*AllowExplicit=*/false,
4784 InOverloadResolution, /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004785 AllowObjCWritebackConversion,
4786 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004787 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004788
Larisse Voufo19d08672015-01-27 18:47:05 +00004789 // C++14 [over.ics.list]p5:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004790 // C++11 [over.ics.list]p4:
4791 // Otherwise, if the parameter has an aggregate type which can be
4792 // initialized from the initializer list [...] the implicit conversion
4793 // sequence is a user-defined conversion sequence.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004794 if (ToType->isAggregateType()) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004795 // Type is an aggregate, argument is an init list. At this point it comes
4796 // down to checking whether the initialization works.
4797 // FIXME: Find out whether this parameter is consumed or not.
Richard Smithb8c0f552016-12-09 18:49:13 +00004798 // FIXME: Expose SemaInit's aggregate initialization code so that we don't
4799 // need to call into the initialization code here; overload resolution
4800 // should not be doing that.
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004801 InitializedEntity Entity =
4802 InitializedEntity::InitializeParameter(S.Context, ToType,
4803 /*Consumed=*/false);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004804 if (S.CanPerformCopyInitialization(Entity, From)) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004805 Result.setUserDefined();
4806 Result.UserDefined.Before.setAsIdentityConversion();
4807 // Initializer lists don't have a type.
4808 Result.UserDefined.Before.setFromType(QualType());
4809 Result.UserDefined.Before.setAllToTypes(QualType());
4810
4811 Result.UserDefined.After.setAsIdentityConversion();
4812 Result.UserDefined.After.setFromType(ToType);
4813 Result.UserDefined.After.setAllToTypes(ToType);
Craig Topperc3ec1492014-05-26 06:22:03 +00004814 Result.UserDefined.ConversionFunction = nullptr;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004815 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004816 return Result;
4817 }
4818
Larisse Voufo19d08672015-01-27 18:47:05 +00004819 // C++14 [over.ics.list]p6:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004820 // C++11 [over.ics.list]p5:
4821 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redldf888642011-12-03 14:54:30 +00004822 if (ToType->isReferenceType()) {
4823 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4824 // mention initializer lists in any way. So we go by what list-
4825 // initialization would do and try to extrapolate from that.
4826
4827 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4828
4829 // If the initializer list has a single element that is reference-related
4830 // to the parameter type, we initialize the reference from that.
4831 if (From->getNumInits() == 1) {
4832 Expr *Init = From->getInit(0);
4833
4834 QualType T2 = Init->getType();
4835
4836 // If the initializer is the address of an overloaded function, try
4837 // to resolve the overloaded function. If all goes well, T2 is the
4838 // type of the resulting function.
4839 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4840 DeclAccessPair Found;
4841 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4842 Init, ToType, false, Found))
4843 T2 = Fn->getType();
4844 }
4845
4846 // Compute some basic properties of the types and the initializer.
4847 bool dummy1 = false;
4848 bool dummy2 = false;
4849 bool dummy3 = false;
4850 Sema::ReferenceCompareResult RefRelationship
4851 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4852 dummy2, dummy3);
4853
Richard Smith4d2bbd72013-09-06 01:22:42 +00004854 if (RefRelationship >= Sema::Ref_Related) {
Richard Smitha93f1022013-09-06 22:30:28 +00004855 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4856 SuppressUserConversions,
4857 /*AllowExplicit=*/false);
Richard Smith4d2bbd72013-09-06 01:22:42 +00004858 }
Sebastian Redldf888642011-12-03 14:54:30 +00004859 }
4860
4861 // Otherwise, we bind the reference to a temporary created from the
4862 // initializer list.
4863 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4864 InOverloadResolution,
4865 AllowObjCWritebackConversion);
4866 if (Result.isFailure())
4867 return Result;
4868 assert(!Result.isEllipsis() &&
4869 "Sub-initialization cannot result in ellipsis conversion.");
4870
4871 // Can we even bind to a temporary?
4872 if (ToType->isRValueReferenceType() ||
4873 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4874 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4875 Result.UserDefined.After;
4876 SCS.ReferenceBinding = true;
4877 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4878 SCS.BindsToRvalue = true;
4879 SCS.BindsToFunctionLvalue = false;
4880 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4881 SCS.ObjCLifetimeConversionBinding = false;
4882 } else
4883 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4884 From, ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004885 return Result;
Sebastian Redldf888642011-12-03 14:54:30 +00004886 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004887
Larisse Voufo19d08672015-01-27 18:47:05 +00004888 // C++14 [over.ics.list]p7:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004889 // C++11 [over.ics.list]p6:
4890 // Otherwise, if the parameter type is not a class:
4891 if (!ToType->isRecordType()) {
Larisse Voufo19d08672015-01-27 18:47:05 +00004892 // - if the initializer list has one element that is not itself an
4893 // initializer list, the implicit conversion sequence is the one
4894 // required to convert the element to the parameter type.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004895 unsigned NumInits = From->getNumInits();
Richard Smith1bbaba82015-01-27 23:23:39 +00004896 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004897 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4898 SuppressUserConversions,
4899 InOverloadResolution,
4900 AllowObjCWritebackConversion);
4901 // - if the initializer list has no elements, the implicit conversion
4902 // sequence is the identity conversion.
4903 else if (NumInits == 0) {
4904 Result.setStandard();
4905 Result.Standard.setAsIdentityConversion();
John McCallb73bc9a2012-04-04 02:40:27 +00004906 Result.Standard.setFromType(ToType);
4907 Result.Standard.setAllToTypes(ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004908 }
4909 return Result;
4910 }
4911
Larisse Voufo19d08672015-01-27 18:47:05 +00004912 // C++14 [over.ics.list]p8:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004913 // C++11 [over.ics.list]p7:
4914 // In all cases other than those enumerated above, no conversion is possible
4915 return Result;
4916}
4917
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004918/// TryCopyInitialization - Try to copy-initialize a value of type
4919/// ToType from the expression From. Return the implicit conversion
4920/// sequence required to pass this argument, which may be a bad
4921/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00004922/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00004923/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004924static ImplicitConversionSequence
4925TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004926 bool SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004927 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004928 bool AllowObjCWritebackConversion,
4929 bool AllowExplicit) {
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004930 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4931 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4932 InOverloadResolution,AllowObjCWritebackConversion);
4933
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004934 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004935 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004936 /*FIXME:*/From->getLocStart(),
4937 SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004938 AllowExplicit);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004939
John McCall5c32be02010-08-24 20:38:10 +00004940 return TryImplicitConversion(S, From, ToType,
4941 SuppressUserConversions,
4942 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004943 InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00004944 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004945 AllowObjCWritebackConversion,
4946 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004947}
4948
Anna Zaks1b068122011-07-28 19:46:48 +00004949static bool TryCopyInitialization(const CanQualType FromQTy,
4950 const CanQualType ToQTy,
4951 Sema &S,
4952 SourceLocation Loc,
4953 ExprValueKind FromVK) {
4954 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4955 ImplicitConversionSequence ICS =
4956 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4957
4958 return !ICS.isBad();
4959}
4960
Douglas Gregor436424c2008-11-18 23:14:02 +00004961/// TryObjectArgumentInitialization - Try to initialize the object
4962/// parameter of the given member function (@c Method) from the
4963/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00004964static ImplicitConversionSequence
Richard Smith0f59cb32015-12-18 21:45:41 +00004965TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004966 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00004967 CXXMethodDecl *Method,
4968 CXXRecordDecl *ActingContext) {
4969 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00004970 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4971 // const volatile object.
4972 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4973 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00004974 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00004975
4976 // Set up the conversion sequence as a "bad" conversion, to allow us
4977 // to exit early.
4978 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00004979
4980 // We need to have an object of class type.
Douglas Gregor02824322011-01-26 19:30:28 +00004981 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004982 FromType = PT->getPointeeType();
4983
Douglas Gregor02824322011-01-26 19:30:28 +00004984 // When we had a pointer, it's implicitly dereferenced, so we
4985 // better have an lvalue.
4986 assert(FromClassification.isLValue());
4987 }
4988
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004989 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00004990
Douglas Gregor02824322011-01-26 19:30:28 +00004991 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004992 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00004993 // parameter is
4994 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004995 // - "lvalue reference to cv X" for functions declared without a
4996 // ref-qualifier or with the & ref-qualifier
4997 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00004998 // ref-qualifier
4999 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005000 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00005001 // cv-qualification on the member function declaration.
5002 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005003 // However, when finding an implicit conversion sequence for the argument, we
Richard Smith122f88d2016-12-06 23:52:28 +00005004 // are not allowed to perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00005005 // (C++ [over.match.funcs]p5). We perform a simplified version of
5006 // reference binding here, that allows class rvalues to bind to
5007 // non-constant references.
5008
Douglas Gregor02824322011-01-26 19:30:28 +00005009 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00005010 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005011 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005012 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00005013 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00005014 ICS.setBad(BadConversionSequence::bad_qualifiers,
Richard Smith03c66d32013-01-26 02:07:32 +00005015 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00005016 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00005017 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005018
5019 // Check that we have either the same type or a derived type. It
5020 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00005021 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00005022 ImplicitConversionKind SecondKind;
5023 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5024 SecondKind = ICK_Identity;
Richard Smith0f59cb32015-12-18 21:45:41 +00005025 } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00005026 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00005027 else {
John McCall65eb8792010-02-25 01:37:24 +00005028 ICS.setBad(BadConversionSequence::unrelated_class,
5029 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00005030 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00005031 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005032
Douglas Gregor02824322011-01-26 19:30:28 +00005033 // Check the ref-qualifier.
5034 switch (Method->getRefQualifier()) {
5035 case RQ_None:
5036 // Do nothing; we don't care about lvalueness or rvalueness.
5037 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005038
Douglas Gregor02824322011-01-26 19:30:28 +00005039 case RQ_LValue:
5040 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
5041 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005042 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00005043 ImplicitParamType);
5044 return ICS;
5045 }
5046 break;
5047
5048 case RQ_RValue:
5049 if (!FromClassification.isRValue()) {
5050 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005051 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00005052 ImplicitParamType);
5053 return ICS;
5054 }
5055 break;
5056 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005057
Douglas Gregor436424c2008-11-18 23:14:02 +00005058 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00005059 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00005060 ICS.Standard.setAsIdentityConversion();
5061 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00005062 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00005063 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00005064 ICS.Standard.ReferenceBinding = true;
5065 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005066 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00005067 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00005068 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5069 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5070 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00005071 return ICS;
5072}
5073
5074/// PerformObjectArgumentInitialization - Perform initialization of
5075/// the implicit object parameter for the given Method with the given
5076/// expression.
John Wiegley01296292011-04-08 18:41:53 +00005077ExprResult
5078Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005079 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00005080 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00005081 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005082 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00005083 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005084 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00005085
Douglas Gregor02824322011-01-26 19:30:28 +00005086 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005087 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005088 FromRecordType = PT->getPointeeType();
5089 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00005090 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005091 } else {
5092 FromRecordType = From->getType();
5093 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00005094 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005095 }
5096
John McCall6e9f8f62009-12-03 04:06:58 +00005097 // Note that we always use the true parent context when performing
5098 // the actual argument initialization.
Nico Weberb58e51c2014-11-19 05:21:39 +00005099 ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
Richard Smith0f59cb32015-12-18 21:45:41 +00005100 *this, From->getLocStart(), From->getType(), FromClassification, Method,
5101 Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005102 if (ICS.isBad()) {
5103 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
5104 Qualifiers FromQs = FromRecordType.getQualifiers();
5105 Qualifiers ToQs = DestType.getQualifiers();
5106 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5107 if (CVR) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005108 Diag(From->getLocStart(),
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005109 diag::err_member_function_call_bad_cvr)
5110 << Method->getDeclName() << FromRecordType << (CVR - 1)
5111 << From->getSourceRange();
5112 Diag(Method->getLocation(), diag::note_previous_decl)
5113 << Method->getDeclName();
John Wiegley01296292011-04-08 18:41:53 +00005114 return ExprError();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005115 }
5116 }
5117
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005118 return Diag(From->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00005119 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005120 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005121 }
Mike Stump11289f42009-09-09 15:08:12 +00005122
John Wiegley01296292011-04-08 18:41:53 +00005123 if (ICS.Standard.Second == ICK_Derived_To_Base) {
5124 ExprResult FromRes =
5125 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5126 if (FromRes.isInvalid())
5127 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005128 From = FromRes.get();
John Wiegley01296292011-04-08 18:41:53 +00005129 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005130
Douglas Gregorcc3f3252010-03-03 23:55:11 +00005131 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley01296292011-04-08 18:41:53 +00005132 From = ImpCastExprToType(From, DestType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005133 From->getValueKind()).get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005134 return From;
Douglas Gregor436424c2008-11-18 23:14:02 +00005135}
5136
Douglas Gregor5fb53972009-01-14 15:45:31 +00005137/// TryContextuallyConvertToBool - Attempt to contextually convert the
5138/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00005139static ImplicitConversionSequence
5140TryContextuallyConvertToBool(Sema &S, Expr *From) {
John McCall5c32be02010-08-24 20:38:10 +00005141 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00005142 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00005143 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00005144 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00005145 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005146 /*AllowObjCWritebackConversion=*/false,
5147 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00005148}
5149
5150/// PerformContextuallyConvertToBool - Perform a contextual conversion
5151/// of the expression From to bool (C++0x [conv]p3).
John Wiegley01296292011-04-08 18:41:53 +00005152ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00005153 if (checkPlaceholderForOverload(*this, From))
5154 return ExprError();
5155
John McCall5c32be02010-08-24 20:38:10 +00005156 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00005157 if (!ICS.isBad())
5158 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005159
Fariborz Jahanian76197412009-11-18 18:26:29 +00005160 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005161 return Diag(From->getLocStart(),
John McCall0009fcc2011-04-26 20:42:42 +00005162 diag::err_typecheck_bool_condition)
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00005163 << From->getType() << From->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00005164 return ExprError();
Douglas Gregor5fb53972009-01-14 15:45:31 +00005165}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005166
Richard Smithf8379a02012-01-18 23:55:52 +00005167/// Check that the specified conversion is permitted in a converted constant
5168/// expression, according to C++11 [expr.const]p3. Return true if the conversion
5169/// is acceptable.
5170static bool CheckConvertedConstantConversions(Sema &S,
5171 StandardConversionSequence &SCS) {
5172 // Since we know that the target type is an integral or unscoped enumeration
5173 // type, most conversion kinds are impossible. All possible First and Third
5174 // conversions are fine.
5175 switch (SCS.Second) {
5176 case ICK_Identity:
Richard Smith3c4f8d22016-10-16 17:54:23 +00005177 case ICK_Function_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005178 case ICK_Integral_Promotion:
Richard Smith410cc892014-11-26 03:26:53 +00005179 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
Richard Smithf8379a02012-01-18 23:55:52 +00005180 return true;
5181
5182 case ICK_Boolean_Conversion:
Richard Smithca24ed42012-09-13 22:00:12 +00005183 // Conversion from an integral or unscoped enumeration type to bool is
Richard Smith410cc892014-11-26 03:26:53 +00005184 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5185 // conversion, so we allow it in a converted constant expression.
5186 //
5187 // FIXME: Per core issue 1407, we should not allow this, but that breaks
5188 // a lot of popular code. We should at least add a warning for this
5189 // (non-conforming) extension.
Richard Smithca24ed42012-09-13 22:00:12 +00005190 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5191 SCS.getToType(2)->isBooleanType();
5192
Richard Smith410cc892014-11-26 03:26:53 +00005193 case ICK_Pointer_Conversion:
5194 case ICK_Pointer_Member:
5195 // C++1z: null pointer conversions and null member pointer conversions are
5196 // only permitted if the source type is std::nullptr_t.
5197 return SCS.getFromType()->isNullPtrType();
5198
5199 case ICK_Floating_Promotion:
5200 case ICK_Complex_Promotion:
5201 case ICK_Floating_Conversion:
5202 case ICK_Complex_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005203 case ICK_Floating_Integral:
Richard Smith410cc892014-11-26 03:26:53 +00005204 case ICK_Compatible_Conversion:
5205 case ICK_Derived_To_Base:
5206 case ICK_Vector_Conversion:
5207 case ICK_Vector_Splat:
Richard Smithf8379a02012-01-18 23:55:52 +00005208 case ICK_Complex_Real:
Richard Smith410cc892014-11-26 03:26:53 +00005209 case ICK_Block_Pointer_Conversion:
5210 case ICK_TransparentUnionConversion:
5211 case ICK_Writeback_Conversion:
5212 case ICK_Zero_Event_Conversion:
George Burgess IV45461812015-10-11 20:13:20 +00005213 case ICK_C_Only_Conversion:
George Burgess IV2099b542016-09-02 22:59:57 +00005214 case ICK_Incompatible_Pointer_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005215 return false;
5216
5217 case ICK_Lvalue_To_Rvalue:
5218 case ICK_Array_To_Pointer:
5219 case ICK_Function_To_Pointer:
Richard Smith410cc892014-11-26 03:26:53 +00005220 llvm_unreachable("found a first conversion kind in Second");
5221
Richard Smithf8379a02012-01-18 23:55:52 +00005222 case ICK_Qualification:
Richard Smith410cc892014-11-26 03:26:53 +00005223 llvm_unreachable("found a third conversion kind in Second");
Richard Smithf8379a02012-01-18 23:55:52 +00005224
5225 case ICK_Num_Conversion_Kinds:
5226 break;
5227 }
5228
5229 llvm_unreachable("unknown conversion kind");
5230}
5231
5232/// CheckConvertedConstantExpression - Check that the expression From is a
5233/// converted constant expression of type T, perform the conversion and produce
5234/// the converted expression, per C++11 [expr.const]p3.
Richard Smith410cc892014-11-26 03:26:53 +00005235static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5236 QualType T, APValue &Value,
5237 Sema::CCEKind CCE,
5238 bool RequireInt) {
5239 assert(S.getLangOpts().CPlusPlus11 &&
5240 "converted constant expression outside C++11");
Richard Smithf8379a02012-01-18 23:55:52 +00005241
Richard Smith410cc892014-11-26 03:26:53 +00005242 if (checkPlaceholderForOverload(S, From))
Richard Smithf8379a02012-01-18 23:55:52 +00005243 return ExprError();
5244
Richard Smith410cc892014-11-26 03:26:53 +00005245 // C++1z [expr.const]p3:
5246 // A converted constant expression of type T is an expression,
5247 // implicitly converted to type T, where the converted
5248 // expression is a constant expression and the implicit conversion
5249 // sequence contains only [... list of conversions ...].
Ismail Pazarbasi4a007742016-09-07 18:24:54 +00005250 // C++1z [stmt.if]p2:
5251 // If the if statement is of the form if constexpr, the value of the
5252 // condition shall be a contextually converted constant expression of type
5253 // bool.
Richard Smithf8379a02012-01-18 23:55:52 +00005254 ImplicitConversionSequence ICS =
Ismail Pazarbasi4a007742016-09-07 18:24:54 +00005255 CCE == Sema::CCEK_ConstexprIf
5256 ? TryContextuallyConvertToBool(S, From)
5257 : TryCopyInitialization(S, From, T,
5258 /*SuppressUserConversions=*/false,
5259 /*InOverloadResolution=*/false,
5260 /*AllowObjcWritebackConversion=*/false,
5261 /*AllowExplicit=*/false);
Craig Topperc3ec1492014-05-26 06:22:03 +00005262 StandardConversionSequence *SCS = nullptr;
Richard Smithf8379a02012-01-18 23:55:52 +00005263 switch (ICS.getKind()) {
5264 case ImplicitConversionSequence::StandardConversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005265 SCS = &ICS.Standard;
5266 break;
5267 case ImplicitConversionSequence::UserDefinedConversion:
Richard Smith410cc892014-11-26 03:26:53 +00005268 // We are converting to a non-class type, so the Before sequence
5269 // must be trivial.
Richard Smithf8379a02012-01-18 23:55:52 +00005270 SCS = &ICS.UserDefined.After;
5271 break;
5272 case ImplicitConversionSequence::AmbiguousConversion:
5273 case ImplicitConversionSequence::BadConversion:
Richard Smith410cc892014-11-26 03:26:53 +00005274 if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5275 return S.Diag(From->getLocStart(),
5276 diag::err_typecheck_converted_constant_expression)
5277 << From->getType() << From->getSourceRange() << T;
Richard Smithf8379a02012-01-18 23:55:52 +00005278 return ExprError();
5279
5280 case ImplicitConversionSequence::EllipsisConversion:
5281 llvm_unreachable("ellipsis conversion in converted constant expression");
5282 }
5283
Richard Smith410cc892014-11-26 03:26:53 +00005284 // Check that we would only use permitted conversions.
5285 if (!CheckConvertedConstantConversions(S, *SCS)) {
5286 return S.Diag(From->getLocStart(),
5287 diag::err_typecheck_converted_constant_expression_disallowed)
5288 << From->getType() << From->getSourceRange() << T;
5289 }
5290 // [...] and where the reference binding (if any) binds directly.
5291 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5292 return S.Diag(From->getLocStart(),
5293 diag::err_typecheck_converted_constant_expression_indirect)
5294 << From->getType() << From->getSourceRange() << T;
5295 }
5296
5297 ExprResult Result =
5298 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
Richard Smithf8379a02012-01-18 23:55:52 +00005299 if (Result.isInvalid())
5300 return Result;
5301
5302 // Check for a narrowing implicit conversion.
5303 APValue PreNarrowingValue;
Richard Smith5614ca72012-03-23 23:55:39 +00005304 QualType PreNarrowingType;
Richard Smith410cc892014-11-26 03:26:53 +00005305 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
Richard Smith5614ca72012-03-23 23:55:39 +00005306 PreNarrowingType)) {
Richard Smith52e624f2016-12-21 21:42:57 +00005307 case NK_Dependent_Narrowing:
5308 // Implicit conversion to a narrower type, but the expression is
5309 // value-dependent so we can't tell whether it's actually narrowing.
Richard Smithf8379a02012-01-18 23:55:52 +00005310 case NK_Variable_Narrowing:
5311 // Implicit conversion to a narrower type, and the value is not a constant
5312 // expression. We'll diagnose this in a moment.
5313 case NK_Not_Narrowing:
5314 break;
5315
5316 case NK_Constant_Narrowing:
Richard Smith410cc892014-11-26 03:26:53 +00005317 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00005318 << CCE << /*Constant*/1
Richard Smith410cc892014-11-26 03:26:53 +00005319 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
Richard Smithf8379a02012-01-18 23:55:52 +00005320 break;
5321
5322 case NK_Type_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*/0 << From->getType() << T;
5325 break;
5326 }
5327
Richard Smith52e624f2016-12-21 21:42:57 +00005328 if (Result.get()->isValueDependent()) {
5329 Value = APValue();
5330 return Result;
5331 }
5332
Richard Smithf8379a02012-01-18 23:55:52 +00005333 // Check the expression is a constant expression.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005334 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithf8379a02012-01-18 23:55:52 +00005335 Expr::EvalResult Eval;
5336 Eval.Diag = &Notes;
5337
Richard Smith410cc892014-11-26 03:26:53 +00005338 if ((T->isReferenceType()
5339 ? !Result.get()->EvaluateAsLValue(Eval, S.Context)
5340 : !Result.get()->EvaluateAsRValue(Eval, S.Context)) ||
5341 (RequireInt && !Eval.Val.isInt())) {
Richard Smithf8379a02012-01-18 23:55:52 +00005342 // The expression can't be folded, so we can't keep it at this position in
5343 // the AST.
5344 Result = ExprError();
Richard Smith911e1422012-01-30 22:27:01 +00005345 } else {
Richard Smith410cc892014-11-26 03:26:53 +00005346 Value = Eval.Val;
Richard Smith911e1422012-01-30 22:27:01 +00005347
5348 if (Notes.empty()) {
5349 // It's a constant expression.
5350 return Result;
5351 }
Richard Smithf8379a02012-01-18 23:55:52 +00005352 }
5353
5354 // It's not a constant expression. Produce an appropriate diagnostic.
5355 if (Notes.size() == 1 &&
5356 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
Richard Smith410cc892014-11-26 03:26:53 +00005357 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
Richard Smithf8379a02012-01-18 23:55:52 +00005358 else {
Richard Smith410cc892014-11-26 03:26:53 +00005359 S.Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smithf8379a02012-01-18 23:55:52 +00005360 << CCE << From->getSourceRange();
5361 for (unsigned I = 0; I < Notes.size(); ++I)
Richard Smith410cc892014-11-26 03:26:53 +00005362 S.Diag(Notes[I].first, Notes[I].second);
Richard Smithf8379a02012-01-18 23:55:52 +00005363 }
Richard Smith410cc892014-11-26 03:26:53 +00005364 return ExprError();
Richard Smithf8379a02012-01-18 23:55:52 +00005365}
5366
Richard Smith410cc892014-11-26 03:26:53 +00005367ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5368 APValue &Value, CCEKind CCE) {
5369 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5370}
5371
5372ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5373 llvm::APSInt &Value,
5374 CCEKind CCE) {
5375 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5376
5377 APValue V;
5378 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5379 if (!R.isInvalid())
5380 Value = V.getInt();
5381 return R;
5382}
5383
5384
John McCallfec112d2011-09-09 06:11:02 +00005385/// dropPointerConversions - If the given standard conversion sequence
5386/// involves any pointer conversions, remove them. This may change
5387/// the result type of the conversion sequence.
5388static void dropPointerConversion(StandardConversionSequence &SCS) {
5389 if (SCS.Second == ICK_Pointer_Conversion) {
5390 SCS.Second = ICK_Identity;
5391 SCS.Third = ICK_Identity;
5392 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5393 }
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005394}
John McCall5c32be02010-08-24 20:38:10 +00005395
John McCallfec112d2011-09-09 06:11:02 +00005396/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5397/// convert the expression From to an Objective-C pointer type.
5398static ImplicitConversionSequence
5399TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5400 // Do an implicit conversion to 'id'.
5401 QualType Ty = S.Context.getObjCIdType();
5402 ImplicitConversionSequence ICS
5403 = TryImplicitConversion(S, From, Ty,
5404 // FIXME: Are these flags correct?
5405 /*SuppressUserConversions=*/false,
5406 /*AllowExplicit=*/true,
5407 /*InOverloadResolution=*/false,
5408 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005409 /*AllowObjCWritebackConversion=*/false,
5410 /*AllowObjCConversionOnExplicit=*/true);
John McCallfec112d2011-09-09 06:11:02 +00005411
5412 // Strip off any final conversions to 'id'.
5413 switch (ICS.getKind()) {
5414 case ImplicitConversionSequence::BadConversion:
5415 case ImplicitConversionSequence::AmbiguousConversion:
5416 case ImplicitConversionSequence::EllipsisConversion:
5417 break;
5418
5419 case ImplicitConversionSequence::UserDefinedConversion:
5420 dropPointerConversion(ICS.UserDefined.After);
5421 break;
5422
5423 case ImplicitConversionSequence::StandardConversion:
5424 dropPointerConversion(ICS.Standard);
5425 break;
5426 }
5427
5428 return ICS;
5429}
5430
5431/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5432/// conversion of the expression From to an Objective-C pointer type.
Richard Smithe15a3702016-10-06 23:12:58 +00005433/// Returns a valid but null ExprResult if no conversion sequence exists.
John McCallfec112d2011-09-09 06:11:02 +00005434ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00005435 if (checkPlaceholderForOverload(*this, From))
5436 return ExprError();
5437
John McCall8b07ec22010-05-15 11:32:37 +00005438 QualType Ty = Context.getObjCIdType();
John McCallfec112d2011-09-09 06:11:02 +00005439 ImplicitConversionSequence ICS =
5440 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005441 if (!ICS.isBad())
5442 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
Richard Smithe15a3702016-10-06 23:12:58 +00005443 return ExprResult();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005444}
Douglas Gregor5fb53972009-01-14 15:45:31 +00005445
Richard Smith8dd34252012-02-04 07:07:42 +00005446/// Determine whether the provided type is an integral type, or an enumeration
5447/// type of a permitted flavor.
Richard Smithccc11812013-05-21 19:05:48 +00005448bool Sema::ICEConvertDiagnoser::match(QualType T) {
5449 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5450 : T->isIntegralOrUnscopedEnumerationType();
Richard Smith8dd34252012-02-04 07:07:42 +00005451}
5452
Larisse Voufo236bec22013-06-10 06:50:24 +00005453static ExprResult
5454diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5455 Sema::ContextualImplicitConverter &Converter,
5456 QualType T, UnresolvedSetImpl &ViableConversions) {
5457
5458 if (Converter.Suppress)
5459 return ExprError();
5460
5461 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5462 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5463 CXXConversionDecl *Conv =
5464 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5465 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5466 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5467 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005468 return From;
Larisse Voufo236bec22013-06-10 06:50:24 +00005469}
5470
5471static bool
5472diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5473 Sema::ContextualImplicitConverter &Converter,
5474 QualType T, bool HadMultipleCandidates,
5475 UnresolvedSetImpl &ExplicitConversions) {
5476 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5477 DeclAccessPair Found = ExplicitConversions[0];
5478 CXXConversionDecl *Conversion =
5479 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5480
5481 // The user probably meant to invoke the given explicit
5482 // conversion; use it.
5483 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5484 std::string TypeStr;
5485 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5486
5487 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5488 << FixItHint::CreateInsertion(From->getLocStart(),
5489 "static_cast<" + TypeStr + ">(")
5490 << FixItHint::CreateInsertion(
Alp Tokerb6cc5922014-05-03 03:45:55 +00005491 SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
Larisse Voufo236bec22013-06-10 06:50:24 +00005492 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5493
5494 // If we aren't in a SFINAE context, build a call to the
5495 // explicit conversion function.
5496 if (SemaRef.isSFINAEContext())
5497 return true;
5498
Craig Topperc3ec1492014-05-26 06:22:03 +00005499 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
Larisse Voufo236bec22013-06-10 06:50:24 +00005500 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5501 HadMultipleCandidates);
5502 if (Result.isInvalid())
5503 return true;
5504 // Record usage of conversion in an implicit cast.
5505 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005506 CK_UserDefinedConversion, Result.get(),
5507 nullptr, Result.get()->getValueKind());
Larisse Voufo236bec22013-06-10 06:50:24 +00005508 }
5509 return false;
5510}
5511
5512static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5513 Sema::ContextualImplicitConverter &Converter,
5514 QualType T, bool HadMultipleCandidates,
5515 DeclAccessPair &Found) {
5516 CXXConversionDecl *Conversion =
5517 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00005518 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
Larisse Voufo236bec22013-06-10 06:50:24 +00005519
5520 QualType ToType = Conversion->getConversionType().getNonReferenceType();
5521 if (!Converter.SuppressConversion) {
5522 if (SemaRef.isSFINAEContext())
5523 return true;
5524
5525 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5526 << From->getSourceRange();
5527 }
5528
5529 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5530 HadMultipleCandidates);
5531 if (Result.isInvalid())
5532 return true;
5533 // Record usage of conversion in an implicit cast.
5534 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005535 CK_UserDefinedConversion, Result.get(),
5536 nullptr, Result.get()->getValueKind());
Larisse Voufo236bec22013-06-10 06:50:24 +00005537 return false;
5538}
5539
5540static ExprResult finishContextualImplicitConversion(
5541 Sema &SemaRef, SourceLocation Loc, Expr *From,
5542 Sema::ContextualImplicitConverter &Converter) {
5543 if (!Converter.match(From->getType()) && !Converter.Suppress)
5544 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5545 << From->getSourceRange();
5546
5547 return SemaRef.DefaultLvalueConversion(From);
5548}
5549
5550static void
5551collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5552 UnresolvedSetImpl &ViableConversions,
5553 OverloadCandidateSet &CandidateSet) {
5554 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5555 DeclAccessPair FoundDecl = ViableConversions[I];
5556 NamedDecl *D = FoundDecl.getDecl();
5557 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5558 if (isa<UsingShadowDecl>(D))
5559 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5560
5561 CXXConversionDecl *Conv;
5562 FunctionTemplateDecl *ConvTemplate;
5563 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5564 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5565 else
5566 Conv = cast<CXXConversionDecl>(D);
5567
5568 if (ConvTemplate)
5569 SemaRef.AddTemplateConversionCandidate(
Douglas Gregor4b60a152013-11-07 22:34:54 +00005570 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5571 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005572 else
5573 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005574 ToType, CandidateSet,
5575 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005576 }
5577}
5578
Richard Smithccc11812013-05-21 19:05:48 +00005579/// \brief Attempt to convert the given expression to a type which is accepted
5580/// by the given converter.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005581///
Richard Smithccc11812013-05-21 19:05:48 +00005582/// This routine will attempt to convert an expression of class type to a
5583/// type accepted by the specified converter. In C++11 and before, the class
5584/// must have a single non-explicit conversion function converting to a matching
5585/// type. In C++1y, there can be multiple such conversion functions, but only
5586/// one target type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005587///
Douglas Gregor4799d032010-06-30 00:20:43 +00005588/// \param Loc The source location of the construct that requires the
5589/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005590///
James Dennett18348b62012-06-22 08:52:37 +00005591/// \param From The expression we're converting from.
Douglas Gregor4799d032010-06-30 00:20:43 +00005592///
Richard Smithccc11812013-05-21 19:05:48 +00005593/// \param Converter Used to control and diagnose the conversion process.
Richard Smith8dd34252012-02-04 07:07:42 +00005594///
Douglas Gregor4799d032010-06-30 00:20:43 +00005595/// \returns The expression, converted to an integral or enumeration type if
5596/// successful.
Richard Smithccc11812013-05-21 19:05:48 +00005597ExprResult Sema::PerformContextualImplicitConversion(
5598 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005599 // We can't perform any more checking for type-dependent expressions.
5600 if (From->isTypeDependent())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005601 return From;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005602
Eli Friedman1da70392012-01-26 00:26:18 +00005603 // Process placeholders immediately.
5604 if (From->hasPlaceholderType()) {
5605 ExprResult result = CheckPlaceholderExpr(From);
Larisse Voufo236bec22013-06-10 06:50:24 +00005606 if (result.isInvalid())
5607 return result;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005608 From = result.get();
Eli Friedman1da70392012-01-26 00:26:18 +00005609 }
5610
Richard Smithccc11812013-05-21 19:05:48 +00005611 // If the expression already has a matching type, we're golden.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005612 QualType T = From->getType();
Richard Smithccc11812013-05-21 19:05:48 +00005613 if (Converter.match(T))
Eli Friedman1da70392012-01-26 00:26:18 +00005614 return DefaultLvalueConversion(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005615
5616 // FIXME: Check for missing '()' if T is a function type?
5617
Richard Smithccc11812013-05-21 19:05:48 +00005618 // We can only perform contextual implicit conversions on objects of class
5619 // type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005620 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikiebbafb8a2012-03-11 07:00:24 +00005621 if (!RecordTy || !getLangOpts().CPlusPlus) {
Richard Smithccc11812013-05-21 19:05:48 +00005622 if (!Converter.Suppress)
5623 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005624 return From;
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005625 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005626
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005627 // We must have a complete class type.
Douglas Gregora6c5abb2012-05-04 16:48:41 +00005628 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
Richard Smithccc11812013-05-21 19:05:48 +00005629 ContextualImplicitConverter &Converter;
Douglas Gregore2b37442012-05-04 22:38:52 +00005630 Expr *From;
Richard Smithccc11812013-05-21 19:05:48 +00005631
5632 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
Richard Smithdb0ac552015-12-18 22:40:25 +00005633 : Converter(Converter), From(From) {}
Richard Smithccc11812013-05-21 19:05:48 +00005634
Craig Toppere14c0f82014-03-12 04:55:44 +00005635 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00005636 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005637 }
Richard Smithccc11812013-05-21 19:05:48 +00005638 } IncompleteDiagnoser(Converter, From);
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005639
Richard Smithdb0ac552015-12-18 22:40:25 +00005640 if (Converter.Suppress ? !isCompleteType(Loc, T)
5641 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005642 return From;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005643
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005644 // Look for a conversion to an integral or enumeration type.
Larisse Voufo236bec22013-06-10 06:50:24 +00005645 UnresolvedSet<4>
5646 ViableConversions; // These are *potentially* viable in C++1y.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005647 UnresolvedSet<4> ExplicitConversions;
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005648 const auto &Conversions =
Larisse Voufo236bec22013-06-10 06:50:24 +00005649 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005650
Larisse Voufo236bec22013-06-10 06:50:24 +00005651 bool HadMultipleCandidates =
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005652 (std::distance(Conversions.begin(), Conversions.end()) > 1);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005653
Larisse Voufo236bec22013-06-10 06:50:24 +00005654 // To check that there is only one target type, in C++1y:
5655 QualType ToType;
5656 bool HasUniqueTargetType = true;
5657
5658 // Collect explicit or viable (potentially in C++1y) conversions.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005659 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005660 NamedDecl *D = (*I)->getUnderlyingDecl();
5661 CXXConversionDecl *Conversion;
5662 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5663 if (ConvTemplate) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005664 if (getLangOpts().CPlusPlus14)
Larisse Voufo236bec22013-06-10 06:50:24 +00005665 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5666 else
5667 continue; // C++11 does not consider conversion operator templates(?).
5668 } else
5669 Conversion = cast<CXXConversionDecl>(D);
5670
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005671 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
Larisse Voufo236bec22013-06-10 06:50:24 +00005672 "Conversion operator templates are considered potentially "
5673 "viable in C++1y");
5674
5675 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5676 if (Converter.match(CurToType) || ConvTemplate) {
5677
5678 if (Conversion->isExplicit()) {
5679 // FIXME: For C++1y, do we need this restriction?
5680 // cf. diagnoseNoViableConversion()
5681 if (!ConvTemplate)
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005682 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
Larisse Voufo236bec22013-06-10 06:50:24 +00005683 } else {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005684 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005685 if (ToType.isNull())
5686 ToType = CurToType.getUnqualifiedType();
5687 else if (HasUniqueTargetType &&
5688 (CurToType.getUnqualifiedType() != ToType))
5689 HasUniqueTargetType = false;
5690 }
5691 ViableConversions.addDecl(I.getDecl(), I.getAccess());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005692 }
Richard Smith8dd34252012-02-04 07:07:42 +00005693 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005694 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005695
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005696 if (getLangOpts().CPlusPlus14) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005697 // C++1y [conv]p6:
5698 // ... An expression e of class type E appearing in such a context
5699 // is said to be contextually implicitly converted to a specified
5700 // type T and is well-formed if and only if e can be implicitly
5701 // converted to a type T that is determined as follows: E is searched
Larisse Voufo67170bd2013-06-10 08:25:58 +00005702 // for conversion functions whose return type is cv T or reference to
5703 // cv T such that T is allowed by the context. There shall be
Larisse Voufo236bec22013-06-10 06:50:24 +00005704 // exactly one such T.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005705
Larisse Voufo236bec22013-06-10 06:50:24 +00005706 // If no unique T is found:
5707 if (ToType.isNull()) {
5708 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5709 HadMultipleCandidates,
5710 ExplicitConversions))
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005711 return ExprError();
Larisse Voufo236bec22013-06-10 06:50:24 +00005712 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005713 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005714
Larisse Voufo236bec22013-06-10 06:50:24 +00005715 // If more than one unique Ts are found:
5716 if (!HasUniqueTargetType)
5717 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5718 ViableConversions);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005719
Larisse Voufo236bec22013-06-10 06:50:24 +00005720 // If one unique T is found:
5721 // First, build a candidate set from the previously recorded
5722 // potentially viable conversions.
Richard Smith100b24a2014-04-17 01:52:14 +00005723 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Larisse Voufo236bec22013-06-10 06:50:24 +00005724 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5725 CandidateSet);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005726
Larisse Voufo236bec22013-06-10 06:50:24 +00005727 // Then, perform overload resolution over the candidate set.
5728 OverloadCandidateSet::iterator Best;
5729 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5730 case OR_Success: {
5731 // Apply this conversion.
5732 DeclAccessPair Found =
5733 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5734 if (recordConversion(*this, Loc, From, Converter, T,
5735 HadMultipleCandidates, Found))
5736 return ExprError();
5737 break;
5738 }
5739 case OR_Ambiguous:
5740 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5741 ViableConversions);
5742 case OR_No_Viable_Function:
5743 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5744 HadMultipleCandidates,
5745 ExplicitConversions))
5746 return ExprError();
5747 // fall through 'OR_Deleted' case.
5748 case OR_Deleted:
5749 // We'll complain below about a non-integral condition type.
5750 break;
5751 }
5752 } else {
5753 switch (ViableConversions.size()) {
5754 case 0: {
5755 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5756 HadMultipleCandidates,
5757 ExplicitConversions))
Douglas Gregor4799d032010-06-30 00:20:43 +00005758 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005759
Larisse Voufo236bec22013-06-10 06:50:24 +00005760 // We'll complain below about a non-integral condition type.
5761 break;
Douglas Gregor4799d032010-06-30 00:20:43 +00005762 }
Larisse Voufo236bec22013-06-10 06:50:24 +00005763 case 1: {
5764 // Apply this conversion.
5765 DeclAccessPair Found = ViableConversions[0];
5766 if (recordConversion(*this, Loc, From, Converter, T,
5767 HadMultipleCandidates, Found))
5768 return ExprError();
5769 break;
5770 }
5771 default:
5772 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5773 ViableConversions);
5774 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005775 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005776
Larisse Voufo236bec22013-06-10 06:50:24 +00005777 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005778}
5779
Richard Smith100b24a2014-04-17 01:52:14 +00005780/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5781/// an acceptable non-member overloaded operator for a call whose
5782/// arguments have types T1 (and, if non-empty, T2). This routine
5783/// implements the check in C++ [over.match.oper]p3b2 concerning
5784/// enumeration types.
5785static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5786 FunctionDecl *Fn,
5787 ArrayRef<Expr *> Args) {
5788 QualType T1 = Args[0]->getType();
5789 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5790
5791 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5792 return true;
5793
5794 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5795 return true;
5796
5797 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5798 if (Proto->getNumParams() < 1)
5799 return false;
5800
5801 if (T1->isEnumeralType()) {
5802 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5803 if (Context.hasSameUnqualifiedType(T1, ArgType))
5804 return true;
5805 }
5806
5807 if (Proto->getNumParams() < 2)
5808 return false;
5809
5810 if (!T2.isNull() && T2->isEnumeralType()) {
5811 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5812 if (Context.hasSameUnqualifiedType(T2, ArgType))
5813 return true;
5814 }
5815
5816 return false;
5817}
5818
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005819/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00005820/// candidate functions, using the given function call arguments. If
5821/// @p SuppressUserConversions, then don't allow user-defined
5822/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00005823///
James Dennett2a4d13c2012-06-15 07:13:21 +00005824/// \param PartialOverloading true if we are performing "partial" overloading
Douglas Gregorcabea402009-09-22 15:41:20 +00005825/// based on an incomplete set of function arguments. This feature is used by
5826/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00005827void
5828Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00005829 DeclAccessPair FoundDecl,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005830 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005831 OverloadCandidateSet &CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00005832 bool SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005833 bool PartialOverloading,
5834 bool AllowExplicit) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005835 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00005836 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005837 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00005838 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005839 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00005840
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005841 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005842 if (!isa<CXXConstructorDecl>(Method)) {
5843 // If we get here, it's because we're calling a member function
5844 // that is named without a member access expression (e.g.,
5845 // "this->f") that was either written explicitly or created
5846 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00005847 // function, e.g., X::f(). We use an empty type for the implied
5848 // object argument (C++ [over.call.func]p3), and the acting context
5849 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00005850 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005851 QualType(), Expr::Classification::makeSimpleLValue(),
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005852 Args, CandidateSet, SuppressUserConversions,
5853 PartialOverloading);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005854 return;
5855 }
5856 // We treat a constructor like a non-member function, since its object
5857 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005858 }
5859
Douglas Gregorff7028a2009-11-13 23:59:09 +00005860 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005861 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00005862
Richard Smith100b24a2014-04-17 01:52:14 +00005863 // C++ [over.match.oper]p3:
5864 // if no operand has a class type, only those non-member functions in the
5865 // lookup set that have a first parameter of type T1 or "reference to
5866 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5867 // is a right operand) a second parameter of type T2 or "reference to
5868 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
5869 // candidate functions.
5870 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5871 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5872 return;
5873
Richard Smith8b86f2d2013-11-04 01:48:18 +00005874 // C++11 [class.copy]p11: [DR1402]
5875 // A defaulted move constructor that is defined as deleted is ignored by
5876 // overload resolution.
5877 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5878 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5879 Constructor->isMoveConstructor())
5880 return;
5881
Douglas Gregor27381f32009-11-23 12:27:39 +00005882 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005883 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005884
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005885 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005886 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCalla0296f72010-03-19 07:35:19 +00005887 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005888 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005889 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005890 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005891 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005892 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005893
John McCall578a1f82014-12-14 01:46:53 +00005894 if (Constructor) {
5895 // C++ [class.copy]p3:
5896 // A member function template is never instantiated to perform the copy
5897 // of a class object to an object of its class type.
5898 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
Richard Smith0f59cb32015-12-18 21:45:41 +00005899 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
John McCall578a1f82014-12-14 01:46:53 +00005900 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00005901 IsDerivedFrom(Args[0]->getLocStart(), Args[0]->getType(),
5902 ClassType))) {
John McCall578a1f82014-12-14 01:46:53 +00005903 Candidate.Viable = false;
5904 Candidate.FailureKind = ovl_fail_illegal_constructor;
5905 return;
5906 }
5907 }
5908
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005909 unsigned NumParams = Proto->getNumParams();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005910
5911 // (C++ 13.3.2p2): A candidate function having fewer than m
5912 // parameters is viable only if it has an ellipsis in its parameter
5913 // list (8.3.5).
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005914 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
Douglas Gregor2a920012009-09-23 14:56:09 +00005915 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005916 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005917 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005918 return;
5919 }
5920
5921 // (C++ 13.3.2p2): A candidate function having more than m parameters
5922 // is viable only if the (m+1)st parameter has a default argument
5923 // (8.3.6). For the purposes of overload resolution, the
5924 // parameter list is truncated on the right, so that there are
5925 // exactly m parameters.
5926 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005927 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005928 // Not enough arguments.
5929 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005930 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005931 return;
5932 }
5933
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005934 // (CUDA B.1): Check for invalid calls between targets.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005935 if (getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005936 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
Eli Bendersky9a220fc2014-09-29 20:38:29 +00005937 // Skip the check for callers that are implicit members, because in this
5938 // case we may not yet know what the member's target is; the target is
5939 // inferred for the member automatically, based on the bases and fields of
5940 // the class.
Justin Lebarb0080032016-08-10 01:09:11 +00005941 if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005942 Candidate.Viable = false;
5943 Candidate.FailureKind = ovl_fail_bad_target;
5944 return;
5945 }
5946
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005947 // Determine the implicit conversion sequences for each of the
5948 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005949 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005950 if (ArgIdx < NumParams) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005951 // (C++ 13.3.2p3): for F to be a viable function, there shall
5952 // exist for each argument an implicit conversion sequence
5953 // (13.3.3.1) that converts that argument to the corresponding
5954 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00005955 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005956 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005957 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005958 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00005959 /*InOverloadResolution=*/true,
5960 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005961 getLangOpts().ObjCAutoRefCount,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005962 AllowExplicit);
John McCall0d1da222010-01-12 00:44:57 +00005963 if (Candidate.Conversions[ArgIdx].isBad()) {
5964 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005965 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005966 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00005967 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005968 } else {
5969 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5970 // argument for which there is no corresponding parameter is
5971 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005972 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005973 }
5974 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005975
5976 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
5977 Candidate.Viable = false;
5978 Candidate.FailureKind = ovl_fail_enable_if;
5979 Candidate.DeductionFailure.Data = FailedAttr;
5980 return;
5981 }
Yaxun Liu5b746652016-12-18 05:18:55 +00005982
5983 if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) {
5984 Candidate.Viable = false;
5985 Candidate.FailureKind = ovl_fail_ext_disabled;
5986 return;
5987 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005988}
5989
Manman Rend2a3cd72016-04-07 19:30:20 +00005990ObjCMethodDecl *
5991Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
5992 SmallVectorImpl<ObjCMethodDecl *> &Methods) {
5993 if (Methods.size() <= 1)
Fariborz Jahanian0ded4242014-08-13 21:24:14 +00005994 return nullptr;
Manman Rend2a3cd72016-04-07 19:30:20 +00005995
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005996 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5997 bool Match = true;
5998 ObjCMethodDecl *Method = Methods[b];
5999 unsigned NumNamedArgs = Sel.getNumArgs();
6000 // Method might have more arguments than selector indicates. This is due
6001 // to addition of c-style arguments in method.
6002 if (Method->param_size() > NumNamedArgs)
6003 NumNamedArgs = Method->param_size();
6004 if (Args.size() < NumNamedArgs)
6005 continue;
6006
6007 for (unsigned i = 0; i < NumNamedArgs; i++) {
6008 // We can't do any type-checking on a type-dependent argument.
6009 if (Args[i]->isTypeDependent()) {
6010 Match = false;
6011 break;
6012 }
6013
6014 ParmVarDecl *param = Method->parameters()[i];
6015 Expr *argExpr = Args[i];
6016 assert(argExpr && "SelectBestMethod(): missing expression");
6017
6018 // Strip the unbridged-cast placeholder expression off unless it's
6019 // a consumed argument.
6020 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
6021 !param->hasAttr<CFConsumedAttr>())
6022 argExpr = stripARCUnbridgedCast(argExpr);
6023
6024 // If the parameter is __unknown_anytype, move on to the next method.
6025 if (param->getType() == Context.UnknownAnyTy) {
6026 Match = false;
6027 break;
6028 }
George Burgess IV45461812015-10-11 20:13:20 +00006029
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006030 ImplicitConversionSequence ConversionState
6031 = TryCopyInitialization(*this, argExpr, param->getType(),
6032 /*SuppressUserConversions*/false,
6033 /*InOverloadResolution=*/true,
6034 /*AllowObjCWritebackConversion=*/
6035 getLangOpts().ObjCAutoRefCount,
6036 /*AllowExplicit*/false);
George Burgess IV2099b542016-09-02 22:59:57 +00006037 // This function looks for a reasonably-exact match, so we consider
6038 // incompatible pointer conversions to be a failure here.
6039 if (ConversionState.isBad() ||
6040 (ConversionState.isStandard() &&
6041 ConversionState.Standard.Second ==
6042 ICK_Incompatible_Pointer_Conversion)) {
6043 Match = false;
6044 break;
6045 }
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006046 }
6047 // Promote additional arguments to variadic methods.
6048 if (Match && Method->isVariadic()) {
6049 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6050 if (Args[i]->isTypeDependent()) {
6051 Match = false;
6052 break;
6053 }
6054 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6055 nullptr);
6056 if (Arg.isInvalid()) {
6057 Match = false;
6058 break;
6059 }
6060 }
Fariborz Jahanian180d76b2014-08-27 16:38:47 +00006061 } else {
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006062 // Check for extra arguments to non-variadic methods.
6063 if (Args.size() != NumNamedArgs)
6064 Match = false;
Fariborz Jahanian180d76b2014-08-27 16:38:47 +00006065 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6066 // Special case when selectors have no argument. In this case, select
6067 // one with the most general result type of 'id'.
6068 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6069 QualType ReturnT = Methods[b]->getReturnType();
6070 if (ReturnT->isObjCIdType())
6071 return Methods[b];
6072 }
6073 }
6074 }
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006075
6076 if (Match)
6077 return Method;
6078 }
6079 return nullptr;
6080}
6081
George Burgess IV2a6150d2015-10-16 01:17:38 +00006082// specific_attr_iterator iterates over enable_if attributes in reverse, and
6083// enable_if is order-sensitive. As a result, we need to reverse things
6084// sometimes. Size of 4 elements is arbitrary.
6085static SmallVector<EnableIfAttr *, 4>
6086getOrderedEnableIfAttrs(const FunctionDecl *Function) {
6087 SmallVector<EnableIfAttr *, 4> Result;
6088 if (!Function->hasAttrs())
6089 return Result;
6090
6091 const auto &FuncAttrs = Function->getAttrs();
6092 for (Attr *Attr : FuncAttrs)
6093 if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr))
6094 Result.push_back(EnableIf);
6095
6096 std::reverse(Result.begin(), Result.end());
6097 return Result;
6098}
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006099
6100EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
6101 bool MissingImplicitThis) {
George Burgess IV2a6150d2015-10-16 01:17:38 +00006102 auto EnableIfAttrs = getOrderedEnableIfAttrs(Function);
6103 if (EnableIfAttrs.empty())
Craig Topperc3ec1492014-05-26 06:22:03 +00006104 return nullptr;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006105
6106 SFINAETrap Trap(*this);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006107 SmallVector<Expr *, 16> ConvertedArgs;
6108 bool InitializationFailed = false;
Nick Lewyckye283c552015-08-25 22:33:16 +00006109
George Burgess IV458b3f32016-08-12 04:19:35 +00006110 // Ignore any variadic arguments. Converting them is pointless, since the
George Burgess IV53b938d2016-08-12 04:12:31 +00006111 // user can't refer to them in the enable_if condition.
6112 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6113
Nick Lewyckye283c552015-08-25 22:33:16 +00006114 // Convert the arguments.
George Burgess IV53b938d2016-08-12 04:12:31 +00006115 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
George Burgess IVe96abf72016-02-24 22:31:14 +00006116 ExprResult R;
6117 if (I == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) &&
Nick Lewyckyb8336b72014-02-28 05:26:13 +00006118 !cast<CXXMethodDecl>(Function)->isStatic() &&
6119 !isa<CXXConstructorDecl>(Function)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006120 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
George Burgess IVe96abf72016-02-24 22:31:14 +00006121 R = PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
6122 Method, Method);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006123 } else {
George Burgess IVe96abf72016-02-24 22:31:14 +00006124 R = PerformCopyInitialization(InitializedEntity::InitializeParameter(
6125 Context, Function->getParamDecl(I)),
6126 SourceLocation(), Args[I]);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006127 }
George Burgess IVe96abf72016-02-24 22:31:14 +00006128
6129 if (R.isInvalid()) {
6130 InitializationFailed = true;
6131 break;
6132 }
6133
George Burgess IVe96abf72016-02-24 22:31:14 +00006134 ConvertedArgs.push_back(R.get());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006135 }
6136
6137 if (InitializationFailed || Trap.hasErrorOccurred())
George Burgess IV2a6150d2015-10-16 01:17:38 +00006138 return EnableIfAttrs[0];
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006139
Nick Lewyckye283c552015-08-25 22:33:16 +00006140 // Push default arguments if needed.
6141 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6142 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6143 ParmVarDecl *P = Function->getParamDecl(i);
6144 ExprResult R = PerformCopyInitialization(
6145 InitializedEntity::InitializeParameter(Context,
6146 Function->getParamDecl(i)),
6147 SourceLocation(),
6148 P->hasUninstantiatedDefaultArg() ? P->getUninstantiatedDefaultArg()
6149 : P->getDefaultArg());
6150 if (R.isInvalid()) {
6151 InitializationFailed = true;
6152 break;
6153 }
Nick Lewyckye283c552015-08-25 22:33:16 +00006154 ConvertedArgs.push_back(R.get());
6155 }
6156
6157 if (InitializationFailed || Trap.hasErrorOccurred())
George Burgess IV2a6150d2015-10-16 01:17:38 +00006158 return EnableIfAttrs[0];
Nick Lewyckye283c552015-08-25 22:33:16 +00006159 }
6160
George Burgess IV2a6150d2015-10-16 01:17:38 +00006161 for (auto *EIA : EnableIfAttrs) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006162 APValue Result;
George Burgess IVe8f10cc2016-05-11 01:38:27 +00006163 // FIXME: This doesn't consider value-dependent cases, because doing so is
6164 // very difficult. Ideally, we should handle them more gracefully.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006165 if (!EIA->getCond()->EvaluateWithSubstitution(
George Burgess IVe8f10cc2016-05-11 01:38:27 +00006166 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006167 return EIA;
George Burgess IVe8f10cc2016-05-11 01:38:27 +00006168
6169 if (!Result.isInt() || !Result.getInt().getBoolValue())
6170 return EIA;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006171 }
Craig Topperc3ec1492014-05-26 06:22:03 +00006172 return nullptr;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006173}
6174
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006175/// \brief Add all of the function declarations in the given function set to
Nick Lewyckyed4265c2013-09-22 10:06:01 +00006176/// the overload candidate set.
John McCall4c4c1df2010-01-26 03:27:55 +00006177void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006178 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006179 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006180 TemplateArgumentListInfo *ExplicitTemplateArgs,
Richard Smithbcc22fc2012-03-09 08:00:36 +00006181 bool SuppressUserConversions,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006182 bool PartialOverloading) {
John McCall4c4c1df2010-01-26 03:27:55 +00006183 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00006184 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6185 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006186 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00006187 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00006188 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00006189 Args[0]->getType(), Args[0]->Classify(Context),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006190 Args.slice(1), CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006191 SuppressUserConversions, PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006192 else
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006193 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006194 SuppressUserConversions, PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006195 } else {
John McCalla0296f72010-03-19 07:35:19 +00006196 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006197 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
6198 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00006199 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00006200 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Richard Smithbcc22fc2012-03-09 08:00:36 +00006201 ExplicitTemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006202 Args[0]->getType(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006203 Args[0]->Classify(Context), Args.slice(1),
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006204 CandidateSet, SuppressUserConversions,
6205 PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006206 else
John McCalla0296f72010-03-19 07:35:19 +00006207 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smithbcc22fc2012-03-09 08:00:36 +00006208 ExplicitTemplateArgs, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006209 CandidateSet, SuppressUserConversions,
6210 PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006211 }
Douglas Gregor15448f82009-06-27 21:05:07 +00006212 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006213}
6214
John McCallf0f1cf02009-11-17 07:50:12 +00006215/// AddMethodCandidate - Adds a named decl (which is some kind of
6216/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00006217void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006218 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006219 Expr::Classification ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00006220 ArrayRef<Expr *> Args,
John McCallf0f1cf02009-11-17 07:50:12 +00006221 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006222 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00006223 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00006224 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00006225
6226 if (isa<UsingShadowDecl>(Decl))
6227 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006228
John McCallf0f1cf02009-11-17 07:50:12 +00006229 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6230 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6231 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00006232 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
Craig Topperc3ec1492014-05-26 06:22:03 +00006233 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006234 ObjectType, ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00006235 Args, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006236 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00006237 } else {
John McCalla0296f72010-03-19 07:35:19 +00006238 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006239 ObjectType, ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00006240 Args,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006241 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00006242 }
6243}
6244
Douglas Gregor436424c2008-11-18 23:14:02 +00006245/// AddMethodCandidate - Adds the given C++ member function to the set
6246/// of candidate functions, using the given function call arguments
6247/// and the object argument (@c Object). For example, in a call
6248/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6249/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6250/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00006251/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00006252void
John McCalla0296f72010-03-19 07:35:19 +00006253Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00006254 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006255 Expr::Classification ObjectClassification,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006256 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006257 OverloadCandidateSet &CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006258 bool SuppressUserConversions,
6259 bool PartialOverloading) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006260 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00006261 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00006262 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00006263 assert(!isa<CXXConstructorDecl>(Method) &&
6264 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00006265
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006266 if (!CandidateSet.isNewCandidate(Method))
6267 return;
6268
Richard Smith8b86f2d2013-11-04 01:48:18 +00006269 // C++11 [class.copy]p23: [DR1402]
6270 // A defaulted move assignment operator that is defined as deleted is
6271 // ignored by overload resolution.
6272 if (Method->isDefaulted() && Method->isDeleted() &&
6273 Method->isMoveAssignmentOperator())
6274 return;
6275
Douglas Gregor27381f32009-11-23 12:27:39 +00006276 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006277 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006278
Douglas Gregor436424c2008-11-18 23:14:02 +00006279 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006280 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00006281 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00006282 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006283 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006284 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006285 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor436424c2008-11-18 23:14:02 +00006286
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006287 unsigned NumParams = Proto->getNumParams();
Douglas Gregor436424c2008-11-18 23:14:02 +00006288
6289 // (C++ 13.3.2p2): A candidate function having fewer than m
6290 // parameters is viable only if it has an ellipsis in its parameter
6291 // list (8.3.5).
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006292 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6293 !Proto->isVariadic()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006294 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006295 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00006296 return;
6297 }
6298
6299 // (C++ 13.3.2p2): A candidate function having more than m parameters
6300 // is viable only if the (m+1)st parameter has a default argument
6301 // (8.3.6). For the purposes of overload resolution, the
6302 // parameter list is truncated on the right, so that there are
6303 // exactly m parameters.
6304 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006305 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006306 // Not enough arguments.
6307 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006308 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00006309 return;
6310 }
6311
6312 Candidate.Viable = true;
Douglas Gregor436424c2008-11-18 23:14:02 +00006313
John McCall6e9f8f62009-12-03 04:06:58 +00006314 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006315 // The implicit object argument is ignored.
6316 Candidate.IgnoreObjectArgument = true;
6317 else {
6318 // Determine the implicit conversion sequence for the object
6319 // parameter.
Richard Smith0f59cb32015-12-18 21:45:41 +00006320 Candidate.Conversions[0] = TryObjectArgumentInitialization(
6321 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6322 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00006323 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006324 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006325 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006326 return;
6327 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006328 }
6329
Eli Bendersky291a57e2014-09-25 23:59:08 +00006330 // (CUDA B.1): Check for invalid calls between targets.
6331 if (getLangOpts().CUDA)
6332 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
Justin Lebarb0080032016-08-10 01:09:11 +00006333 if (!IsAllowedCUDACall(Caller, Method)) {
Eli Bendersky291a57e2014-09-25 23:59:08 +00006334 Candidate.Viable = false;
6335 Candidate.FailureKind = ovl_fail_bad_target;
6336 return;
6337 }
6338
Douglas Gregor436424c2008-11-18 23:14:02 +00006339 // Determine the implicit conversion sequences for each of the
6340 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006341 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006342 if (ArgIdx < NumParams) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006343 // (C++ 13.3.2p3): for F to be a viable function, there shall
6344 // exist for each argument an implicit conversion sequence
6345 // (13.3.3.1) that converts that argument to the corresponding
6346 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00006347 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00006348 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006349 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006350 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00006351 /*InOverloadResolution=*/true,
6352 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006353 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00006354 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006355 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006356 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006357 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00006358 }
6359 } else {
6360 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6361 // argument for which there is no corresponding parameter is
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006362 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006363 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00006364 }
6365 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006366
6367 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6368 Candidate.Viable = false;
6369 Candidate.FailureKind = ovl_fail_enable_if;
6370 Candidate.DeductionFailure.Data = FailedAttr;
6371 return;
6372 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006373}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006374
Douglas Gregor97628d62009-08-21 00:16:32 +00006375/// \brief Add a C++ member function template as a candidate to the candidate
6376/// set, using template argument deduction to produce an appropriate member
6377/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00006378void
Douglas Gregor97628d62009-08-21 00:16:32 +00006379Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00006380 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006381 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006382 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006383 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006384 Expr::Classification ObjectClassification,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006385 ArrayRef<Expr *> Args,
Douglas Gregor97628d62009-08-21 00:16:32 +00006386 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006387 bool SuppressUserConversions,
6388 bool PartialOverloading) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006389 if (!CandidateSet.isNewCandidate(MethodTmpl))
6390 return;
6391
Douglas Gregor97628d62009-08-21 00:16:32 +00006392 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00006393 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00006394 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00006395 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00006396 // candidate functions in the usual way.113) A given name can refer to one
6397 // or more function templates and also to a set of overloaded non-template
6398 // functions. In such a case, the candidate functions generated from each
6399 // function template are combined with the set of non-template candidate
6400 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00006401 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006402 FunctionDecl *Specialization = nullptr;
Douglas Gregor97628d62009-08-21 00:16:32 +00006403 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006404 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006405 Specialization, Info, PartialOverloading)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006406 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006407 Candidate.FoundDecl = FoundDecl;
6408 Candidate.Function = MethodTmpl->getTemplatedDecl();
6409 Candidate.Viable = false;
6410 Candidate.FailureKind = ovl_fail_bad_deduction;
6411 Candidate.IsSurrogate = false;
6412 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006413 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006414 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006415 Info);
6416 return;
6417 }
Mike Stump11289f42009-09-09 15:08:12 +00006418
Douglas Gregor97628d62009-08-21 00:16:32 +00006419 // Add the function template specialization produced by template argument
6420 // deduction as a candidate.
6421 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00006422 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00006423 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00006424 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006425 ActingContext, ObjectType, ObjectClassification, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006426 CandidateSet, SuppressUserConversions, PartialOverloading);
Douglas Gregor97628d62009-08-21 00:16:32 +00006427}
6428
Douglas Gregor05155d82009-08-21 23:19:43 +00006429/// \brief Add a C++ function template specialization as a candidate
6430/// in the candidate set, using template argument deduction to produce
6431/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00006432void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006433Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00006434 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006435 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006436 ArrayRef<Expr *> Args,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006437 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006438 bool SuppressUserConversions,
6439 bool PartialOverloading) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006440 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6441 return;
6442
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006443 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00006444 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006445 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00006446 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006447 // candidate functions in the usual way.113) A given name can refer to one
6448 // or more function templates and also to a set of overloaded non-template
6449 // functions. In such a case, the candidate functions generated from each
6450 // function template are combined with the set of non-template candidate
6451 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00006452 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006453 FunctionDecl *Specialization = nullptr;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006454 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006455 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006456 Specialization, Info, PartialOverloading)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006457 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCalla0296f72010-03-19 07:35:19 +00006458 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00006459 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6460 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006461 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00006462 Candidate.IsSurrogate = false;
6463 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006464 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006465 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006466 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006467 return;
6468 }
Mike Stump11289f42009-09-09 15:08:12 +00006469
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006470 // Add the function template specialization produced by template argument
6471 // deduction as a candidate.
6472 assert(Specialization && "Missing function template specialization?");
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006473 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006474 SuppressUserConversions, PartialOverloading);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006475}
Mike Stump11289f42009-09-09 15:08:12 +00006476
Douglas Gregor4b60a152013-11-07 22:34:54 +00006477/// Determine whether this is an allowable conversion from the result
6478/// of an explicit conversion operator to the expected type, per C++
6479/// [over.match.conv]p1 and [over.match.ref]p1.
6480///
6481/// \param ConvType The return type of the conversion function.
6482///
6483/// \param ToType The type we are converting to.
6484///
6485/// \param AllowObjCPointerConversion Allow a conversion from one
6486/// Objective-C pointer to another.
6487///
6488/// \returns true if the conversion is allowable, false otherwise.
6489static bool isAllowableExplicitConversion(Sema &S,
6490 QualType ConvType, QualType ToType,
6491 bool AllowObjCPointerConversion) {
6492 QualType ToNonRefType = ToType.getNonReferenceType();
6493
6494 // Easy case: the types are the same.
6495 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6496 return true;
6497
6498 // Allow qualification conversions.
6499 bool ObjCLifetimeConversion;
6500 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6501 ObjCLifetimeConversion))
6502 return true;
6503
6504 // If we're not allowed to consider Objective-C pointer conversions,
6505 // we're done.
6506 if (!AllowObjCPointerConversion)
6507 return false;
6508
6509 // Is this an Objective-C pointer conversion?
6510 bool IncompatibleObjC = false;
6511 QualType ConvertedType;
6512 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6513 IncompatibleObjC);
6514}
6515
Douglas Gregora1f013e2008-11-07 22:36:19 +00006516/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00006517/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00006518/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00006519/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00006520/// (which may or may not be the same type as the type that the
6521/// conversion function produces).
6522void
6523Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006524 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006525 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00006526 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006527 OverloadCandidateSet& CandidateSet,
6528 bool AllowObjCConversionOnExplicit) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006529 assert(!Conversion->getDescribedFunctionTemplate() &&
6530 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00006531 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006532 if (!CandidateSet.isNewCandidate(Conversion))
6533 return;
6534
Richard Smith2a7d4812013-05-04 07:00:32 +00006535 // If the conversion function has an undeduced return type, trigger its
6536 // deduction now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006537 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00006538 if (DeduceReturnType(Conversion, From->getExprLoc()))
6539 return;
6540 ConvType = Conversion->getConversionType().getNonReferenceType();
6541 }
6542
Richard Smith089c3162013-09-21 21:55:46 +00006543 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6544 // operator is only a candidate if its return type is the target type or
6545 // can be converted to the target type with a qualification conversion.
Douglas Gregor4b60a152013-11-07 22:34:54 +00006546 if (Conversion->isExplicit() &&
6547 !isAllowableExplicitConversion(*this, ConvType, ToType,
6548 AllowObjCConversionOnExplicit))
Richard Smith089c3162013-09-21 21:55:46 +00006549 return;
6550
Douglas Gregor27381f32009-11-23 12:27:39 +00006551 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006552 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006553
Douglas Gregora1f013e2008-11-07 22:36:19 +00006554 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006555 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCalla0296f72010-03-19 07:35:19 +00006556 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006557 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006558 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006559 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006560 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00006561 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00006562 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00006563 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006564 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006565
Douglas Gregor6affc782010-08-19 15:37:02 +00006566 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006567 // For conversion functions, the function is considered to be a member of
6568 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00006569 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006570 //
6571 // Determine the implicit conversion sequence for the implicit
6572 // object parameter.
6573 QualType ImplicitParamType = From->getType();
6574 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6575 ImplicitParamType = FromPtrType->getPointeeType();
6576 CXXRecordDecl *ConversionContext
6577 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006578
Richard Smith0f59cb32015-12-18 21:45:41 +00006579 Candidate.Conversions[0] = TryObjectArgumentInitialization(
6580 *this, CandidateSet.getLocation(), From->getType(),
6581 From->Classify(Context), Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006582
John McCall0d1da222010-01-12 00:44:57 +00006583 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006584 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006585 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006586 return;
6587 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006588
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006589 // We won't go through a user-defined type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006590 // derived to base as such conversions are given Conversion Rank. They only
6591 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6592 QualType FromCanon
6593 = Context.getCanonicalType(From->getType().getUnqualifiedType());
6594 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
Richard Smith0f59cb32015-12-18 21:45:41 +00006595 if (FromCanon == ToCanon ||
6596 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006597 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006598 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006599 return;
6600 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006601
Douglas Gregora1f013e2008-11-07 22:36:19 +00006602 // To determine what the conversion from the result of calling the
6603 // conversion function to the type we're eventually trying to
6604 // convert to (ToType), we need to synthesize a call to the
6605 // conversion function and attempt copy initialization from it. This
6606 // makes sure that we get the right semantics with respect to
6607 // lvalues/rvalues and the type. Fortunately, we can allocate this
6608 // call on the stack and we don't need its arguments to be
6609 // well-formed.
John McCall113bee02012-03-10 09:33:50 +00006610 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00006611 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00006612 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6613 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00006614 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00006615 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00006616
Richard Smith48d24642011-07-13 22:53:21 +00006617 QualType ConversionType = Conversion->getConversionType();
Richard Smithdb0ac552015-12-18 22:40:25 +00006618 if (!isCompleteType(From->getLocStart(), ConversionType)) {
Douglas Gregor72ebdab2010-11-13 19:36:57 +00006619 Candidate.Viable = false;
6620 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6621 return;
6622 }
6623
Richard Smith48d24642011-07-13 22:53:21 +00006624 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCall7decc9e2010-11-18 06:31:45 +00006625
Mike Stump11289f42009-09-09 15:08:12 +00006626 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00006627 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6628 // allocator).
Richard Smith48d24642011-07-13 22:53:21 +00006629 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00006630 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00006631 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00006632 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006633 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00006634 /*SuppressUserConversions=*/true,
John McCall31168b02011-06-15 23:02:42 +00006635 /*InOverloadResolution=*/false,
6636 /*AllowObjCWritebackConversion=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00006637
John McCall0d1da222010-01-12 00:44:57 +00006638 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006639 case ImplicitConversionSequence::StandardConversion:
6640 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006641
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006642 // C++ [over.ics.user]p3:
6643 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006644 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006645 // shall have exact match rank.
6646 if (Conversion->getPrimaryTemplate() &&
6647 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6648 Candidate.Viable = false;
6649 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006650 return;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006651 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006652
Douglas Gregorcba72b12011-01-21 05:18:22 +00006653 // C++0x [dcl.init.ref]p5:
6654 // In the second case, if the reference is an rvalue reference and
6655 // the second standard conversion sequence of the user-defined
6656 // conversion sequence includes an lvalue-to-rvalue conversion, the
6657 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006658 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00006659 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6660 Candidate.Viable = false;
6661 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006662 return;
Douglas Gregorcba72b12011-01-21 05:18:22 +00006663 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00006664 break;
6665
6666 case ImplicitConversionSequence::BadConversion:
6667 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006668 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006669 return;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006670
6671 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006672 llvm_unreachable(
Douglas Gregora1f013e2008-11-07 22:36:19 +00006673 "Can only end up with a standard conversion sequence or failure");
6674 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006675
Craig Topper5fc8fc22014-08-27 06:28:36 +00006676 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006677 Candidate.Viable = false;
6678 Candidate.FailureKind = ovl_fail_enable_if;
6679 Candidate.DeductionFailure.Data = FailedAttr;
6680 return;
6681 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00006682}
6683
Douglas Gregor05155d82009-08-21 23:19:43 +00006684/// \brief Adds a conversion function template specialization
6685/// candidate to the overload set, using template argument deduction
6686/// to deduce the template arguments of the conversion function
6687/// template from the type that we are converting to (C++
6688/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00006689void
Douglas Gregor05155d82009-08-21 23:19:43 +00006690Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00006691 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006692 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00006693 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006694 OverloadCandidateSet &CandidateSet,
6695 bool AllowObjCConversionOnExplicit) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006696 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
6697 "Only conversion function templates permitted here");
6698
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006699 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6700 return;
6701
Craig Toppere6706e42012-09-19 02:26:47 +00006702 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006703 CXXConversionDecl *Specialization = nullptr;
Douglas Gregor05155d82009-08-21 23:19:43 +00006704 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00006705 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00006706 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006707 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006708 Candidate.FoundDecl = FoundDecl;
6709 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6710 Candidate.Viable = false;
6711 Candidate.FailureKind = ovl_fail_bad_deduction;
6712 Candidate.IsSurrogate = false;
6713 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006714 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006715 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006716 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00006717 return;
6718 }
Mike Stump11289f42009-09-09 15:08:12 +00006719
Douglas Gregor05155d82009-08-21 23:19:43 +00006720 // Add the conversion function template specialization produced by
6721 // template argument deduction as a candidate.
6722 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00006723 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006724 CandidateSet, AllowObjCConversionOnExplicit);
Douglas Gregor05155d82009-08-21 23:19:43 +00006725}
6726
Douglas Gregorab7897a2008-11-19 22:57:39 +00006727/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
6728/// converts the given @c Object to a function pointer via the
6729/// conversion function @c Conversion, and then attempts to call it
6730/// with the given arguments (C++ [over.call.object]p2-4). Proto is
6731/// the type of function that we'll eventually be calling.
6732void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006733 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006734 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006735 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00006736 Expr *Object,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006737 ArrayRef<Expr *> Args,
Douglas Gregorab7897a2008-11-19 22:57:39 +00006738 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006739 if (!CandidateSet.isNewCandidate(Conversion))
6740 return;
6741
Douglas Gregor27381f32009-11-23 12:27:39 +00006742 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006743 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006744
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006745 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00006746 Candidate.FoundDecl = FoundDecl;
Craig Topperc3ec1492014-05-26 06:22:03 +00006747 Candidate.Function = nullptr;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006748 Candidate.Surrogate = Conversion;
6749 Candidate.Viable = true;
6750 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006751 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006752 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006753
6754 // Determine the implicit conversion sequence for the implicit
6755 // object parameter.
Richard Smith0f59cb32015-12-18 21:45:41 +00006756 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
6757 *this, CandidateSet.getLocation(), Object->getType(),
6758 Object->Classify(Context), Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00006759 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006760 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006761 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00006762 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006763 return;
6764 }
6765
6766 // The first conversion is actually a user-defined conversion whose
6767 // first conversion is ObjectInit's standard conversion (which is
6768 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00006769 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006770 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00006771 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006772 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006773 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00006774 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump11289f42009-09-09 15:08:12 +00006775 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00006776 = Candidate.Conversions[0].UserDefined.Before;
6777 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
6778
Mike Stump11289f42009-09-09 15:08:12 +00006779 // Find the
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006780 unsigned NumParams = Proto->getNumParams();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006781
6782 // (C++ 13.3.2p2): A candidate function having fewer than m
6783 // parameters is viable only if it has an ellipsis in its parameter
6784 // list (8.3.5).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006785 if (Args.size() > NumParams && !Proto->isVariadic()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006786 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006787 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006788 return;
6789 }
6790
6791 // Function types don't have any default arguments, so just check if
6792 // we have enough arguments.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006793 if (Args.size() < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006794 // Not enough arguments.
6795 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006796 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006797 return;
6798 }
6799
6800 // Determine the implicit conversion sequences for each of the
6801 // arguments.
Richard Smithe54c3072013-05-05 15:51:06 +00006802 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006803 if (ArgIdx < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006804 // (C++ 13.3.2p3): for F to be a viable function, there shall
6805 // exist for each argument an implicit conversion sequence
6806 // (13.3.3.1) that converts that argument to the corresponding
6807 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00006808 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00006809 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006810 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00006811 /*SuppressUserConversions=*/false,
John McCall31168b02011-06-15 23:02:42 +00006812 /*InOverloadResolution=*/false,
6813 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006814 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00006815 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006816 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006817 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006818 return;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006819 }
6820 } else {
6821 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6822 // argument for which there is no corresponding parameter is
6823 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006824 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006825 }
6826 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006827
Craig Topper5fc8fc22014-08-27 06:28:36 +00006828 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006829 Candidate.Viable = false;
6830 Candidate.FailureKind = ovl_fail_enable_if;
6831 Candidate.DeductionFailure.Data = FailedAttr;
6832 return;
6833 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00006834}
6835
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006836/// \brief Add overload candidates for overloaded operators that are
6837/// member functions.
6838///
6839/// Add the overloaded operator candidates that are member functions
6840/// for the operator Op that was used in an operator expression such
6841/// as "x Op y". , Args/NumArgs provides the operator arguments, and
6842/// CandidateSet will store the added overload candidates. (C++
6843/// [over.match.oper]).
6844void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
6845 SourceLocation OpLoc,
Richard Smithe54c3072013-05-05 15:51:06 +00006846 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006847 OverloadCandidateSet& CandidateSet,
6848 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006849 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6850
6851 // C++ [over.match.oper]p3:
6852 // For a unary operator @ with an operand of a type whose
6853 // cv-unqualified version is T1, and for a binary operator @ with
6854 // a left operand of a type whose cv-unqualified version is T1 and
6855 // a right operand of a type whose cv-unqualified version is T2,
6856 // three sets of candidate functions, designated member
6857 // candidates, non-member candidates and built-in candidates, are
6858 // constructed as follows:
6859 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00006860
Richard Smith0feaf0c2013-04-20 12:41:22 +00006861 // -- If T1 is a complete class type or a class currently being
6862 // defined, the set of member candidates is the result of the
6863 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
6864 // the set of member candidates is empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006865 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Richard Smith0feaf0c2013-04-20 12:41:22 +00006866 // Complete the type if it can be completed.
Richard Smithdb0ac552015-12-18 22:40:25 +00006867 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
Richard Smith82b8d4e2015-12-18 22:19:11 +00006868 return;
Richard Smith0feaf0c2013-04-20 12:41:22 +00006869 // If the type is neither complete nor being defined, bail out now.
6870 if (!T1Rec->getDecl()->getDefinition())
Douglas Gregor6a1f9652009-08-27 23:35:55 +00006871 return;
Mike Stump11289f42009-09-09 15:08:12 +00006872
John McCall27b18f82009-11-17 02:14:36 +00006873 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6874 LookupQualifiedName(Operators, T1Rec->getDecl());
6875 Operators.suppressDiagnostics();
6876
Mike Stump11289f42009-09-09 15:08:12 +00006877 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00006878 OperEnd = Operators.end();
6879 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00006880 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00006881 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
Rafael Espindola51629df2013-04-29 19:29:25 +00006882 Args[0]->Classify(Context),
Richard Smithe54c3072013-05-05 15:51:06 +00006883 Args.slice(1),
Douglas Gregor02824322011-01-26 19:30:28 +00006884 CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00006885 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00006886 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006887}
6888
Douglas Gregora11693b2008-11-12 17:17:38 +00006889/// AddBuiltinCandidate - Add a candidate for a built-in
6890/// operator. ResultTy and ParamTys are the result and parameter types
6891/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00006892/// arguments being passed to the candidate. IsAssignmentOperator
6893/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00006894/// operator. NumContextualBoolArguments is the number of arguments
6895/// (at the beginning of the argument list) that will be contextually
6896/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00006897void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Richard Smithe54c3072013-05-05 15:51:06 +00006898 ArrayRef<Expr *> Args,
Douglas Gregorc5e61072009-01-13 00:52:54 +00006899 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00006900 bool IsAssignmentOperator,
6901 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00006902 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006903 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006904
Douglas Gregora11693b2008-11-12 17:17:38 +00006905 // Add this candidate
Richard Smithe54c3072013-05-05 15:51:06 +00006906 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
Craig Topperc3ec1492014-05-26 06:22:03 +00006907 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
6908 Candidate.Function = nullptr;
Douglas Gregor1d248c52008-12-12 02:00:36 +00006909 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006910 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00006911 Candidate.BuiltinTypes.ResultTy = ResultTy;
Richard Smithe54c3072013-05-05 15:51:06 +00006912 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Douglas Gregora11693b2008-11-12 17:17:38 +00006913 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6914
6915 // Determine the implicit conversion sequences for each of the
6916 // arguments.
6917 Candidate.Viable = true;
Richard Smithe54c3072013-05-05 15:51:06 +00006918 Candidate.ExplicitCallArguments = Args.size();
6919 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00006920 // C++ [over.match.oper]p4:
6921 // For the built-in assignment operators, conversions of the
6922 // left operand are restricted as follows:
6923 // -- no temporaries are introduced to hold the left operand, and
6924 // -- no user-defined conversions are applied to the left
6925 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00006926 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00006927 //
6928 // We block these conversions by turning off user-defined
6929 // conversions, since that is the only way that initialization of
6930 // a reference to a non-class type can occur from something that
6931 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00006932 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00006933 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00006934 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00006935 Candidate.Conversions[ArgIdx]
6936 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006937 } else {
Mike Stump11289f42009-09-09 15:08:12 +00006938 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006939 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00006940 ArgIdx == 0 && IsAssignmentOperator,
John McCall31168b02011-06-15 23:02:42 +00006941 /*InOverloadResolution=*/false,
6942 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006943 getLangOpts().ObjCAutoRefCount);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006944 }
John McCall0d1da222010-01-12 00:44:57 +00006945 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006946 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006947 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00006948 break;
6949 }
Douglas Gregora11693b2008-11-12 17:17:38 +00006950 }
6951}
6952
Craig Toppercd7b0332013-07-01 06:29:40 +00006953namespace {
6954
Douglas Gregora11693b2008-11-12 17:17:38 +00006955/// BuiltinCandidateTypeSet - A set of types that will be used for the
6956/// candidate operator functions for built-in operators (C++
6957/// [over.built]). The types are separated into pointer types and
6958/// enumeration types.
6959class BuiltinCandidateTypeSet {
6960 /// TypeSet - A set of types.
Richard Smith95853072016-03-25 00:08:53 +00006961 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
6962 llvm::SmallPtrSet<QualType, 8>> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00006963
6964 /// PointerTypes - The set of pointer types that will be used in the
6965 /// built-in candidates.
6966 TypeSet PointerTypes;
6967
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006968 /// MemberPointerTypes - The set of member pointer types that will be
6969 /// used in the built-in candidates.
6970 TypeSet MemberPointerTypes;
6971
Douglas Gregora11693b2008-11-12 17:17:38 +00006972 /// EnumerationTypes - The set of enumeration types that will be
6973 /// used in the built-in candidates.
6974 TypeSet EnumerationTypes;
6975
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006976 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006977 /// candidates.
6978 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00006979
6980 /// \brief A flag indicating non-record types are viable candidates
6981 bool HasNonRecordTypes;
6982
6983 /// \brief A flag indicating whether either arithmetic or enumeration types
6984 /// were present in the candidate set.
6985 bool HasArithmeticOrEnumeralTypes;
6986
Douglas Gregor80af3132011-05-21 23:15:46 +00006987 /// \brief A flag indicating whether the nullptr type was present in the
6988 /// candidate set.
6989 bool HasNullPtrType;
6990
Douglas Gregor8a2e6012009-08-24 15:23:48 +00006991 /// Sema - The semantic analysis instance where we are building the
6992 /// candidate type set.
6993 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00006994
Douglas Gregora11693b2008-11-12 17:17:38 +00006995 /// Context - The AST context in which we will build the type sets.
6996 ASTContext &Context;
6997
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006998 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6999 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007000 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00007001
7002public:
7003 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00007004 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00007005
Mike Stump11289f42009-09-09 15:08:12 +00007006 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00007007 : HasNonRecordTypes(false),
7008 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor80af3132011-05-21 23:15:46 +00007009 HasNullPtrType(false),
Chandler Carruth00a38332010-12-13 01:44:01 +00007010 SemaRef(SemaRef),
7011 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00007012
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007013 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007014 SourceLocation Loc,
7015 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007016 bool AllowExplicitConversions,
7017 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00007018
7019 /// pointer_begin - First pointer type found;
7020 iterator pointer_begin() { return PointerTypes.begin(); }
7021
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007022 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00007023 iterator pointer_end() { return PointerTypes.end(); }
7024
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007025 /// member_pointer_begin - First member pointer type found;
7026 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
7027
7028 /// member_pointer_end - Past the last member pointer type found;
7029 iterator member_pointer_end() { return MemberPointerTypes.end(); }
7030
Douglas Gregora11693b2008-11-12 17:17:38 +00007031 /// enumeration_begin - First enumeration type found;
7032 iterator enumeration_begin() { return EnumerationTypes.begin(); }
7033
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007034 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00007035 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007036
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007037 iterator vector_begin() { return VectorTypes.begin(); }
7038 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00007039
7040 bool hasNonRecordTypes() { return HasNonRecordTypes; }
7041 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor80af3132011-05-21 23:15:46 +00007042 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregora11693b2008-11-12 17:17:38 +00007043};
7044
Craig Toppercd7b0332013-07-01 06:29:40 +00007045} // end anonymous namespace
7046
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007047/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00007048/// the set of pointer types along with any more-qualified variants of
7049/// that type. For example, if @p Ty is "int const *", this routine
7050/// will add "int const *", "int const volatile *", "int const
7051/// restrict *", and "int const volatile restrict *" to the set of
7052/// pointer types. Returns true if the add of @p Ty itself succeeded,
7053/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00007054///
7055/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007056bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007057BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7058 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00007059
Douglas Gregora11693b2008-11-12 17:17:38 +00007060 // Insert this type.
Richard Smith95853072016-03-25 00:08:53 +00007061 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00007062 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007063
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00007064 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00007065 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00007066 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00007067 if (!PointerTy) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00007068 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7069 PointeeTy = PTy->getPointeeType();
7070 buildObjCPtr = true;
7071 } else {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00007072 PointeeTy = PointerTy->getPointeeType();
Douglas Gregor5bee2582012-06-04 00:15:09 +00007073 }
7074
Sebastian Redl4990a632009-11-18 20:39:26 +00007075 // Don't add qualified variants of arrays. For one, they're not allowed
7076 // (the qualifier would sink to the element type), and for another, the
7077 // only overload situation where it matters is subscript or pointer +- int,
7078 // and those shouldn't have qualifier variants anyway.
7079 if (PointeeTy->isArrayType())
7080 return true;
Douglas Gregor5bee2582012-06-04 00:15:09 +00007081
John McCall8ccfcb52009-09-24 19:53:00 +00007082 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007083 bool hasVolatile = VisibleQuals.hasVolatile();
7084 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007085
John McCall8ccfcb52009-09-24 19:53:00 +00007086 // Iterate through all strict supersets of BaseCVR.
7087 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7088 if ((CVR | BaseCVR) != CVR) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00007089 // Skip over volatile if no volatile found anywhere in the types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007090 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00007091
7092 // Skip over restrict if no restrict found anywhere in the types, or if
7093 // the type cannot be restrict-qualified.
7094 if ((CVR & Qualifiers::Restrict) &&
7095 (!hasRestrict ||
7096 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7097 continue;
7098
7099 // Build qualified pointee type.
John McCall8ccfcb52009-09-24 19:53:00 +00007100 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007101
7102 // Build qualified pointer type.
7103 QualType QPointerTy;
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00007104 if (!buildObjCPtr)
Douglas Gregor5bee2582012-06-04 00:15:09 +00007105 QPointerTy = Context.getPointerType(QPointeeTy);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00007106 else
Douglas Gregor5bee2582012-06-04 00:15:09 +00007107 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
7108
7109 // Insert qualified pointer type.
7110 PointerTypes.insert(QPointerTy);
Douglas Gregora11693b2008-11-12 17:17:38 +00007111 }
7112
7113 return true;
7114}
7115
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007116/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7117/// to the set of pointer types along with any more-qualified variants of
7118/// that type. For example, if @p Ty is "int const *", this routine
7119/// will add "int const *", "int const volatile *", "int const
7120/// restrict *", and "int const volatile restrict *" to the set of
7121/// pointer types. Returns true if the add of @p Ty itself succeeded,
7122/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00007123///
7124/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007125bool
7126BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7127 QualType Ty) {
7128 // Insert this type.
Richard Smith95853072016-03-25 00:08:53 +00007129 if (!MemberPointerTypes.insert(Ty))
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007130 return false;
7131
John McCall8ccfcb52009-09-24 19:53:00 +00007132 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
7133 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007134
John McCall8ccfcb52009-09-24 19:53:00 +00007135 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00007136 // Don't add qualified variants of arrays. For one, they're not allowed
7137 // (the qualifier would sink to the element type), and for another, the
7138 // only overload situation where it matters is subscript or pointer +- int,
7139 // and those shouldn't have qualifier variants anyway.
7140 if (PointeeTy->isArrayType())
7141 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00007142 const Type *ClassTy = PointerTy->getClass();
7143
7144 // Iterate through all strict supersets of the pointee type's CVR
7145 // qualifiers.
7146 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7147 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7148 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007149
John McCall8ccfcb52009-09-24 19:53:00 +00007150 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00007151 MemberPointerTypes.insert(
7152 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007153 }
7154
7155 return true;
7156}
7157
Douglas Gregora11693b2008-11-12 17:17:38 +00007158/// AddTypesConvertedFrom - Add each of the types to which the type @p
7159/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007160/// primarily interested in pointer types and enumeration types. We also
7161/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00007162/// AllowUserConversions is true if we should look at the conversion
7163/// functions of a class type, and AllowExplicitConversions if we
7164/// should also include the explicit conversion functions of a class
7165/// type.
Mike Stump11289f42009-09-09 15:08:12 +00007166void
Douglas Gregor5fb53972009-01-14 15:45:31 +00007167BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007168 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00007169 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007170 bool AllowExplicitConversions,
7171 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007172 // Only deal with canonical types.
7173 Ty = Context.getCanonicalType(Ty);
7174
7175 // Look through reference types; they aren't part of the type of an
7176 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007177 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00007178 Ty = RefTy->getPointeeType();
7179
John McCall33ddac02011-01-19 10:06:00 +00007180 // If we're dealing with an array type, decay to the pointer.
7181 if (Ty->isArrayType())
7182 Ty = SemaRef.Context.getArrayDecayedType(Ty);
7183
7184 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007185 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00007186
Chandler Carruth00a38332010-12-13 01:44:01 +00007187 // Flag if we ever add a non-record type.
7188 const RecordType *TyRec = Ty->getAs<RecordType>();
7189 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7190
Chandler Carruth00a38332010-12-13 01:44:01 +00007191 // Flag if we encounter an arithmetic type.
7192 HasArithmeticOrEnumeralTypes =
7193 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7194
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00007195 if (Ty->isObjCIdType() || Ty->isObjCClassType())
7196 PointerTypes.insert(Ty);
7197 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007198 // Insert our type, and its more-qualified variants, into the set
7199 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007200 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00007201 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007202 } else if (Ty->isMemberPointerType()) {
7203 // Member pointers are far easier, since the pointee can't be converted.
7204 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7205 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00007206 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007207 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00007208 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007209 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007210 // We treat vector types as arithmetic types in many contexts as an
7211 // extension.
7212 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007213 VectorTypes.insert(Ty);
Douglas Gregor80af3132011-05-21 23:15:46 +00007214 } else if (Ty->isNullPtrType()) {
7215 HasNullPtrType = true;
Chandler Carruth00a38332010-12-13 01:44:01 +00007216 } else if (AllowUserConversions && TyRec) {
7217 // No conversion functions in incomplete types.
Richard Smithdb0ac552015-12-18 22:40:25 +00007218 if (!SemaRef.isCompleteType(Loc, Ty))
Chandler Carruth00a38332010-12-13 01:44:01 +00007219 return;
Mike Stump11289f42009-09-09 15:08:12 +00007220
Chandler Carruth00a38332010-12-13 01:44:01 +00007221 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00007222 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007223 if (isa<UsingShadowDecl>(D))
7224 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00007225
Chandler Carruth00a38332010-12-13 01:44:01 +00007226 // Skip conversion function templates; they don't tell us anything
7227 // about which builtin types we can convert to.
7228 if (isa<FunctionTemplateDecl>(D))
7229 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00007230
Chandler Carruth00a38332010-12-13 01:44:01 +00007231 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7232 if (AllowExplicitConversions || !Conv->isExplicit()) {
7233 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7234 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00007235 }
7236 }
7237 }
7238}
7239
Douglas Gregor84605ae2009-08-24 13:43:27 +00007240/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
7241/// the volatile- and non-volatile-qualified assignment operators for the
7242/// given type to the candidate set.
7243static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7244 QualType T,
Richard Smithe54c3072013-05-05 15:51:06 +00007245 ArrayRef<Expr *> Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00007246 OverloadCandidateSet &CandidateSet) {
7247 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00007248
Douglas Gregor84605ae2009-08-24 13:43:27 +00007249 // T& operator=(T&, T)
7250 ParamTypes[0] = S.Context.getLValueReferenceType(T);
7251 ParamTypes[1] = T;
Richard Smithe54c3072013-05-05 15:51:06 +00007252 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor84605ae2009-08-24 13:43:27 +00007253 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00007254
Douglas Gregor84605ae2009-08-24 13:43:27 +00007255 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7256 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00007257 ParamTypes[0]
7258 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00007259 ParamTypes[1] = T;
Richard Smithe54c3072013-05-05 15:51:06 +00007260 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00007261 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00007262 }
7263}
Mike Stump11289f42009-09-09 15:08:12 +00007264
Sebastian Redl1054fae2009-10-25 17:03:50 +00007265/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7266/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007267static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7268 Qualifiers VRQuals;
7269 const RecordType *TyRec;
7270 if (const MemberPointerType *RHSMPType =
7271 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00007272 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007273 else
7274 TyRec = ArgExpr->getType()->getAs<RecordType>();
7275 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007276 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007277 VRQuals.addVolatile();
7278 VRQuals.addRestrict();
7279 return VRQuals;
7280 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007281
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007282 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00007283 if (!ClassDecl->hasDefinition())
7284 return VRQuals;
7285
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00007286 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
John McCallda4458e2010-03-31 01:36:47 +00007287 if (isa<UsingShadowDecl>(D))
7288 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7289 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007290 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7291 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7292 CanTy = ResTypeRef->getPointeeType();
7293 // Need to go down the pointer/mempointer chain and add qualifiers
7294 // as see them.
7295 bool done = false;
7296 while (!done) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00007297 if (CanTy.isRestrictQualified())
7298 VRQuals.addRestrict();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007299 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7300 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007301 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007302 CanTy->getAs<MemberPointerType>())
7303 CanTy = ResTypeMPtr->getPointeeType();
7304 else
7305 done = true;
7306 if (CanTy.isVolatileQualified())
7307 VRQuals.addVolatile();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007308 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7309 return VRQuals;
7310 }
7311 }
7312 }
7313 return VRQuals;
7314}
John McCall52872982010-11-13 05:51:15 +00007315
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007316namespace {
John McCall52872982010-11-13 05:51:15 +00007317
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007318/// \brief Helper class to manage the addition of builtin operator overload
7319/// candidates. It provides shared state and utility methods used throughout
7320/// the process, as well as a helper method to add each group of builtin
7321/// operator overloads from the standard to a candidate set.
7322class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007323 // Common instance state available to all overload candidate addition methods.
7324 Sema &S;
Richard Smithe54c3072013-05-05 15:51:06 +00007325 ArrayRef<Expr *> Args;
Chandler Carruthc6586e52010-12-12 10:35:00 +00007326 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00007327 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007328 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruthc6586e52010-12-12 10:35:00 +00007329 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007330
Chandler Carruthc6586e52010-12-12 10:35:00 +00007331 // Define some constants used to index and iterate over the arithemetic types
7332 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00007333 // The "promoted arithmetic types" are the arithmetic
7334 // types are that preserved by promotion (C++ [over.built]p2).
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00007335 static const unsigned FirstIntegralType = 4;
7336 static const unsigned LastIntegralType = 21;
7337 static const unsigned FirstPromotedIntegralType = 4,
7338 LastPromotedIntegralType = 12;
John McCall52872982010-11-13 05:51:15 +00007339 static const unsigned FirstPromotedArithmeticType = 0,
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00007340 LastPromotedArithmeticType = 12;
7341 static const unsigned NumArithmeticTypes = 21;
John McCall52872982010-11-13 05:51:15 +00007342
Chandler Carruthc6586e52010-12-12 10:35:00 +00007343 /// \brief Get the canonical type for a given arithmetic type index.
7344 CanQualType getArithmeticType(unsigned index) {
7345 assert(index < NumArithmeticTypes);
7346 static CanQualType ASTContext::* const
7347 ArithmeticTypes[NumArithmeticTypes] = {
7348 // Start of promoted types.
7349 &ASTContext::FloatTy,
7350 &ASTContext::DoubleTy,
7351 &ASTContext::LongDoubleTy,
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00007352 &ASTContext::Float128Ty,
John McCall52872982010-11-13 05:51:15 +00007353
Chandler Carruthc6586e52010-12-12 10:35:00 +00007354 // Start of integral types.
7355 &ASTContext::IntTy,
7356 &ASTContext::LongTy,
7357 &ASTContext::LongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00007358 &ASTContext::Int128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00007359 &ASTContext::UnsignedIntTy,
7360 &ASTContext::UnsignedLongTy,
7361 &ASTContext::UnsignedLongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00007362 &ASTContext::UnsignedInt128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00007363 // End of promoted types.
7364
7365 &ASTContext::BoolTy,
7366 &ASTContext::CharTy,
7367 &ASTContext::WCharTy,
7368 &ASTContext::Char16Ty,
7369 &ASTContext::Char32Ty,
7370 &ASTContext::SignedCharTy,
7371 &ASTContext::ShortTy,
7372 &ASTContext::UnsignedCharTy,
7373 &ASTContext::UnsignedShortTy,
7374 // End of integral types.
Richard Smith521ecc12012-06-10 08:00:26 +00007375 // FIXME: What about complex? What about half?
Chandler Carruthc6586e52010-12-12 10:35:00 +00007376 };
7377 return S.Context.*ArithmeticTypes[index];
7378 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007379
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007380 /// \brief Gets the canonical type resulting from the usual arithemetic
7381 /// converions for the given arithmetic types.
7382 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
7383 // Accelerator table for performing the usual arithmetic conversions.
7384 // The rules are basically:
7385 // - if either is floating-point, use the wider floating-point
7386 // - if same signedness, use the higher rank
7387 // - if same size, use unsigned of the higher rank
7388 // - use the larger type
7389 // These rules, together with the axiom that higher ranks are
7390 // never smaller, are sufficient to precompute all of these results
7391 // *except* when dealing with signed types of higher rank.
7392 // (we could precompute SLL x UI for all known platforms, but it's
7393 // better not to make any assumptions).
Richard Smith521ecc12012-06-10 08:00:26 +00007394 // We assume that int128 has a higher rank than long long on all platforms.
George Burgess IVf23ce362016-04-29 21:32:53 +00007395 enum PromotedType : int8_t {
Richard Smith521ecc12012-06-10 08:00:26 +00007396 Dep=-1,
7397 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007398 };
Nuno Lopes9af6b032012-04-21 14:45:25 +00007399 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007400 [LastPromotedArithmeticType] = {
Richard Smith521ecc12012-06-10 08:00:26 +00007401/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
7402/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
7403/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
7404/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
7405/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
7406/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
7407/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
7408/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
7409/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
7410/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
7411/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007412 };
7413
7414 assert(L < LastPromotedArithmeticType);
7415 assert(R < LastPromotedArithmeticType);
7416 int Idx = ConversionsTable[L][R];
7417
7418 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007419 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007420
7421 // Slow path: we need to compare widths.
7422 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007423 CanQualType LT = getArithmeticType(L),
7424 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007425 unsigned LW = S.Context.getIntWidth(LT),
7426 RW = S.Context.getIntWidth(RT);
7427
7428 // If they're different widths, use the signed type.
7429 if (LW > RW) return LT;
7430 else if (LW < RW) return RT;
7431
7432 // Otherwise, use the unsigned type of the signed type's rank.
7433 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
7434 assert(L == SLL || R == SLL);
7435 return S.Context.UnsignedLongLongTy;
7436 }
7437
Chandler Carruth5659c0c2010-12-12 09:22:45 +00007438 /// \brief Helper method to factor out the common pattern of adding overloads
7439 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007440 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007441 bool HasVolatile,
7442 bool HasRestrict) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007443 QualType ParamTypes[2] = {
7444 S.Context.getLValueReferenceType(CandidateTy),
7445 S.Context.IntTy
7446 };
7447
7448 // Non-volatile version.
Richard Smithe54c3072013-05-05 15:51:06 +00007449 if (Args.size() == 1)
7450 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007451 else
Richard Smithe54c3072013-05-05 15:51:06 +00007452 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007453
7454 // Use a heuristic to reduce number of builtin candidates in the set:
7455 // add volatile version only if there are conversions to a volatile type.
7456 if (HasVolatile) {
7457 ParamTypes[0] =
7458 S.Context.getLValueReferenceType(
7459 S.Context.getVolatileType(CandidateTy));
Richard Smithe54c3072013-05-05 15:51:06 +00007460 if (Args.size() == 1)
7461 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007462 else
Richard Smithe54c3072013-05-05 15:51:06 +00007463 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007464 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007465
7466 // Add restrict version only if there are conversions to a restrict type
7467 // and our candidate type is a non-restrict-qualified pointer.
7468 if (HasRestrict && CandidateTy->isAnyPointerType() &&
7469 !CandidateTy.isRestrictQualified()) {
7470 ParamTypes[0]
7471 = S.Context.getLValueReferenceType(
7472 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
Richard Smithe54c3072013-05-05 15:51:06 +00007473 if (Args.size() == 1)
7474 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007475 else
Richard Smithe54c3072013-05-05 15:51:06 +00007476 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007477
7478 if (HasVolatile) {
7479 ParamTypes[0]
7480 = S.Context.getLValueReferenceType(
7481 S.Context.getCVRQualifiedType(CandidateTy,
7482 (Qualifiers::Volatile |
7483 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007484 if (Args.size() == 1)
7485 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007486 else
Richard Smithe54c3072013-05-05 15:51:06 +00007487 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007488 }
7489 }
7490
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007491 }
7492
7493public:
7494 BuiltinOperatorOverloadBuilder(
Richard Smithe54c3072013-05-05 15:51:06 +00007495 Sema &S, ArrayRef<Expr *> Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007496 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00007497 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007498 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007499 OverloadCandidateSet &CandidateSet)
Richard Smithe54c3072013-05-05 15:51:06 +00007500 : S(S), Args(Args),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007501 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00007502 HasArithmeticOrEnumeralCandidateType(
7503 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007504 CandidateTypes(CandidateTypes),
7505 CandidateSet(CandidateSet) {
7506 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007507 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007508 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007509 assert(getArithmeticType(LastPromotedIntegralType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00007510 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007511 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007512 assert(getArithmeticType(FirstPromotedArithmeticType)
7513 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007514 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007515 assert(getArithmeticType(LastPromotedArithmeticType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00007516 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007517 "Invalid last promoted arithmetic type");
7518 }
7519
7520 // C++ [over.built]p3:
7521 //
7522 // For every pair (T, VQ), where T is an arithmetic type, and VQ
7523 // is either volatile or empty, there exist candidate operator
7524 // functions of the form
7525 //
7526 // VQ T& operator++(VQ T&);
7527 // T operator++(VQ T&, int);
7528 //
7529 // C++ [over.built]p4:
7530 //
7531 // For every pair (T, VQ), where T is an arithmetic type other
7532 // than bool, and VQ is either volatile or empty, there exist
7533 // candidate operator functions of the form
7534 //
7535 // VQ T& operator--(VQ T&);
7536 // T operator--(VQ T&, int);
7537 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007538 if (!HasArithmeticOrEnumeralCandidateType)
7539 return;
7540
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007541 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
7542 Arith < NumArithmeticTypes; ++Arith) {
7543 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00007544 getArithmeticType(Arith),
Douglas Gregor5bee2582012-06-04 00:15:09 +00007545 VisibleTypeConversionsQuals.hasVolatile(),
7546 VisibleTypeConversionsQuals.hasRestrict());
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007547 }
7548 }
7549
7550 // C++ [over.built]p5:
7551 //
7552 // For every pair (T, VQ), where T is a cv-qualified or
7553 // cv-unqualified object type, and VQ is either volatile or
7554 // empty, there exist candidate operator functions of the form
7555 //
7556 // T*VQ& operator++(T*VQ&);
7557 // T*VQ& operator--(T*VQ&);
7558 // T* operator++(T*VQ&, int);
7559 // T* operator--(T*VQ&, int);
7560 void addPlusPlusMinusMinusPointerOverloads() {
7561 for (BuiltinCandidateTypeSet::iterator
7562 Ptr = CandidateTypes[0].pointer_begin(),
7563 PtrEnd = CandidateTypes[0].pointer_end();
7564 Ptr != PtrEnd; ++Ptr) {
7565 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00007566 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007567 continue;
7568
7569 addPlusPlusMinusMinusStyleOverloads(*Ptr,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007570 (!(*Ptr).isVolatileQualified() &&
7571 VisibleTypeConversionsQuals.hasVolatile()),
7572 (!(*Ptr).isRestrictQualified() &&
7573 VisibleTypeConversionsQuals.hasRestrict()));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007574 }
7575 }
7576
7577 // C++ [over.built]p6:
7578 // For every cv-qualified or cv-unqualified object type T, there
7579 // exist candidate operator functions of the form
7580 //
7581 // T& operator*(T*);
7582 //
7583 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007584 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00007585 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007586 // T& operator*(T*);
7587 void addUnaryStarPointerOverloads() {
7588 for (BuiltinCandidateTypeSet::iterator
7589 Ptr = CandidateTypes[0].pointer_begin(),
7590 PtrEnd = CandidateTypes[0].pointer_end();
7591 Ptr != PtrEnd; ++Ptr) {
7592 QualType ParamTy = *Ptr;
7593 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007594 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7595 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007596
Douglas Gregor02824322011-01-26 19:30:28 +00007597 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7598 if (Proto->getTypeQuals() || Proto->getRefQualifier())
7599 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007600
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007601 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
Richard Smithe54c3072013-05-05 15:51:06 +00007602 &ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007603 }
7604 }
7605
7606 // C++ [over.built]p9:
7607 // For every promoted arithmetic type T, there exist candidate
7608 // operator functions of the form
7609 //
7610 // T operator+(T);
7611 // T operator-(T);
7612 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007613 if (!HasArithmeticOrEnumeralCandidateType)
7614 return;
7615
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007616 for (unsigned Arith = FirstPromotedArithmeticType;
7617 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007618 QualType ArithTy = getArithmeticType(Arith);
Richard Smithe54c3072013-05-05 15:51:06 +00007619 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007620 }
7621
7622 // Extension: We also add these operators for vector types.
7623 for (BuiltinCandidateTypeSet::iterator
7624 Vec = CandidateTypes[0].vector_begin(),
7625 VecEnd = CandidateTypes[0].vector_end();
7626 Vec != VecEnd; ++Vec) {
7627 QualType VecTy = *Vec;
Richard Smithe54c3072013-05-05 15:51:06 +00007628 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007629 }
7630 }
7631
7632 // C++ [over.built]p8:
7633 // For every type T, there exist candidate operator functions of
7634 // the form
7635 //
7636 // T* operator+(T*);
7637 void addUnaryPlusPointerOverloads() {
7638 for (BuiltinCandidateTypeSet::iterator
7639 Ptr = CandidateTypes[0].pointer_begin(),
7640 PtrEnd = CandidateTypes[0].pointer_end();
7641 Ptr != PtrEnd; ++Ptr) {
7642 QualType ParamTy = *Ptr;
Richard Smithe54c3072013-05-05 15:51:06 +00007643 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007644 }
7645 }
7646
7647 // C++ [over.built]p10:
7648 // For every promoted integral type T, there exist candidate
7649 // operator functions of the form
7650 //
7651 // T operator~(T);
7652 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007653 if (!HasArithmeticOrEnumeralCandidateType)
7654 return;
7655
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007656 for (unsigned Int = FirstPromotedIntegralType;
7657 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007658 QualType IntTy = getArithmeticType(Int);
Richard Smithe54c3072013-05-05 15:51:06 +00007659 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007660 }
7661
7662 // Extension: We also add this operator for vector types.
7663 for (BuiltinCandidateTypeSet::iterator
7664 Vec = CandidateTypes[0].vector_begin(),
7665 VecEnd = CandidateTypes[0].vector_end();
7666 Vec != VecEnd; ++Vec) {
7667 QualType VecTy = *Vec;
Richard Smithe54c3072013-05-05 15:51:06 +00007668 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007669 }
7670 }
7671
7672 // C++ [over.match.oper]p16:
Richard Smith5e9746f2016-10-21 22:00:42 +00007673 // For every pointer to member type T or type std::nullptr_t, there
7674 // exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007675 //
7676 // bool operator==(T,T);
7677 // bool operator!=(T,T);
Richard Smith5e9746f2016-10-21 22:00:42 +00007678 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007679 /// Set of (canonical) types that we've already handled.
7680 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7681
Richard Smithe54c3072013-05-05 15:51:06 +00007682 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007683 for (BuiltinCandidateTypeSet::iterator
7684 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7685 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7686 MemPtr != MemPtrEnd;
7687 ++MemPtr) {
7688 // Don't add the same builtin candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007689 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007690 continue;
7691
7692 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smithe54c3072013-05-05 15:51:06 +00007693 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007694 }
Richard Smith5e9746f2016-10-21 22:00:42 +00007695
7696 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7697 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7698 if (AddedTypes.insert(NullPtrTy).second) {
7699 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
7700 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
7701 CandidateSet);
7702 }
7703 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007704 }
7705 }
7706
7707 // C++ [over.built]p15:
7708 //
Richard Smith5e9746f2016-10-21 22:00:42 +00007709 // For every T, where T is an enumeration type or a pointer type,
7710 // there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007711 //
7712 // bool operator<(T, T);
7713 // bool operator>(T, T);
7714 // bool operator<=(T, T);
7715 // bool operator>=(T, T);
7716 // bool operator==(T, T);
7717 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007718 void addRelationalPointerOrEnumeralOverloads() {
Eli Friedman14f082b2012-09-18 21:52:24 +00007719 // C++ [over.match.oper]p3:
7720 // [...]the built-in candidates include all of the candidate operator
7721 // functions defined in 13.6 that, compared to the given operator, [...]
7722 // do not have the same parameter-type-list as any non-template non-member
7723 // candidate.
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007724 //
Eli Friedman14f082b2012-09-18 21:52:24 +00007725 // Note that in practice, this only affects enumeration types because there
7726 // aren't any built-in candidates of record type, and a user-defined operator
7727 // must have an operand of record or enumeration type. Also, the only other
7728 // overloaded operator with enumeration arguments, operator=,
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007729 // cannot be overloaded for enumeration types, so this is the only place
7730 // where we must suppress candidates like this.
7731 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7732 UserDefinedBinaryOperators;
7733
Richard Smithe54c3072013-05-05 15:51:06 +00007734 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007735 if (CandidateTypes[ArgIdx].enumeration_begin() !=
7736 CandidateTypes[ArgIdx].enumeration_end()) {
7737 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7738 CEnd = CandidateSet.end();
7739 C != CEnd; ++C) {
7740 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7741 continue;
7742
Eli Friedman14f082b2012-09-18 21:52:24 +00007743 if (C->Function->isFunctionTemplateSpecialization())
7744 continue;
7745
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007746 QualType FirstParamType =
7747 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7748 QualType SecondParamType =
7749 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7750
7751 // Skip if either parameter isn't of enumeral type.
7752 if (!FirstParamType->isEnumeralType() ||
7753 !SecondParamType->isEnumeralType())
7754 continue;
7755
7756 // Add this operator to the set of known user-defined operators.
7757 UserDefinedBinaryOperators.insert(
7758 std::make_pair(S.Context.getCanonicalType(FirstParamType),
7759 S.Context.getCanonicalType(SecondParamType)));
7760 }
7761 }
7762 }
7763
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007764 /// Set of (canonical) types that we've already handled.
7765 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7766
Richard Smithe54c3072013-05-05 15:51:06 +00007767 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007768 for (BuiltinCandidateTypeSet::iterator
7769 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7770 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7771 Ptr != PtrEnd; ++Ptr) {
7772 // Don't add the same builtin candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007773 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007774 continue;
7775
7776 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smithe54c3072013-05-05 15:51:06 +00007777 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007778 }
7779 for (BuiltinCandidateTypeSet::iterator
7780 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7781 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7782 Enum != EnumEnd; ++Enum) {
7783 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
7784
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007785 // Don't add the same builtin candidate twice, or if a user defined
7786 // candidate exists.
David Blaikie82e95a32014-11-19 07:49:47 +00007787 if (!AddedTypes.insert(CanonType).second ||
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007788 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
7789 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007790 continue;
7791
7792 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smithe54c3072013-05-05 15:51:06 +00007793 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007794 }
7795 }
7796 }
7797
7798 // C++ [over.built]p13:
7799 //
7800 // For every cv-qualified or cv-unqualified object type T
7801 // there exist candidate operator functions of the form
7802 //
7803 // T* operator+(T*, ptrdiff_t);
7804 // T& operator[](T*, ptrdiff_t); [BELOW]
7805 // T* operator-(T*, ptrdiff_t);
7806 // T* operator+(ptrdiff_t, T*);
7807 // T& operator[](ptrdiff_t, T*); [BELOW]
7808 //
7809 // C++ [over.built]p14:
7810 //
7811 // For every T, where T is a pointer to object type, there
7812 // exist candidate operator functions of the form
7813 //
7814 // ptrdiff_t operator-(T, T);
7815 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
7816 /// Set of (canonical) types that we've already handled.
7817 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7818
7819 for (int Arg = 0; Arg < 2; ++Arg) {
Eric Christopher9207a522015-08-21 16:24:01 +00007820 QualType AsymmetricParamTypes[2] = {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007821 S.Context.getPointerDiffType(),
7822 S.Context.getPointerDiffType(),
7823 };
7824 for (BuiltinCandidateTypeSet::iterator
7825 Ptr = CandidateTypes[Arg].pointer_begin(),
7826 PtrEnd = CandidateTypes[Arg].pointer_end();
7827 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00007828 QualType PointeeTy = (*Ptr)->getPointeeType();
7829 if (!PointeeTy->isObjectType())
7830 continue;
7831
Eric Christopher9207a522015-08-21 16:24:01 +00007832 AsymmetricParamTypes[Arg] = *Ptr;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007833 if (Arg == 0 || Op == OO_Plus) {
7834 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
7835 // T* operator+(ptrdiff_t, T*);
Eric Christopher9207a522015-08-21 16:24:01 +00007836 S.AddBuiltinCandidate(*Ptr, AsymmetricParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007837 }
7838 if (Op == OO_Minus) {
7839 // ptrdiff_t operator-(T, T);
David Blaikie82e95a32014-11-19 07:49:47 +00007840 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007841 continue;
7842
7843 QualType ParamTypes[2] = { *Ptr, *Ptr };
7844 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
Richard Smithe54c3072013-05-05 15:51:06 +00007845 Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007846 }
7847 }
7848 }
7849 }
7850
7851 // C++ [over.built]p12:
7852 //
7853 // For every pair of promoted arithmetic types L and R, there
7854 // exist candidate operator functions of the form
7855 //
7856 // LR operator*(L, R);
7857 // LR operator/(L, R);
7858 // LR operator+(L, R);
7859 // LR operator-(L, R);
7860 // bool operator<(L, R);
7861 // bool operator>(L, R);
7862 // bool operator<=(L, R);
7863 // bool operator>=(L, R);
7864 // bool operator==(L, R);
7865 // bool operator!=(L, R);
7866 //
7867 // where LR is the result of the usual arithmetic conversions
7868 // between types L and R.
7869 //
7870 // C++ [over.built]p24:
7871 //
7872 // For every pair of promoted arithmetic types L and R, there exist
7873 // candidate operator functions of the form
7874 //
7875 // LR operator?(bool, L, R);
7876 //
7877 // where LR is the result of the usual arithmetic conversions
7878 // between types L and R.
7879 // Our candidates ignore the first parameter.
7880 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007881 if (!HasArithmeticOrEnumeralCandidateType)
7882 return;
7883
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007884 for (unsigned Left = FirstPromotedArithmeticType;
7885 Left < LastPromotedArithmeticType; ++Left) {
7886 for (unsigned Right = FirstPromotedArithmeticType;
7887 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007888 QualType LandR[2] = { getArithmeticType(Left),
7889 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007890 QualType Result =
7891 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007892 : getUsualArithmeticConversions(Left, Right);
Richard Smithe54c3072013-05-05 15:51:06 +00007893 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007894 }
7895 }
7896
7897 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7898 // conditional operator for vector types.
7899 for (BuiltinCandidateTypeSet::iterator
7900 Vec1 = CandidateTypes[0].vector_begin(),
7901 Vec1End = CandidateTypes[0].vector_end();
7902 Vec1 != Vec1End; ++Vec1) {
7903 for (BuiltinCandidateTypeSet::iterator
7904 Vec2 = CandidateTypes[1].vector_begin(),
7905 Vec2End = CandidateTypes[1].vector_end();
7906 Vec2 != Vec2End; ++Vec2) {
7907 QualType LandR[2] = { *Vec1, *Vec2 };
7908 QualType Result = S.Context.BoolTy;
7909 if (!isComparison) {
7910 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7911 Result = *Vec1;
7912 else
7913 Result = *Vec2;
7914 }
7915
Richard Smithe54c3072013-05-05 15:51:06 +00007916 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007917 }
7918 }
7919 }
7920
7921 // C++ [over.built]p17:
7922 //
7923 // For every pair of promoted integral types L and R, there
7924 // exist candidate operator functions of the form
7925 //
7926 // LR operator%(L, R);
7927 // LR operator&(L, R);
7928 // LR operator^(L, R);
7929 // LR operator|(L, R);
7930 // L operator<<(L, R);
7931 // L operator>>(L, R);
7932 //
7933 // where LR is the result of the usual arithmetic conversions
7934 // between types L and R.
7935 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007936 if (!HasArithmeticOrEnumeralCandidateType)
7937 return;
7938
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007939 for (unsigned Left = FirstPromotedIntegralType;
7940 Left < LastPromotedIntegralType; ++Left) {
7941 for (unsigned Right = FirstPromotedIntegralType;
7942 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007943 QualType LandR[2] = { getArithmeticType(Left),
7944 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007945 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7946 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007947 : getUsualArithmeticConversions(Left, Right);
Richard Smithe54c3072013-05-05 15:51:06 +00007948 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007949 }
7950 }
7951 }
7952
7953 // C++ [over.built]p20:
7954 //
7955 // For every pair (T, VQ), where T is an enumeration or
7956 // pointer to member type and VQ is either volatile or
7957 // empty, there exist candidate operator functions of the form
7958 //
7959 // VQ T& operator=(VQ T&, T);
7960 void addAssignmentMemberPointerOrEnumeralOverloads() {
7961 /// Set of (canonical) types that we've already handled.
7962 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7963
7964 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7965 for (BuiltinCandidateTypeSet::iterator
7966 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7967 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7968 Enum != EnumEnd; ++Enum) {
David Blaikie82e95a32014-11-19 07:49:47 +00007969 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007970 continue;
7971
Richard Smithe54c3072013-05-05 15:51:06 +00007972 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007973 }
7974
7975 for (BuiltinCandidateTypeSet::iterator
7976 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7977 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7978 MemPtr != MemPtrEnd; ++MemPtr) {
David Blaikie82e95a32014-11-19 07:49:47 +00007979 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007980 continue;
7981
Richard Smithe54c3072013-05-05 15:51:06 +00007982 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007983 }
7984 }
7985 }
7986
7987 // C++ [over.built]p19:
7988 //
7989 // For every pair (T, VQ), where T is any type and VQ is either
7990 // volatile or empty, there exist candidate operator functions
7991 // of the form
7992 //
7993 // T*VQ& operator=(T*VQ&, T*);
7994 //
7995 // C++ [over.built]p21:
7996 //
7997 // For every pair (T, VQ), where T is a cv-qualified or
7998 // cv-unqualified object type and VQ is either volatile or
7999 // empty, there exist candidate operator functions of the form
8000 //
8001 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
8002 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
8003 void addAssignmentPointerOverloads(bool isEqualOp) {
8004 /// Set of (canonical) types that we've already handled.
8005 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8006
8007 for (BuiltinCandidateTypeSet::iterator
8008 Ptr = CandidateTypes[0].pointer_begin(),
8009 PtrEnd = CandidateTypes[0].pointer_end();
8010 Ptr != PtrEnd; ++Ptr) {
8011 // If this is operator=, keep track of the builtin candidates we added.
8012 if (isEqualOp)
8013 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00008014 else if (!(*Ptr)->getPointeeType()->isObjectType())
8015 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008016
8017 // non-volatile version
8018 QualType ParamTypes[2] = {
8019 S.Context.getLValueReferenceType(*Ptr),
8020 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
8021 };
Richard Smithe54c3072013-05-05 15:51:06 +00008022 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008023 /*IsAssigmentOperator=*/ isEqualOp);
8024
Douglas Gregor5bee2582012-06-04 00:15:09 +00008025 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8026 VisibleTypeConversionsQuals.hasVolatile();
8027 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008028 // volatile version
8029 ParamTypes[0] =
8030 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00008031 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008032 /*IsAssigmentOperator=*/isEqualOp);
8033 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00008034
8035 if (!(*Ptr).isRestrictQualified() &&
8036 VisibleTypeConversionsQuals.hasRestrict()) {
8037 // restrict version
8038 ParamTypes[0]
8039 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00008040 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00008041 /*IsAssigmentOperator=*/isEqualOp);
8042
8043 if (NeedVolatile) {
8044 // volatile restrict version
8045 ParamTypes[0]
8046 = S.Context.getLValueReferenceType(
8047 S.Context.getCVRQualifiedType(*Ptr,
8048 (Qualifiers::Volatile |
8049 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00008050 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00008051 /*IsAssigmentOperator=*/isEqualOp);
8052 }
8053 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008054 }
8055
8056 if (isEqualOp) {
8057 for (BuiltinCandidateTypeSet::iterator
8058 Ptr = CandidateTypes[1].pointer_begin(),
8059 PtrEnd = CandidateTypes[1].pointer_end();
8060 Ptr != PtrEnd; ++Ptr) {
8061 // Make sure we don't add the same candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00008062 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008063 continue;
8064
Chandler Carruth8e543b32010-12-12 08:17:55 +00008065 QualType ParamTypes[2] = {
8066 S.Context.getLValueReferenceType(*Ptr),
8067 *Ptr,
8068 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008069
8070 // non-volatile version
Richard Smithe54c3072013-05-05 15:51:06 +00008071 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008072 /*IsAssigmentOperator=*/true);
8073
Douglas Gregor5bee2582012-06-04 00:15:09 +00008074 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8075 VisibleTypeConversionsQuals.hasVolatile();
8076 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008077 // volatile version
8078 ParamTypes[0] =
8079 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00008080 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8081 /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008082 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00008083
8084 if (!(*Ptr).isRestrictQualified() &&
8085 VisibleTypeConversionsQuals.hasRestrict()) {
8086 // restrict version
8087 ParamTypes[0]
8088 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00008089 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8090 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00008091
8092 if (NeedVolatile) {
8093 // volatile restrict version
8094 ParamTypes[0]
8095 = S.Context.getLValueReferenceType(
8096 S.Context.getCVRQualifiedType(*Ptr,
8097 (Qualifiers::Volatile |
8098 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00008099 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8100 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00008101 }
8102 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008103 }
8104 }
8105 }
8106
8107 // C++ [over.built]p18:
8108 //
8109 // For every triple (L, VQ, R), where L is an arithmetic type,
8110 // VQ is either volatile or empty, and R is a promoted
8111 // arithmetic type, there exist candidate operator functions of
8112 // the form
8113 //
8114 // VQ L& operator=(VQ L&, R);
8115 // VQ L& operator*=(VQ L&, R);
8116 // VQ L& operator/=(VQ L&, R);
8117 // VQ L& operator+=(VQ L&, R);
8118 // VQ L& operator-=(VQ L&, R);
8119 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00008120 if (!HasArithmeticOrEnumeralCandidateType)
8121 return;
8122
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008123 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
8124 for (unsigned Right = FirstPromotedArithmeticType;
8125 Right < LastPromotedArithmeticType; ++Right) {
8126 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00008127 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008128
8129 // Add this built-in operator as a candidate (VQ is empty).
8130 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00008131 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smithe54c3072013-05-05 15:51:06 +00008132 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008133 /*IsAssigmentOperator=*/isEqualOp);
8134
8135 // Add this built-in operator as a candidate (VQ is 'volatile').
8136 if (VisibleTypeConversionsQuals.hasVolatile()) {
8137 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00008138 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008139 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00008140 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008141 /*IsAssigmentOperator=*/isEqualOp);
8142 }
8143 }
8144 }
8145
8146 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8147 for (BuiltinCandidateTypeSet::iterator
8148 Vec1 = CandidateTypes[0].vector_begin(),
8149 Vec1End = CandidateTypes[0].vector_end();
8150 Vec1 != Vec1End; ++Vec1) {
8151 for (BuiltinCandidateTypeSet::iterator
8152 Vec2 = CandidateTypes[1].vector_begin(),
8153 Vec2End = CandidateTypes[1].vector_end();
8154 Vec2 != Vec2End; ++Vec2) {
8155 QualType ParamTypes[2];
8156 ParamTypes[1] = *Vec2;
8157 // Add this built-in operator as a candidate (VQ is empty).
8158 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
Richard Smithe54c3072013-05-05 15:51:06 +00008159 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008160 /*IsAssigmentOperator=*/isEqualOp);
8161
8162 // Add this built-in operator as a candidate (VQ is 'volatile').
8163 if (VisibleTypeConversionsQuals.hasVolatile()) {
8164 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
8165 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00008166 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008167 /*IsAssigmentOperator=*/isEqualOp);
8168 }
8169 }
8170 }
8171 }
8172
8173 // C++ [over.built]p22:
8174 //
8175 // For every triple (L, VQ, R), where L is an integral type, VQ
8176 // is either volatile or empty, and R is a promoted integral
8177 // type, there exist candidate operator functions of the form
8178 //
8179 // VQ L& operator%=(VQ L&, R);
8180 // VQ L& operator<<=(VQ L&, R);
8181 // VQ L& operator>>=(VQ L&, R);
8182 // VQ L& operator&=(VQ L&, R);
8183 // VQ L& operator^=(VQ L&, R);
8184 // VQ L& operator|=(VQ L&, R);
8185 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00008186 if (!HasArithmeticOrEnumeralCandidateType)
8187 return;
8188
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008189 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8190 for (unsigned Right = FirstPromotedIntegralType;
8191 Right < LastPromotedIntegralType; ++Right) {
8192 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00008193 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008194
8195 // Add this built-in operator as a candidate (VQ is empty).
8196 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00008197 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smithe54c3072013-05-05 15:51:06 +00008198 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008199 if (VisibleTypeConversionsQuals.hasVolatile()) {
8200 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00008201 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008202 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8203 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00008204 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008205 }
8206 }
8207 }
8208 }
8209
8210 // C++ [over.operator]p23:
8211 //
8212 // There also exist candidate operator functions of the form
8213 //
8214 // bool operator!(bool);
8215 // bool operator&&(bool, bool);
8216 // bool operator||(bool, bool);
8217 void addExclaimOverload() {
8218 QualType ParamTy = S.Context.BoolTy;
Richard Smithe54c3072013-05-05 15:51:06 +00008219 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008220 /*IsAssignmentOperator=*/false,
8221 /*NumContextualBoolArguments=*/1);
8222 }
8223 void addAmpAmpOrPipePipeOverload() {
8224 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
Richard Smithe54c3072013-05-05 15:51:06 +00008225 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008226 /*IsAssignmentOperator=*/false,
8227 /*NumContextualBoolArguments=*/2);
8228 }
8229
8230 // C++ [over.built]p13:
8231 //
8232 // For every cv-qualified or cv-unqualified object type T there
8233 // exist candidate operator functions of the form
8234 //
8235 // T* operator+(T*, ptrdiff_t); [ABOVE]
8236 // T& operator[](T*, ptrdiff_t);
8237 // T* operator-(T*, ptrdiff_t); [ABOVE]
8238 // T* operator+(ptrdiff_t, T*); [ABOVE]
8239 // T& operator[](ptrdiff_t, T*);
8240 void addSubscriptOverloads() {
8241 for (BuiltinCandidateTypeSet::iterator
8242 Ptr = CandidateTypes[0].pointer_begin(),
8243 PtrEnd = CandidateTypes[0].pointer_end();
8244 Ptr != PtrEnd; ++Ptr) {
8245 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8246 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00008247 if (!PointeeType->isObjectType())
8248 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008249
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008250 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8251
8252 // T& operator[](T*, ptrdiff_t)
Richard Smithe54c3072013-05-05 15:51:06 +00008253 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008254 }
8255
8256 for (BuiltinCandidateTypeSet::iterator
8257 Ptr = CandidateTypes[1].pointer_begin(),
8258 PtrEnd = CandidateTypes[1].pointer_end();
8259 Ptr != PtrEnd; ++Ptr) {
8260 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8261 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00008262 if (!PointeeType->isObjectType())
8263 continue;
8264
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008265 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8266
8267 // T& operator[](ptrdiff_t, T*)
Richard Smithe54c3072013-05-05 15:51:06 +00008268 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008269 }
8270 }
8271
8272 // C++ [over.built]p11:
8273 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8274 // C1 is the same type as C2 or is a derived class of C2, T is an object
8275 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8276 // there exist candidate operator functions of the form
8277 //
8278 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8279 //
8280 // where CV12 is the union of CV1 and CV2.
8281 void addArrowStarOverloads() {
8282 for (BuiltinCandidateTypeSet::iterator
8283 Ptr = CandidateTypes[0].pointer_begin(),
8284 PtrEnd = CandidateTypes[0].pointer_end();
8285 Ptr != PtrEnd; ++Ptr) {
8286 QualType C1Ty = (*Ptr);
8287 QualType C1;
8288 QualifierCollector Q1;
8289 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8290 if (!isa<RecordType>(C1))
8291 continue;
8292 // heuristic to reduce number of builtin candidates in the set.
8293 // Add volatile/restrict version only if there are conversions to a
8294 // volatile/restrict type.
8295 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8296 continue;
8297 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8298 continue;
8299 for (BuiltinCandidateTypeSet::iterator
8300 MemPtr = CandidateTypes[1].member_pointer_begin(),
8301 MemPtrEnd = CandidateTypes[1].member_pointer_end();
8302 MemPtr != MemPtrEnd; ++MemPtr) {
8303 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8304 QualType C2 = QualType(mptr->getClass(), 0);
8305 C2 = C2.getUnqualifiedType();
Richard Smith0f59cb32015-12-18 21:45:41 +00008306 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008307 break;
8308 QualType ParamTypes[2] = { *Ptr, *MemPtr };
8309 // build CV12 T&
8310 QualType T = mptr->getPointeeType();
8311 if (!VisibleTypeConversionsQuals.hasVolatile() &&
8312 T.isVolatileQualified())
8313 continue;
8314 if (!VisibleTypeConversionsQuals.hasRestrict() &&
8315 T.isRestrictQualified())
8316 continue;
8317 T = Q1.apply(S.Context, T);
8318 QualType ResultTy = S.Context.getLValueReferenceType(T);
Richard Smithe54c3072013-05-05 15:51:06 +00008319 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008320 }
8321 }
8322 }
8323
8324 // Note that we don't consider the first argument, since it has been
8325 // contextually converted to bool long ago. The candidates below are
8326 // therefore added as binary.
8327 //
8328 // C++ [over.built]p25:
8329 // For every type T, where T is a pointer, pointer-to-member, or scoped
8330 // enumeration type, there exist candidate operator functions of the form
8331 //
8332 // T operator?(bool, T, T);
8333 //
8334 void addConditionalOperatorOverloads() {
8335 /// Set of (canonical) types that we've already handled.
8336 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8337
8338 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8339 for (BuiltinCandidateTypeSet::iterator
8340 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8341 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8342 Ptr != PtrEnd; ++Ptr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008343 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008344 continue;
8345
8346 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smithe54c3072013-05-05 15:51:06 +00008347 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008348 }
8349
8350 for (BuiltinCandidateTypeSet::iterator
8351 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8352 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8353 MemPtr != MemPtrEnd; ++MemPtr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008354 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008355 continue;
8356
8357 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smithe54c3072013-05-05 15:51:06 +00008358 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008359 }
8360
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008361 if (S.getLangOpts().CPlusPlus11) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008362 for (BuiltinCandidateTypeSet::iterator
8363 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8364 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8365 Enum != EnumEnd; ++Enum) {
8366 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8367 continue;
8368
David Blaikie82e95a32014-11-19 07:49:47 +00008369 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008370 continue;
8371
8372 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smithe54c3072013-05-05 15:51:06 +00008373 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008374 }
8375 }
8376 }
8377 }
8378};
8379
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008380} // end anonymous namespace
8381
8382/// AddBuiltinOperatorCandidates - Add the appropriate built-in
8383/// operator overloads to the candidate set (C++ [over.built]), based
8384/// on the operator @p Op and the arguments given. For example, if the
8385/// operator is a binary '+', this routine might add "int
8386/// operator+(int, int)" to cover integer addition.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00008387void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8388 SourceLocation OpLoc,
8389 ArrayRef<Expr *> Args,
8390 OverloadCandidateSet &CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00008391 // Find all of the types that the arguments can convert to, but only
8392 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00008393 // that make use of these types. Also record whether we encounter non-record
8394 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00008395 Qualifiers VisibleTypeConversionsQuals;
8396 VisibleTypeConversionsQuals.addConst();
Richard Smithe54c3072013-05-05 15:51:06 +00008397 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00008398 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00008399
8400 bool HasNonRecordCandidateType = false;
8401 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008402 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Richard Smithe54c3072013-05-05 15:51:06 +00008403 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Benjamin Kramer57dddd482015-02-17 21:55:18 +00008404 CandidateTypes.emplace_back(*this);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00008405 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8406 OpLoc,
8407 true,
8408 (Op == OO_Exclaim ||
8409 Op == OO_AmpAmp ||
8410 Op == OO_PipePipe),
8411 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00008412 HasNonRecordCandidateType = HasNonRecordCandidateType ||
8413 CandidateTypes[ArgIdx].hasNonRecordTypes();
8414 HasArithmeticOrEnumeralCandidateType =
8415 HasArithmeticOrEnumeralCandidateType ||
8416 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00008417 }
Douglas Gregora11693b2008-11-12 17:17:38 +00008418
Chandler Carruth00a38332010-12-13 01:44:01 +00008419 // Exit early when no non-record types have been added to the candidate set
8420 // for any of the arguments to the operator.
Douglas Gregor877d4eb2011-10-10 14:05:31 +00008421 //
8422 // We can't exit early for !, ||, or &&, since there we have always have
8423 // 'bool' overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00008424 if (!HasNonRecordCandidateType &&
Douglas Gregor877d4eb2011-10-10 14:05:31 +00008425 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth00a38332010-12-13 01:44:01 +00008426 return;
8427
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008428 // Setup an object to manage the common state for building overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00008429 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008430 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00008431 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008432 CandidateTypes, CandidateSet);
8433
8434 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00008435 switch (Op) {
8436 case OO_None:
8437 case NUM_OVERLOADED_OPERATORS:
David Blaikie83d382b2011-09-23 05:06:16 +00008438 llvm_unreachable("Expected an overloaded operator");
Douglas Gregora11693b2008-11-12 17:17:38 +00008439
Chandler Carruth5184de02010-12-12 08:51:33 +00008440 case OO_New:
8441 case OO_Delete:
8442 case OO_Array_New:
8443 case OO_Array_Delete:
8444 case OO_Call:
David Blaikie83d382b2011-09-23 05:06:16 +00008445 llvm_unreachable(
8446 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruth5184de02010-12-12 08:51:33 +00008447
8448 case OO_Comma:
8449 case OO_Arrow:
Richard Smith9f690bd2015-10-27 06:02:45 +00008450 case OO_Coawait:
Chandler Carruth5184de02010-12-12 08:51:33 +00008451 // C++ [over.match.oper]p3:
Richard Smith9f690bd2015-10-27 06:02:45 +00008452 // -- For the operator ',', the unary operator '&', the
8453 // operator '->', or the operator 'co_await', the
8454 // built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00008455 break;
8456
8457 case OO_Plus: // '+' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008458 if (Args.size() == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008459 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00008460 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00008461
8462 case OO_Minus: // '-' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008463 if (Args.size() == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008464 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008465 } else {
8466 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8467 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8468 }
Douglas Gregord08452f2008-11-19 15:42:04 +00008469 break;
8470
Chandler Carruth5184de02010-12-12 08:51:33 +00008471 case OO_Star: // '*' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008472 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008473 OpBuilder.addUnaryStarPointerOverloads();
8474 else
8475 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8476 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008477
Chandler Carruth5184de02010-12-12 08:51:33 +00008478 case OO_Slash:
8479 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008480 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008481
8482 case OO_PlusPlus:
8483 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008484 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8485 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00008486 break;
8487
Douglas Gregor84605ae2009-08-24 13:43:27 +00008488 case OO_EqualEqual:
8489 case OO_ExclaimEqual:
Richard Smith5e9746f2016-10-21 22:00:42 +00008490 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00008491 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008492
Douglas Gregora11693b2008-11-12 17:17:38 +00008493 case OO_Less:
8494 case OO_Greater:
8495 case OO_LessEqual:
8496 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00008497 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00008498 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
8499 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008500
Douglas Gregora11693b2008-11-12 17:17:38 +00008501 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00008502 case OO_Caret:
8503 case OO_Pipe:
8504 case OO_LessLess:
8505 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008506 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00008507 break;
8508
Chandler Carruth5184de02010-12-12 08:51:33 +00008509 case OO_Amp: // '&' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008510 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008511 // C++ [over.match.oper]p3:
8512 // -- For the operator ',', the unary operator '&', or the
8513 // operator '->', the built-in candidates set is empty.
8514 break;
8515
8516 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8517 break;
8518
8519 case OO_Tilde:
8520 OpBuilder.addUnaryTildePromotedIntegralOverloads();
8521 break;
8522
Douglas Gregora11693b2008-11-12 17:17:38 +00008523 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008524 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00008525 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00008526
8527 case OO_PlusEqual:
8528 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008529 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008530 // Fall through.
8531
8532 case OO_StarEqual:
8533 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008534 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008535 break;
8536
8537 case OO_PercentEqual:
8538 case OO_LessLessEqual:
8539 case OO_GreaterGreaterEqual:
8540 case OO_AmpEqual:
8541 case OO_CaretEqual:
8542 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008543 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008544 break;
8545
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008546 case OO_Exclaim:
8547 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00008548 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008549
Douglas Gregora11693b2008-11-12 17:17:38 +00008550 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008551 case OO_PipePipe:
8552 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00008553 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008554
8555 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008556 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008557 break;
8558
8559 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008560 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008561 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00008562
8563 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008564 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008565 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8566 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008567 }
8568}
8569
Douglas Gregore254f902009-02-04 00:32:51 +00008570/// \brief Add function candidates found via argument-dependent lookup
8571/// to the set of overloading candidates.
8572///
8573/// This routine performs argument-dependent name lookup based on the
8574/// given function name (which may also be an operator name) and adds
8575/// all of the overload candidates found by ADL to the overload
8576/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00008577void
Douglas Gregore254f902009-02-04 00:32:51 +00008578Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smith100b24a2014-04-17 01:52:14 +00008579 SourceLocation Loc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008580 ArrayRef<Expr *> Args,
Douglas Gregor739b107a2011-03-03 02:41:12 +00008581 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008582 OverloadCandidateSet& CandidateSet,
Richard Smithb6626742012-10-18 17:56:02 +00008583 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00008584 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00008585
John McCall91f61fc2010-01-26 06:04:06 +00008586 // FIXME: This approach for uniquing ADL results (and removing
8587 // redundant candidates from the set) relies on pointer-equality,
8588 // which means we need to key off the canonical decl. However,
8589 // always going back to the canonical decl might not get us the
8590 // right set of default arguments. What default arguments are
8591 // we supposed to consider on ADL candidates, anyway?
8592
Douglas Gregorcabea402009-09-22 15:41:20 +00008593 // FIXME: Pass in the explicit template arguments?
Richard Smith100b24a2014-04-17 01:52:14 +00008594 ArgumentDependentLookup(Name, Loc, Args, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00008595
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008596 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008597 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8598 CandEnd = CandidateSet.end();
8599 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00008600 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00008601 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00008602 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00008603 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00008604 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008605
8606 // For each of the ADL candidates we found, add it to the overload
8607 // set.
John McCall8fe68082010-01-26 07:16:45 +00008608 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00008609 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00008610 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00008611 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00008612 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008613
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008614 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8615 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00008616 } else
John McCall4c4c1df2010-01-26 03:27:55 +00008617 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00008618 FoundDecl, ExplicitTemplateArgs,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00008619 Args, CandidateSet, PartialOverloading);
Douglas Gregor15448f82009-06-27 21:05:07 +00008620 }
Douglas Gregore254f902009-02-04 00:32:51 +00008621}
8622
George Burgess IV3dc166912016-05-10 01:59:34 +00008623namespace {
8624enum class Comparison { Equal, Better, Worse };
8625}
8626
8627/// Compares the enable_if attributes of two FunctionDecls, for the purposes of
8628/// overload resolution.
8629///
8630/// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
8631/// Cand1's first N enable_if attributes have precisely the same conditions as
8632/// Cand2's first N enable_if attributes (where N = the number of enable_if
8633/// attributes on Cand2), and Cand1 has more than N enable_if attributes.
8634///
8635/// Note that you can have a pair of candidates such that Cand1's enable_if
8636/// attributes are worse than Cand2's, and Cand2's enable_if attributes are
8637/// worse than Cand1's.
8638static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
8639 const FunctionDecl *Cand2) {
8640 // Common case: One (or both) decls don't have enable_if attrs.
8641 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
8642 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
8643 if (!Cand1Attr || !Cand2Attr) {
8644 if (Cand1Attr == Cand2Attr)
8645 return Comparison::Equal;
8646 return Cand1Attr ? Comparison::Better : Comparison::Worse;
8647 }
George Burgess IV2a6150d2015-10-16 01:17:38 +00008648
8649 // FIXME: The next several lines are just
8650 // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8651 // instead of reverse order which is how they're stored in the AST.
8652 auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1);
8653 auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2);
8654
George Burgess IV3dc166912016-05-10 01:59:34 +00008655 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
8656 // has fewer enable_if attributes than Cand2.
8657 if (Cand1Attrs.size() < Cand2Attrs.size())
8658 return Comparison::Worse;
George Burgess IV2a6150d2015-10-16 01:17:38 +00008659
8660 auto Cand1I = Cand1Attrs.begin();
8661 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
8662 for (auto &Cand2A : Cand2Attrs) {
8663 Cand1ID.clear();
8664 Cand2ID.clear();
8665
8666 auto &Cand1A = *Cand1I++;
8667 Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true);
8668 Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true);
8669 if (Cand1ID != Cand2ID)
George Burgess IV3dc166912016-05-10 01:59:34 +00008670 return Comparison::Worse;
George Burgess IV2a6150d2015-10-16 01:17:38 +00008671 }
8672
George Burgess IV3dc166912016-05-10 01:59:34 +00008673 return Cand1I == Cand1Attrs.end() ? Comparison::Equal : Comparison::Better;
George Burgess IV2a6150d2015-10-16 01:17:38 +00008674}
8675
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008676/// isBetterOverloadCandidate - Determines whether the first overload
8677/// candidate is a better candidate than the second (C++ 13.3.3p1).
Richard Smith17c00b42014-11-12 01:24:00 +00008678bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1,
8679 const OverloadCandidate &Cand2,
8680 SourceLocation Loc,
8681 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008682 // Define viable functions to be better candidates than non-viable
8683 // functions.
8684 if (!Cand2.Viable)
8685 return Cand1.Viable;
8686 else if (!Cand1.Viable)
8687 return false;
8688
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008689 // C++ [over.match.best]p1:
8690 //
8691 // -- if F is a static member function, ICS1(F) is defined such
8692 // that ICS1(F) is neither better nor worse than ICS1(G) for
8693 // any function G, and, symmetrically, ICS1(G) is neither
8694 // better nor worse than ICS1(F).
8695 unsigned StartArg = 0;
8696 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8697 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008698
George Burgess IVfbad5b22016-09-07 20:03:19 +00008699 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
8700 // We don't allow incompatible pointer conversions in C++.
8701 if (!S.getLangOpts().CPlusPlus)
8702 return ICS.isStandard() &&
8703 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
8704
8705 // The only ill-formed conversion we allow in C++ is the string literal to
8706 // char* conversion, which is only considered ill-formed after C++11.
8707 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
8708 hasDeprecatedStringLiteralToCharPtrConversion(ICS);
8709 };
8710
8711 // Define functions that don't require ill-formed conversions for a given
8712 // argument to be better candidates than functions that do.
8713 unsigned NumArgs = Cand1.NumConversions;
8714 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
8715 bool HasBetterConversion = false;
8716 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
8717 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
8718 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
8719 if (Cand1Bad != Cand2Bad) {
8720 if (Cand1Bad)
8721 return false;
8722 HasBetterConversion = true;
8723 }
8724 }
8725
8726 if (HasBetterConversion)
8727 return true;
8728
Douglas Gregord3cb3562009-07-07 23:38:56 +00008729 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00008730 // A viable function F1 is defined to be a better function than another
8731 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00008732 // conversion sequence than ICSi(F2), and then...
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008733 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Richard Smith0f59cb32015-12-18 21:45:41 +00008734 switch (CompareImplicitConversionSequences(S, Loc,
John McCall5c32be02010-08-24 20:38:10 +00008735 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008736 Cand2.Conversions[ArgIdx])) {
8737 case ImplicitConversionSequence::Better:
8738 // Cand1 has a better conversion sequence.
8739 HasBetterConversion = true;
8740 break;
8741
8742 case ImplicitConversionSequence::Worse:
8743 // Cand1 can't be better than Cand2.
8744 return false;
8745
8746 case ImplicitConversionSequence::Indistinguishable:
8747 // Do nothing.
8748 break;
8749 }
8750 }
8751
Mike Stump11289f42009-09-09 15:08:12 +00008752 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00008753 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008754 if (HasBetterConversion)
8755 return true;
8756
Douglas Gregora1f013e2008-11-07 22:36:19 +00008757 // -- the context is an initialization by user-defined conversion
8758 // (see 8.5, 13.3.1.5) and the standard conversion sequence
8759 // from the return type of F1 to the destination type (i.e.,
8760 // the type of the entity being initialized) is a better
8761 // conversion sequence than the standard conversion sequence
8762 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00008763 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00008764 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00008765 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregor2837aa22012-02-22 17:32:19 +00008766 // First check whether we prefer one of the conversion functions over the
8767 // other. This only distinguishes the results in non-standard, extension
8768 // cases such as the conversion from a lambda closure type to a function
8769 // pointer or block.
Richard Smithec2748a2014-05-17 04:36:39 +00008770 ImplicitConversionSequence::CompareKind Result =
8771 compareConversionFunctions(S, Cand1.Function, Cand2.Function);
8772 if (Result == ImplicitConversionSequence::Indistinguishable)
Richard Smith0f59cb32015-12-18 21:45:41 +00008773 Result = CompareStandardConversionSequences(S, Loc,
Richard Smithec2748a2014-05-17 04:36:39 +00008774 Cand1.FinalConversion,
8775 Cand2.FinalConversion);
Richard Smith6fdeaab2014-05-17 01:58:45 +00008776
Richard Smithec2748a2014-05-17 04:36:39 +00008777 if (Result != ImplicitConversionSequence::Indistinguishable)
8778 return Result == ImplicitConversionSequence::Better;
Richard Smith6fdeaab2014-05-17 01:58:45 +00008779
8780 // FIXME: Compare kind of reference binding if conversion functions
8781 // convert to a reference type used in direct reference binding, per
8782 // C++14 [over.match.best]p1 section 2 bullet 3.
8783 }
8784
8785 // -- F1 is a non-template function and F2 is a function template
8786 // specialization, or, if not that,
8787 bool Cand1IsSpecialization = Cand1.Function &&
8788 Cand1.Function->getPrimaryTemplate();
8789 bool Cand2IsSpecialization = Cand2.Function &&
8790 Cand2.Function->getPrimaryTemplate();
8791 if (Cand1IsSpecialization != Cand2IsSpecialization)
8792 return Cand2IsSpecialization;
8793
8794 // -- F1 and F2 are function template specializations, and the function
8795 // template for F1 is more specialized than the template for F2
8796 // according to the partial ordering rules described in 14.5.5.2, or,
8797 // if not that,
8798 if (Cand1IsSpecialization && Cand2IsSpecialization) {
8799 if (FunctionTemplateDecl *BetterTemplate
8800 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
8801 Cand2.Function->getPrimaryTemplate(),
8802 Loc,
8803 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
8804 : TPOC_Call,
8805 Cand1.ExplicitCallArguments,
8806 Cand2.ExplicitCallArguments))
8807 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregora1f013e2008-11-07 22:36:19 +00008808 }
8809
Richard Smith5179eb72016-06-28 19:03:57 +00008810 // FIXME: Work around a defect in the C++17 inheriting constructor wording.
8811 // A derived-class constructor beats an (inherited) base class constructor.
8812 bool Cand1IsInherited =
8813 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
8814 bool Cand2IsInherited =
8815 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
8816 if (Cand1IsInherited != Cand2IsInherited)
8817 return Cand2IsInherited;
8818 else if (Cand1IsInherited) {
8819 assert(Cand2IsInherited);
8820 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
8821 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
8822 if (Cand1Class->isDerivedFrom(Cand2Class))
8823 return true;
8824 if (Cand2Class->isDerivedFrom(Cand1Class))
8825 return false;
8826 // Inherited from sibling base classes: still ambiguous.
8827 }
8828
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008829 // Check for enable_if value-based overload resolution.
George Burgess IV3dc166912016-05-10 01:59:34 +00008830 if (Cand1.Function && Cand2.Function) {
8831 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
8832 if (Cmp != Comparison::Equal)
8833 return Cmp == Comparison::Better;
8834 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008835
Justin Lebar25c4a812016-03-29 16:24:16 +00008836 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
Artem Belevich94a55e82015-09-22 17:22:59 +00008837 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
8838 return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
8839 S.IdentifyCUDAPreference(Caller, Cand2.Function);
8840 }
8841
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008842 bool HasPS1 = Cand1.Function != nullptr &&
8843 functionHasPassObjectSizeParams(Cand1.Function);
8844 bool HasPS2 = Cand2.Function != nullptr &&
8845 functionHasPassObjectSizeParams(Cand2.Function);
8846 return HasPS1 != HasPS2 && HasPS1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008847}
8848
Richard Smith2dbe4042015-11-04 19:26:32 +00008849/// Determine whether two declarations are "equivalent" for the purposes of
Richard Smith26210db2015-11-13 03:52:13 +00008850/// name lookup and overload resolution. This applies when the same internal/no
8851/// linkage entity is defined by two modules (probably by textually including
Richard Smith2dbe4042015-11-04 19:26:32 +00008852/// the same header). In such a case, we don't consider the declarations to
8853/// declare the same entity, but we also don't want lookups with both
8854/// declarations visible to be ambiguous in some cases (this happens when using
8855/// a modularized libstdc++).
8856bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
8857 const NamedDecl *B) {
Richard Smith26210db2015-11-13 03:52:13 +00008858 auto *VA = dyn_cast_or_null<ValueDecl>(A);
8859 auto *VB = dyn_cast_or_null<ValueDecl>(B);
8860 if (!VA || !VB)
8861 return false;
8862
8863 // The declarations must be declaring the same name as an internal linkage
8864 // entity in different modules.
8865 if (!VA->getDeclContext()->getRedeclContext()->Equals(
8866 VB->getDeclContext()->getRedeclContext()) ||
8867 getOwningModule(const_cast<ValueDecl *>(VA)) ==
8868 getOwningModule(const_cast<ValueDecl *>(VB)) ||
8869 VA->isExternallyVisible() || VB->isExternallyVisible())
8870 return false;
8871
8872 // Check that the declarations appear to be equivalent.
8873 //
8874 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
8875 // For constants and functions, we should check the initializer or body is
8876 // the same. For non-constant variables, we shouldn't allow it at all.
8877 if (Context.hasSameType(VA->getType(), VB->getType()))
8878 return true;
8879
8880 // Enum constants within unnamed enumerations will have different types, but
8881 // may still be similar enough to be interchangeable for our purposes.
8882 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
8883 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
8884 // Only handle anonymous enums. If the enumerations were named and
8885 // equivalent, they would have been merged to the same type.
8886 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
8887 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
8888 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
8889 !Context.hasSameType(EnumA->getIntegerType(),
8890 EnumB->getIntegerType()))
8891 return false;
8892 // Allow this only if the value is the same for both enumerators.
8893 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
8894 }
8895 }
8896
8897 // Nothing else is sufficiently similar.
8898 return false;
Richard Smith2dbe4042015-11-04 19:26:32 +00008899}
8900
8901void Sema::diagnoseEquivalentInternalLinkageDeclarations(
8902 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
8903 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
8904
8905 Module *M = getOwningModule(const_cast<NamedDecl*>(D));
8906 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
8907 << !M << (M ? M->getFullModuleName() : "");
8908
8909 for (auto *E : Equiv) {
8910 Module *M = getOwningModule(const_cast<NamedDecl*>(E));
8911 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
8912 << !M << (M ? M->getFullModuleName() : "");
8913 }
Richard Smith896c66e2015-10-21 07:13:52 +00008914}
8915
Mike Stump11289f42009-09-09 15:08:12 +00008916/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008917/// within an overload candidate set.
8918///
James Dennettffad8b72012-06-22 08:10:18 +00008919/// \param Loc The location of the function name (or operator symbol) for
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008920/// which overload resolution occurs.
8921///
James Dennettffad8b72012-06-22 08:10:18 +00008922/// \param Best If overload resolution was successful or found a deleted
8923/// function, \p Best points to the candidate function found.
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008924///
8925/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00008926OverloadingResult
8927OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00008928 iterator &Best,
Chandler Carruth30141632011-02-25 19:41:05 +00008929 bool UserDefinedConversion) {
Artem Belevich18609102016-02-12 18:29:18 +00008930 llvm::SmallVector<OverloadCandidate *, 16> Candidates;
8931 std::transform(begin(), end(), std::back_inserter(Candidates),
8932 [](OverloadCandidate &Cand) { return &Cand; });
8933
Justin Lebar66a2ab92016-08-10 00:40:43 +00008934 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
8935 // are accepted by both clang and NVCC. However, during a particular
Artem Belevich18609102016-02-12 18:29:18 +00008936 // compilation mode only one call variant is viable. We need to
8937 // exclude non-viable overload candidates from consideration based
8938 // only on their host/device attributes. Specifically, if one
8939 // candidate call is WrongSide and the other is SameSide, we ignore
8940 // the WrongSide candidate.
Justin Lebar25c4a812016-03-29 16:24:16 +00008941 if (S.getLangOpts().CUDA) {
Artem Belevich18609102016-02-12 18:29:18 +00008942 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
8943 bool ContainsSameSideCandidate =
8944 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
8945 return Cand->Function &&
8946 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
8947 Sema::CFP_SameSide;
8948 });
8949 if (ContainsSameSideCandidate) {
8950 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
8951 return Cand->Function &&
8952 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
8953 Sema::CFP_WrongSide;
8954 };
8955 Candidates.erase(std::remove_if(Candidates.begin(), Candidates.end(),
8956 IsWrongSideCandidate),
8957 Candidates.end());
8958 }
8959 }
8960
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008961 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00008962 Best = end();
Artem Belevich18609102016-02-12 18:29:18 +00008963 for (auto *Cand : Candidates)
John McCall5c32be02010-08-24 20:38:10 +00008964 if (Cand->Viable)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008965 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00008966 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008967 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008968
8969 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00008970 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008971 return OR_No_Viable_Function;
8972
Richard Smith2dbe4042015-11-04 19:26:32 +00008973 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
Richard Smith896c66e2015-10-21 07:13:52 +00008974
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008975 // Make sure that this function is better than every other viable
8976 // function. If not, we have an ambiguity.
Artem Belevich18609102016-02-12 18:29:18 +00008977 for (auto *Cand : Candidates) {
Mike Stump11289f42009-09-09 15:08:12 +00008978 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008979 Cand != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008980 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00008981 UserDefinedConversion)) {
Richard Smith2dbe4042015-11-04 19:26:32 +00008982 if (S.isEquivalentInternalLinkageDeclaration(Best->Function,
8983 Cand->Function)) {
8984 EquivalentCands.push_back(Cand->Function);
Richard Smith896c66e2015-10-21 07:13:52 +00008985 continue;
8986 }
8987
John McCall5c32be02010-08-24 20:38:10 +00008988 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008989 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00008990 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008991 }
Mike Stump11289f42009-09-09 15:08:12 +00008992
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008993 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00008994 if (Best->Function &&
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00008995 (Best->Function->isDeleted() ||
8996 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor171c45a2009-02-18 21:56:37 +00008997 return OR_Deleted;
8998
Richard Smith2dbe4042015-11-04 19:26:32 +00008999 if (!EquivalentCands.empty())
9000 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
9001 EquivalentCands);
Richard Smith896c66e2015-10-21 07:13:52 +00009002
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009003 return OR_Success;
9004}
9005
John McCall53262c92010-01-12 02:15:36 +00009006namespace {
9007
9008enum OverloadCandidateKind {
9009 oc_function,
9010 oc_method,
9011 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00009012 oc_function_template,
9013 oc_method_template,
9014 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00009015 oc_implicit_default_constructor,
9016 oc_implicit_copy_constructor,
Alexis Hunt119c10e2011-05-25 23:16:36 +00009017 oc_implicit_move_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00009018 oc_implicit_copy_assignment,
Alexis Hunt119c10e2011-05-25 23:16:36 +00009019 oc_implicit_move_assignment,
Richard Smith5179eb72016-06-28 19:03:57 +00009020 oc_inherited_constructor,
9021 oc_inherited_constructor_template
John McCall53262c92010-01-12 02:15:36 +00009022};
9023
George Burgess IVd66d37c2016-10-28 21:42:06 +00009024static OverloadCandidateKind
9025ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
9026 std::string &Description) {
John McCalle1ac8d12010-01-13 00:25:19 +00009027 bool isTemplate = false;
9028
9029 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
9030 isTemplate = true;
9031 Description = S.getTemplateArgumentBindingsText(
9032 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
9033 }
John McCallfd0b2f82010-01-06 09:43:14 +00009034
9035 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
Richard Smith5179eb72016-06-28 19:03:57 +00009036 if (!Ctor->isImplicit()) {
9037 if (isa<ConstructorUsingShadowDecl>(Found))
9038 return isTemplate ? oc_inherited_constructor_template
9039 : oc_inherited_constructor;
9040 else
9041 return isTemplate ? oc_constructor_template : oc_constructor;
9042 }
Sebastian Redl08905022011-02-05 19:23:19 +00009043
Alexis Hunt119c10e2011-05-25 23:16:36 +00009044 if (Ctor->isDefaultConstructor())
9045 return oc_implicit_default_constructor;
9046
9047 if (Ctor->isMoveConstructor())
9048 return oc_implicit_move_constructor;
9049
9050 assert(Ctor->isCopyConstructor() &&
9051 "unexpected sort of implicit constructor");
9052 return oc_implicit_copy_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00009053 }
9054
9055 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
9056 // This actually gets spelled 'candidate function' for now, but
9057 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00009058 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00009059 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00009060
Alexis Hunt119c10e2011-05-25 23:16:36 +00009061 if (Meth->isMoveAssignmentOperator())
9062 return oc_implicit_move_assignment;
9063
Douglas Gregor12695102012-02-10 08:36:38 +00009064 if (Meth->isCopyAssignmentOperator())
9065 return oc_implicit_copy_assignment;
9066
9067 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
9068 return oc_method;
John McCall53262c92010-01-12 02:15:36 +00009069 }
9070
John McCalle1ac8d12010-01-13 00:25:19 +00009071 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00009072}
9073
Richard Smith5179eb72016-06-28 19:03:57 +00009074void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
9075 // FIXME: It'd be nice to only emit a note once per using-decl per overload
9076 // set.
9077 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
9078 S.Diag(FoundDecl->getLocation(),
9079 diag::note_ovl_candidate_inherited_constructor)
9080 << Shadow->getNominatedBaseClass();
Sebastian Redl08905022011-02-05 19:23:19 +00009081}
9082
John McCall53262c92010-01-12 02:15:36 +00009083} // end anonymous namespace
9084
George Burgess IV5f21c712015-10-12 19:57:04 +00009085static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
9086 const FunctionDecl *FD) {
9087 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
9088 bool AlwaysTrue;
9089 if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
9090 return false;
9091 if (!AlwaysTrue)
9092 return false;
9093 }
9094 return true;
9095}
9096
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009097/// \brief Returns true if we can take the address of the function.
9098///
9099/// \param Complain - If true, we'll emit a diagnostic
9100/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
9101/// we in overload resolution?
9102/// \param Loc - The location of the statement we're complaining about. Ignored
9103/// if we're not complaining, or if we're in overload resolution.
9104static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
9105 bool Complain,
9106 bool InOverloadResolution,
9107 SourceLocation Loc) {
9108 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
9109 if (Complain) {
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009110 if (InOverloadResolution)
9111 S.Diag(FD->getLocStart(),
9112 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
9113 else
9114 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
9115 }
9116 return false;
9117 }
9118
George Burgess IV21081362016-07-24 23:12:40 +00009119 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
9120 return P->hasAttr<PassObjectSizeAttr>();
9121 });
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009122 if (I == FD->param_end())
9123 return true;
9124
9125 if (Complain) {
9126 // Add one to ParamNo because it's user-facing
9127 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
9128 if (InOverloadResolution)
9129 S.Diag(FD->getLocation(),
9130 diag::note_ovl_candidate_has_pass_object_size_params)
9131 << ParamNo;
9132 else
9133 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
9134 << FD << ParamNo;
9135 }
9136 return false;
9137}
9138
9139static bool checkAddressOfCandidateIsAvailable(Sema &S,
9140 const FunctionDecl *FD) {
9141 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
9142 /*InOverloadResolution=*/true,
9143 /*Loc=*/SourceLocation());
9144}
9145
9146bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
9147 bool Complain,
9148 SourceLocation Loc) {
9149 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
9150 /*InOverloadResolution=*/false,
9151 Loc);
9152}
9153
John McCall53262c92010-01-12 02:15:36 +00009154// Notes the location of an overload candidate.
Richard Smithc2bebe92016-05-11 20:37:46 +00009155void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
9156 QualType DestType, bool TakingAddress) {
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009157 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
9158 return;
9159
John McCalle1ac8d12010-01-13 00:25:19 +00009160 std::string FnDesc;
Richard Smithc2bebe92016-05-11 20:37:46 +00009161 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Found, Fn, FnDesc);
Richard Trieucaff2472011-11-23 22:32:32 +00009162 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
9163 << (unsigned) K << FnDesc;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009164
9165 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
Richard Trieucaff2472011-11-23 22:32:32 +00009166 Diag(Fn->getLocation(), PD);
Richard Smith5179eb72016-06-28 19:03:57 +00009167 MaybeEmitInheritedConstructorNote(*this, Found);
John McCallfd0b2f82010-01-06 09:43:14 +00009168}
9169
Nick Lewyckyed4265c2013-09-22 10:06:01 +00009170// Notes the location of all overload candidates designated through
Douglas Gregorb491ed32011-02-19 21:32:49 +00009171// OverloadedExpr
George Burgess IV5f21c712015-10-12 19:57:04 +00009172void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
9173 bool TakingAddress) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009174 assert(OverloadedExpr->getType() == Context.OverloadTy);
9175
9176 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
9177 OverloadExpr *OvlExpr = Ovl.Expression;
9178
9179 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9180 IEnd = OvlExpr->decls_end();
9181 I != IEnd; ++I) {
9182 if (FunctionTemplateDecl *FunTmpl =
9183 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Smithc2bebe92016-05-11 20:37:46 +00009184 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType,
George Burgess IV5f21c712015-10-12 19:57:04 +00009185 TakingAddress);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009186 } else if (FunctionDecl *Fun
9187 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Smithc2bebe92016-05-11 20:37:46 +00009188 NoteOverloadCandidate(*I, Fun, DestType, TakingAddress);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009189 }
9190 }
9191}
9192
John McCall0d1da222010-01-12 00:44:57 +00009193/// Diagnoses an ambiguous conversion. The partial diagnostic is the
9194/// "lead" diagnostic; it will be given two arguments, the source and
9195/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00009196void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
9197 Sema &S,
9198 SourceLocation CaretLoc,
9199 const PartialDiagnostic &PDiag) const {
9200 S.Diag(CaretLoc, PDiag)
9201 << Ambiguous.getFromType() << Ambiguous.getToType();
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00009202 // FIXME: The note limiting machinery is borrowed from
9203 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
9204 // refactoring here.
9205 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9206 unsigned CandsShown = 0;
9207 AmbiguousConversionSequence::const_iterator I, E;
9208 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
9209 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9210 break;
9211 ++CandsShown;
Richard Smithc2bebe92016-05-11 20:37:46 +00009212 S.NoteOverloadCandidate(I->first, I->second);
John McCall0d1da222010-01-12 00:44:57 +00009213 }
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00009214 if (I != E)
9215 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
John McCall12f97bc2010-01-08 04:41:39 +00009216}
9217
Richard Smith17c00b42014-11-12 01:24:00 +00009218static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009219 unsigned I, bool TakingCandidateAddress) {
John McCall6a61b522010-01-13 09:16:55 +00009220 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
9221 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00009222 assert(Cand->Function && "for now, candidate must be a function");
9223 FunctionDecl *Fn = Cand->Function;
9224
9225 // There's a conversion slot for the object argument if this is a
9226 // non-constructor method. Note that 'I' corresponds the
9227 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00009228 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00009229 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00009230 if (I == 0)
9231 isObjectArgument = true;
9232 else
9233 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00009234 }
9235
John McCalle1ac8d12010-01-13 00:25:19 +00009236 std::string FnDesc;
Richard Smithc2bebe92016-05-11 20:37:46 +00009237 OverloadCandidateKind FnKind =
9238 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
John McCalle1ac8d12010-01-13 00:25:19 +00009239
John McCall6a61b522010-01-13 09:16:55 +00009240 Expr *FromExpr = Conv.Bad.FromExpr;
9241 QualType FromTy = Conv.Bad.getFromType();
9242 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00009243
John McCallfb7ad0f2010-02-02 02:42:52 +00009244 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00009245 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00009246 Expr *E = FromExpr->IgnoreParens();
9247 if (isa<UnaryOperator>(E))
9248 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00009249 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00009250
9251 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
9252 << (unsigned) FnKind << FnDesc
9253 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9254 << ToTy << Name << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009255 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCallfb7ad0f2010-02-02 02:42:52 +00009256 return;
9257 }
9258
John McCall6d174642010-01-23 08:10:49 +00009259 // Do some hand-waving analysis to see if the non-viability is due
9260 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00009261 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
9262 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
9263 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
9264 CToTy = RT->getPointeeType();
9265 else {
9266 // TODO: detect and diagnose the full richness of const mismatches.
9267 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
Richard Trieucc3949d2016-02-18 22:34:54 +00009268 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
9269 CFromTy = FromPT->getPointeeType();
9270 CToTy = ToPT->getPointeeType();
9271 }
John McCall47000992010-01-14 03:28:57 +00009272 }
9273
9274 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
9275 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall47000992010-01-14 03:28:57 +00009276 Qualifiers FromQs = CFromTy.getQualifiers();
9277 Qualifiers ToQs = CToTy.getQualifiers();
9278
9279 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
9280 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
9281 << (unsigned) FnKind << FnDesc
9282 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9283 << FromTy
9284 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
9285 << (unsigned) isObjectArgument << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009286 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall47000992010-01-14 03:28:57 +00009287 return;
9288 }
9289
John McCall31168b02011-06-15 23:02:42 +00009290 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00009291 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCall31168b02011-06-15 23:02:42 +00009292 << (unsigned) FnKind << FnDesc
9293 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9294 << FromTy
9295 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
9296 << (unsigned) isObjectArgument << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009297 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall31168b02011-06-15 23:02:42 +00009298 return;
9299 }
9300
Douglas Gregoraec25842011-04-26 23:16:46 +00009301 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
9302 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
9303 << (unsigned) FnKind << FnDesc
9304 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9305 << FromTy
9306 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
9307 << (unsigned) isObjectArgument << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009308 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Douglas Gregoraec25842011-04-26 23:16:46 +00009309 return;
9310 }
9311
Andrey Bokhanko45d41322016-05-11 18:38:21 +00009312 if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
9313 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
9314 << (unsigned) FnKind << FnDesc
9315 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9316 << FromTy << FromQs.hasUnaligned() << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009317 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Andrey Bokhanko45d41322016-05-11 18:38:21 +00009318 return;
9319 }
9320
John McCall47000992010-01-14 03:28:57 +00009321 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
9322 assert(CVR && "unexpected qualifiers mismatch");
9323
9324 if (isObjectArgument) {
9325 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
9326 << (unsigned) FnKind << FnDesc
9327 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9328 << FromTy << (CVR - 1);
9329 } else {
9330 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
9331 << (unsigned) FnKind << FnDesc
9332 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9333 << FromTy << (CVR - 1) << I+1;
9334 }
Richard Smith5179eb72016-06-28 19:03:57 +00009335 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall47000992010-01-14 03:28:57 +00009336 return;
9337 }
9338
Sebastian Redla72462c2011-09-24 17:48:32 +00009339 // Special diagnostic for failure to convert an initializer list, since
9340 // telling the user that it has type void is not useful.
9341 if (FromExpr && isa<InitListExpr>(FromExpr)) {
9342 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
9343 << (unsigned) FnKind << FnDesc
9344 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9345 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009346 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Sebastian Redla72462c2011-09-24 17:48:32 +00009347 return;
9348 }
9349
John McCall6d174642010-01-23 08:10:49 +00009350 // Diagnose references or pointers to incomplete types differently,
9351 // since it's far from impossible that the incompleteness triggered
9352 // the failure.
9353 QualType TempFromTy = FromTy.getNonReferenceType();
9354 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
9355 TempFromTy = PTy->getPointeeType();
9356 if (TempFromTy->isIncompleteType()) {
David Blaikieac928932016-03-04 22:29:11 +00009357 // Emit the generic diagnostic and, optionally, add the hints to it.
John McCall6d174642010-01-23 08:10:49 +00009358 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
9359 << (unsigned) FnKind << FnDesc
9360 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
David Blaikieac928932016-03-04 22:29:11 +00009361 << FromTy << ToTy << (unsigned) isObjectArgument << I+1
9362 << (unsigned) (Cand->Fix.Kind);
9363
Richard Smith5179eb72016-06-28 19:03:57 +00009364 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall6d174642010-01-23 08:10:49 +00009365 return;
9366 }
9367
Douglas Gregor56f2e342010-06-30 23:01:39 +00009368 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009369 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00009370 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
9371 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
9372 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9373 FromPtrTy->getPointeeType()) &&
9374 !FromPtrTy->getPointeeType()->isIncompleteType() &&
9375 !ToPtrTy->getPointeeType()->isIncompleteType() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00009376 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00009377 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009378 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00009379 }
9380 } else if (const ObjCObjectPointerType *FromPtrTy
9381 = FromTy->getAs<ObjCObjectPointerType>()) {
9382 if (const ObjCObjectPointerType *ToPtrTy
9383 = ToTy->getAs<ObjCObjectPointerType>())
9384 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
9385 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
9386 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9387 FromPtrTy->getPointeeType()) &&
9388 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009389 BaseToDerivedConversion = 2;
9390 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009391 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
9392 !FromTy->isIncompleteType() &&
9393 !ToRefTy->getPointeeType()->isIncompleteType() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00009394 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009395 BaseToDerivedConversion = 3;
9396 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
9397 ToTy.getNonReferenceType().getCanonicalType() ==
9398 FromTy.getNonReferenceType().getCanonicalType()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009399 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
9400 << (unsigned) FnKind << FnDesc
9401 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9402 << (unsigned) isObjectArgument << I + 1;
Richard Smith5179eb72016-06-28 19:03:57 +00009403 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009404 return;
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009405 }
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009406 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009407
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009408 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009409 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009410 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00009411 << (unsigned) FnKind << FnDesc
9412 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009413 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009414 << FromTy << ToTy << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009415 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Douglas Gregor56f2e342010-06-30 23:01:39 +00009416 return;
9417 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009418
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00009419 if (isa<ObjCObjectPointerType>(CFromTy) &&
9420 isa<PointerType>(CToTy)) {
9421 Qualifiers FromQs = CFromTy.getQualifiers();
9422 Qualifiers ToQs = CToTy.getQualifiers();
9423 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9424 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
9425 << (unsigned) FnKind << FnDesc
9426 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9427 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009428 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00009429 return;
9430 }
9431 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009432
9433 if (TakingCandidateAddress &&
9434 !checkAddressOfCandidateIsAvailable(S, Cand->Function))
9435 return;
9436
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009437 // Emit the generic diagnostic and, optionally, add the hints to it.
9438 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
9439 FDiag << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00009440 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009441 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
9442 << (unsigned) (Cand->Fix.Kind);
9443
9444 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer490afa62012-01-14 21:05:10 +00009445 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
9446 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009447 FDiag << *HI;
9448 S.Diag(Fn->getLocation(), FDiag);
9449
Richard Smith5179eb72016-06-28 19:03:57 +00009450 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall6a61b522010-01-13 09:16:55 +00009451}
9452
Larisse Voufo98b20f12013-07-19 23:00:19 +00009453/// Additional arity mismatch diagnosis specific to a function overload
9454/// candidates. This is not covered by the more general DiagnoseArityMismatch()
9455/// over a candidate in any candidate set.
Richard Smith17c00b42014-11-12 01:24:00 +00009456static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
9457 unsigned NumArgs) {
John McCall6a61b522010-01-13 09:16:55 +00009458 FunctionDecl *Fn = Cand->Function;
John McCall6a61b522010-01-13 09:16:55 +00009459 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009460
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009461 // With invalid overloaded operators, it's possible that we think we
Larisse Voufo98b20f12013-07-19 23:00:19 +00009462 // have an arity mismatch when in fact it looks like we have the
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009463 // right number of arguments, because only overloaded operators have
9464 // the weird behavior of overloading member and non-member functions.
9465 // Just don't report anything.
9466 if (Fn->isInvalidDecl() &&
9467 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009468 return true;
9469
9470 if (NumArgs < MinParams) {
9471 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
9472 (Cand->FailureKind == ovl_fail_bad_deduction &&
9473 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
9474 } else {
9475 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
9476 (Cand->FailureKind == ovl_fail_bad_deduction &&
9477 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
9478 }
9479
9480 return false;
9481}
9482
9483/// General arity mismatch diagnosis over a candidate in a candidate set.
Richard Smithc2bebe92016-05-11 20:37:46 +00009484static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
9485 unsigned NumFormalArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009486 assert(isa<FunctionDecl>(D) &&
9487 "The templated declaration should at least be a function"
9488 " when diagnosing bad template argument deduction due to too many"
9489 " or too few arguments");
9490
9491 FunctionDecl *Fn = cast<FunctionDecl>(D);
9492
9493 // TODO: treat calls to a missing default constructor as a special case
9494 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
9495 unsigned MinParams = Fn->getMinRequiredArguments();
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009496
John McCall6a61b522010-01-13 09:16:55 +00009497 // at least / at most / exactly
9498 unsigned mode, modeCount;
9499 if (NumFormalArgs < MinParams) {
Alp Toker9cacbab2014-01-20 20:26:09 +00009500 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
9501 FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00009502 mode = 0; // "at least"
9503 else
9504 mode = 2; // "exactly"
9505 modeCount = MinParams;
9506 } else {
Alp Toker9cacbab2014-01-20 20:26:09 +00009507 if (MinParams != FnTy->getNumParams())
John McCall6a61b522010-01-13 09:16:55 +00009508 mode = 1; // "at most"
9509 else
9510 mode = 2; // "exactly"
Alp Toker9cacbab2014-01-20 20:26:09 +00009511 modeCount = FnTy->getNumParams();
John McCall6a61b522010-01-13 09:16:55 +00009512 }
9513
9514 std::string Description;
Richard Smithc2bebe92016-05-11 20:37:46 +00009515 OverloadCandidateKind FnKind =
9516 ClassifyOverloadCandidate(S, Found, Fn, Description);
John McCall6a61b522010-01-13 09:16:55 +00009517
Richard Smith10ff50d2012-05-11 05:16:41 +00009518 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
9519 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
Craig Topperc3ec1492014-05-26 06:22:03 +00009520 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9521 << mode << Fn->getParamDecl(0) << NumFormalArgs;
Richard Smith10ff50d2012-05-11 05:16:41 +00009522 else
9523 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Craig Topperc3ec1492014-05-26 06:22:03 +00009524 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9525 << mode << modeCount << NumFormalArgs;
Richard Smith5179eb72016-06-28 19:03:57 +00009526 MaybeEmitInheritedConstructorNote(S, Found);
John McCalle1ac8d12010-01-13 00:25:19 +00009527}
9528
Larisse Voufo98b20f12013-07-19 23:00:19 +00009529/// Arity mismatch diagnosis specific to a function overload candidate.
Richard Smith17c00b42014-11-12 01:24:00 +00009530static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
9531 unsigned NumFormalArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009532 if (!CheckArityMismatch(S, Cand, NumFormalArgs))
Richard Smithc2bebe92016-05-11 20:37:46 +00009533 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
Larisse Voufo98b20f12013-07-19 23:00:19 +00009534}
Larisse Voufo47c08452013-07-19 22:53:23 +00009535
Richard Smith17c00b42014-11-12 01:24:00 +00009536static TemplateDecl *getDescribedTemplate(Decl *Templated) {
Serge Pavlov7dcc97e2016-04-19 06:19:52 +00009537 if (TemplateDecl *TD = Templated->getDescribedTemplate())
9538 return TD;
Larisse Voufo98b20f12013-07-19 23:00:19 +00009539 llvm_unreachable("Unsupported: Getting the described template declaration"
9540 " for bad deduction diagnosis");
9541}
9542
9543/// Diagnose a failed template-argument deduction.
Richard Smithc2bebe92016-05-11 20:37:46 +00009544static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
Richard Smith17c00b42014-11-12 01:24:00 +00009545 DeductionFailureInfo &DeductionFailure,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009546 unsigned NumArgs,
9547 bool TakingCandidateAddress) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009548 TemplateParameter Param = DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009549 NamedDecl *ParamD;
9550 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
9551 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
9552 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
Larisse Voufo98b20f12013-07-19 23:00:19 +00009553 switch (DeductionFailure.Result) {
John McCall8b9ed552010-02-01 18:53:26 +00009554 case Sema::TDK_Success:
9555 llvm_unreachable("TDK_success while diagnosing bad deduction");
9556
9557 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00009558 assert(ParamD && "no parameter found for incomplete deduction result");
Larisse Voufo98b20f12013-07-19 23:00:19 +00009559 S.Diag(Templated->getLocation(),
9560 diag::note_ovl_candidate_incomplete_deduction)
9561 << ParamD->getDeclName();
Richard Smith5179eb72016-06-28 19:03:57 +00009562 MaybeEmitInheritedConstructorNote(S, Found);
John McCall8b9ed552010-02-01 18:53:26 +00009563 return;
9564 }
9565
John McCall42d7d192010-08-05 09:05:08 +00009566 case Sema::TDK_Underqualified: {
9567 assert(ParamD && "no parameter found for bad qualifiers deduction result");
9568 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
9569
Larisse Voufo98b20f12013-07-19 23:00:19 +00009570 QualType Param = DeductionFailure.getFirstArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00009571
9572 // Param will have been canonicalized, but it should just be a
9573 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00009574 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00009575 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00009576 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00009577 assert(S.Context.hasSameType(Param, NonCanonParam));
9578
9579 // Arg has also been canonicalized, but there's nothing we can do
9580 // about that. It also doesn't matter as much, because it won't
9581 // have any template parameters in it (because deduction isn't
9582 // done on dependent types).
Larisse Voufo98b20f12013-07-19 23:00:19 +00009583 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00009584
Larisse Voufo98b20f12013-07-19 23:00:19 +00009585 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
9586 << ParamD->getDeclName() << Arg << NonCanonParam;
Richard Smith5179eb72016-06-28 19:03:57 +00009587 MaybeEmitInheritedConstructorNote(S, Found);
John McCall42d7d192010-08-05 09:05:08 +00009588 return;
9589 }
9590
9591 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00009592 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009593 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009594 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009595 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009596 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009597 which = 1;
9598 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009599 which = 2;
9600 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009601
Larisse Voufo98b20f12013-07-19 23:00:19 +00009602 S.Diag(Templated->getLocation(),
9603 diag::note_ovl_candidate_inconsistent_deduction)
9604 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
9605 << *DeductionFailure.getSecondArg();
Richard Smith5179eb72016-06-28 19:03:57 +00009606 MaybeEmitInheritedConstructorNote(S, Found);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009607 return;
9608 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00009609
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009610 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009611 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009612 if (ParamD->getDeclName())
Larisse Voufo98b20f12013-07-19 23:00:19 +00009613 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009614 diag::note_ovl_candidate_explicit_arg_mismatch_named)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009615 << ParamD->getDeclName();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009616 else {
9617 int index = 0;
9618 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
9619 index = TTP->getIndex();
9620 else if (NonTypeTemplateParmDecl *NTTP
9621 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
9622 index = NTTP->getIndex();
9623 else
9624 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
Larisse Voufo98b20f12013-07-19 23:00:19 +00009625 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009626 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009627 << (index + 1);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009628 }
Richard Smith5179eb72016-06-28 19:03:57 +00009629 MaybeEmitInheritedConstructorNote(S, Found);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009630 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009631
Douglas Gregor02eb4832010-05-08 18:13:28 +00009632 case Sema::TDK_TooManyArguments:
9633 case Sema::TDK_TooFewArguments:
Richard Smithc2bebe92016-05-11 20:37:46 +00009634 DiagnoseArityMismatch(S, Found, Templated, NumArgs);
Douglas Gregor02eb4832010-05-08 18:13:28 +00009635 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00009636
9637 case Sema::TDK_InstantiationDepth:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009638 S.Diag(Templated->getLocation(),
9639 diag::note_ovl_candidate_instantiation_depth);
Richard Smith5179eb72016-06-28 19:03:57 +00009640 MaybeEmitInheritedConstructorNote(S, Found);
Douglas Gregord09efd42010-05-08 20:07:26 +00009641 return;
9642
9643 case Sema::TDK_SubstitutionFailure: {
Richard Smith9ca64612012-05-07 09:03:25 +00009644 // Format the template argument list into the argument string.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009645 SmallString<128> TemplateArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00009646 if (TemplateArgumentList *Args =
Larisse Voufo98b20f12013-07-19 23:00:19 +00009647 DeductionFailure.getTemplateArgumentList()) {
Richard Smith9ca64612012-05-07 09:03:25 +00009648 TemplateArgString = " ";
9649 TemplateArgString += S.getTemplateArgumentBindingsText(
Larisse Voufo98b20f12013-07-19 23:00:19 +00009650 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
Richard Smith9ca64612012-05-07 09:03:25 +00009651 }
9652
Richard Smith6f8d2c62012-05-09 05:17:00 +00009653 // If this candidate was disabled by enable_if, say so.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009654 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
Richard Smith6f8d2c62012-05-09 05:17:00 +00009655 if (PDiag && PDiag->second.getDiagID() ==
9656 diag::err_typename_nested_not_found_enable_if) {
9657 // FIXME: Use the source range of the condition, and the fully-qualified
9658 // name of the enable_if template. These are both present in PDiag.
9659 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
9660 << "'enable_if'" << TemplateArgString;
9661 return;
9662 }
9663
Richard Smith9ca64612012-05-07 09:03:25 +00009664 // Format the SFINAE diagnostic into the argument string.
9665 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
9666 // formatted message in another diagnostic.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009667 SmallString<128> SFINAEArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00009668 SourceRange R;
Richard Smith6f8d2c62012-05-09 05:17:00 +00009669 if (PDiag) {
Richard Smith9ca64612012-05-07 09:03:25 +00009670 SFINAEArgString = ": ";
9671 R = SourceRange(PDiag->first, PDiag->first);
9672 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
9673 }
9674
Larisse Voufo98b20f12013-07-19 23:00:19 +00009675 S.Diag(Templated->getLocation(),
9676 diag::note_ovl_candidate_substitution_failure)
9677 << TemplateArgString << SFINAEArgString << R;
Richard Smith5179eb72016-06-28 19:03:57 +00009678 MaybeEmitInheritedConstructorNote(S, Found);
Douglas Gregord09efd42010-05-08 20:07:26 +00009679 return;
9680 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009681
Richard Smith8c6eeb92013-01-31 04:03:12 +00009682 case Sema::TDK_FailedOverloadResolution: {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009683 OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr());
9684 S.Diag(Templated->getLocation(),
Richard Smith8c6eeb92013-01-31 04:03:12 +00009685 diag::note_ovl_candidate_failed_overload_resolution)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009686 << R.Expression->getName();
Richard Smith8c6eeb92013-01-31 04:03:12 +00009687 return;
9688 }
9689
Richard Smith9b534542015-12-31 02:02:54 +00009690 case Sema::TDK_DeducedMismatch: {
9691 // Format the template argument list into the argument string.
9692 SmallString<128> TemplateArgString;
9693 if (TemplateArgumentList *Args =
9694 DeductionFailure.getTemplateArgumentList()) {
9695 TemplateArgString = " ";
9696 TemplateArgString += S.getTemplateArgumentBindingsText(
9697 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9698 }
9699
9700 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
9701 << (*DeductionFailure.getCallArgIndex() + 1)
9702 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
9703 << TemplateArgString;
9704 break;
9705 }
9706
Richard Trieue3732352013-04-08 21:11:40 +00009707 case Sema::TDK_NonDeducedMismatch: {
Richard Smith44ecdbd2013-01-31 05:19:49 +00009708 // FIXME: Provide a source location to indicate what we couldn't match.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009709 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
9710 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
Richard Trieue3732352013-04-08 21:11:40 +00009711 if (FirstTA.getKind() == TemplateArgument::Template &&
9712 SecondTA.getKind() == TemplateArgument::Template) {
9713 TemplateName FirstTN = FirstTA.getAsTemplate();
9714 TemplateName SecondTN = SecondTA.getAsTemplate();
9715 if (FirstTN.getKind() == TemplateName::Template &&
9716 SecondTN.getKind() == TemplateName::Template) {
9717 if (FirstTN.getAsTemplateDecl()->getName() ==
9718 SecondTN.getAsTemplateDecl()->getName()) {
9719 // FIXME: This fixes a bad diagnostic where both templates are named
9720 // the same. This particular case is a bit difficult since:
9721 // 1) It is passed as a string to the diagnostic printer.
9722 // 2) The diagnostic printer only attempts to find a better
9723 // name for types, not decls.
9724 // Ideally, this should folded into the diagnostic printer.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009725 S.Diag(Templated->getLocation(),
Richard Trieue3732352013-04-08 21:11:40 +00009726 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
9727 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
9728 return;
9729 }
9730 }
9731 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009732
9733 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
9734 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
9735 return;
9736
Faisal Vali2b391ab2013-09-26 19:54:12 +00009737 // FIXME: For generic lambda parameters, check if the function is a lambda
9738 // call operator, and if so, emit a prettier and more informative
9739 // diagnostic that mentions 'auto' and lambda in addition to
9740 // (or instead of?) the canonical template type parameters.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009741 S.Diag(Templated->getLocation(),
9742 diag::note_ovl_candidate_non_deduced_mismatch)
9743 << FirstTA << SecondTA;
Richard Smith44ecdbd2013-01-31 05:19:49 +00009744 return;
Richard Trieue3732352013-04-08 21:11:40 +00009745 }
John McCall8b9ed552010-02-01 18:53:26 +00009746 // TODO: diagnose these individually, then kill off
9747 // note_ovl_candidate_bad_deduction, which is uselessly vague.
Richard Smith44ecdbd2013-01-31 05:19:49 +00009748 case Sema::TDK_MiscellaneousDeductionFailure:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009749 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
Richard Smith5179eb72016-06-28 19:03:57 +00009750 MaybeEmitInheritedConstructorNote(S, Found);
John McCall8b9ed552010-02-01 18:53:26 +00009751 return;
Artem Belevich13e9b4d2016-12-07 19:27:16 +00009752 case Sema::TDK_CUDATargetMismatch:
9753 S.Diag(Templated->getLocation(),
9754 diag::note_cuda_ovl_candidate_target_mismatch);
9755 return;
John McCall8b9ed552010-02-01 18:53:26 +00009756 }
9757}
9758
Larisse Voufo98b20f12013-07-19 23:00:19 +00009759/// Diagnose a failed template-argument deduction, for function calls.
Richard Smith17c00b42014-11-12 01:24:00 +00009760static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009761 unsigned NumArgs,
9762 bool TakingCandidateAddress) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009763 unsigned TDK = Cand->DeductionFailure.Result;
9764 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
9765 if (CheckArityMismatch(S, Cand, NumArgs))
9766 return;
9767 }
Richard Smithc2bebe92016-05-11 20:37:46 +00009768 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009769 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
Larisse Voufo98b20f12013-07-19 23:00:19 +00009770}
9771
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009772/// CUDA: diagnose an invalid call across targets.
Richard Smith17c00b42014-11-12 01:24:00 +00009773static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009774 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
9775 FunctionDecl *Callee = Cand->Function;
9776
9777 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
9778 CalleeTarget = S.IdentifyCUDATarget(Callee);
9779
9780 std::string FnDesc;
Richard Smithc2bebe92016-05-11 20:37:46 +00009781 OverloadCandidateKind FnKind =
9782 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc);
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009783
9784 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
Eli Bendersky9a220fc2014-09-29 20:38:29 +00009785 << (unsigned)FnKind << CalleeTarget << CallerTarget;
9786
9787 // This could be an implicit constructor for which we could not infer the
9788 // target due to a collsion. Diagnose that case.
9789 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
9790 if (Meth != nullptr && Meth->isImplicit()) {
9791 CXXRecordDecl *ParentClass = Meth->getParent();
9792 Sema::CXXSpecialMember CSM;
9793
9794 switch (FnKind) {
9795 default:
9796 return;
9797 case oc_implicit_default_constructor:
9798 CSM = Sema::CXXDefaultConstructor;
9799 break;
9800 case oc_implicit_copy_constructor:
9801 CSM = Sema::CXXCopyConstructor;
9802 break;
9803 case oc_implicit_move_constructor:
9804 CSM = Sema::CXXMoveConstructor;
9805 break;
9806 case oc_implicit_copy_assignment:
9807 CSM = Sema::CXXCopyAssignment;
9808 break;
9809 case oc_implicit_move_assignment:
9810 CSM = Sema::CXXMoveAssignment;
9811 break;
9812 };
9813
9814 bool ConstRHS = false;
9815 if (Meth->getNumParams()) {
9816 if (const ReferenceType *RT =
9817 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
9818 ConstRHS = RT->getPointeeType().isConstQualified();
9819 }
9820 }
9821
9822 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
9823 /* ConstRHS */ ConstRHS,
9824 /* Diagnose */ true);
9825 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009826}
9827
Richard Smith17c00b42014-11-12 01:24:00 +00009828static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009829 FunctionDecl *Callee = Cand->Function;
9830 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
9831
9832 S.Diag(Callee->getLocation(),
9833 diag::note_ovl_candidate_disabled_by_enable_if_attr)
9834 << Attr->getCond()->getSourceRange() << Attr->getMessage();
9835}
9836
Yaxun Liu5b746652016-12-18 05:18:55 +00009837static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) {
9838 FunctionDecl *Callee = Cand->Function;
9839
9840 S.Diag(Callee->getLocation(),
9841 diag::note_ovl_candidate_disabled_by_extension);
9842}
9843
John McCall8b9ed552010-02-01 18:53:26 +00009844/// Generates a 'note' diagnostic for an overload candidate. We've
9845/// already generated a primary error at the call site.
9846///
9847/// It really does need to be a single diagnostic with its caret
9848/// pointed at the candidate declaration. Yes, this creates some
9849/// major challenges of technical writing. Yes, this makes pointing
9850/// out problems with specific arguments quite awkward. It's still
9851/// better than generating twenty screens of text for every failed
9852/// overload.
9853///
9854/// It would be great to be able to express per-candidate problems
9855/// more richly for those diagnostic clients that cared, but we'd
9856/// still have to be just as careful with the default diagnostics.
Richard Smith17c00b42014-11-12 01:24:00 +00009857static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009858 unsigned NumArgs,
9859 bool TakingCandidateAddress) {
John McCall53262c92010-01-12 02:15:36 +00009860 FunctionDecl *Fn = Cand->Function;
9861
John McCall12f97bc2010-01-08 04:41:39 +00009862 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00009863 if (Cand->Viable && (Fn->isDeleted() ||
9864 S.isFunctionConsideredUnavailable(Fn))) {
John McCalle1ac8d12010-01-13 00:25:19 +00009865 std::string FnDesc;
Richard Smithc2bebe92016-05-11 20:37:46 +00009866 OverloadCandidateKind FnKind =
9867 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00009868
9869 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
Richard Smith6f1e2c62012-04-02 20:59:25 +00009870 << FnKind << FnDesc
9871 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
Richard Smith5179eb72016-06-28 19:03:57 +00009872 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCalld3224162010-01-08 00:58:21 +00009873 return;
John McCall12f97bc2010-01-08 04:41:39 +00009874 }
9875
John McCalle1ac8d12010-01-13 00:25:19 +00009876 // We don't really have anything else to say about viable candidates.
9877 if (Cand->Viable) {
Richard Smithc2bebe92016-05-11 20:37:46 +00009878 S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009879 return;
9880 }
John McCall0d1da222010-01-12 00:44:57 +00009881
John McCall6a61b522010-01-13 09:16:55 +00009882 switch (Cand->FailureKind) {
9883 case ovl_fail_too_many_arguments:
9884 case ovl_fail_too_few_arguments:
9885 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00009886
John McCall6a61b522010-01-13 09:16:55 +00009887 case ovl_fail_bad_deduction:
Richard Smithc2bebe92016-05-11 20:37:46 +00009888 return DiagnoseBadDeduction(S, Cand, NumArgs,
9889 TakingCandidateAddress);
John McCall8b9ed552010-02-01 18:53:26 +00009890
John McCall578a1f82014-12-14 01:46:53 +00009891 case ovl_fail_illegal_constructor: {
9892 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
9893 << (Fn->getPrimaryTemplate() ? 1 : 0);
Richard Smith5179eb72016-06-28 19:03:57 +00009894 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall578a1f82014-12-14 01:46:53 +00009895 return;
9896 }
9897
John McCallfe796dd2010-01-23 05:17:32 +00009898 case ovl_fail_trivial_conversion:
9899 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00009900 case ovl_fail_final_conversion_not_exact:
Richard Smithc2bebe92016-05-11 20:37:46 +00009901 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009902
John McCall65eb8792010-02-25 01:37:24 +00009903 case ovl_fail_bad_conversion: {
9904 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009905 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00009906 if (Cand->Conversions[I].isBad())
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009907 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009908
John McCall6a61b522010-01-13 09:16:55 +00009909 // FIXME: this currently happens when we're called from SemaInit
9910 // when user-conversion overload fails. Figure out how to handle
9911 // those conditions and diagnose them well.
Richard Smithc2bebe92016-05-11 20:37:46 +00009912 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009913 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009914
9915 case ovl_fail_bad_target:
9916 return DiagnoseBadTarget(S, Cand);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009917
9918 case ovl_fail_enable_if:
9919 return DiagnoseFailedEnableIfAttr(S, Cand);
George Burgess IV7204ed92016-01-07 02:26:57 +00009920
Yaxun Liu5b746652016-12-18 05:18:55 +00009921 case ovl_fail_ext_disabled:
9922 return DiagnoseOpenCLExtensionDisabled(S, Cand);
9923
George Burgess IV7204ed92016-01-07 02:26:57 +00009924 case ovl_fail_addr_not_available: {
9925 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
9926 (void)Available;
9927 assert(!Available);
9928 break;
9929 }
John McCall65eb8792010-02-25 01:37:24 +00009930 }
John McCalld3224162010-01-08 00:58:21 +00009931}
9932
Richard Smith17c00b42014-11-12 01:24:00 +00009933static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
John McCalld3224162010-01-08 00:58:21 +00009934 // Desugar the type of the surrogate down to a function type,
9935 // retaining as many typedefs as possible while still showing
9936 // the function type (and, therefore, its parameter types).
9937 QualType FnType = Cand->Surrogate->getConversionType();
9938 bool isLValueReference = false;
9939 bool isRValueReference = false;
9940 bool isPointer = false;
9941 if (const LValueReferenceType *FnTypeRef =
9942 FnType->getAs<LValueReferenceType>()) {
9943 FnType = FnTypeRef->getPointeeType();
9944 isLValueReference = true;
9945 } else if (const RValueReferenceType *FnTypeRef =
9946 FnType->getAs<RValueReferenceType>()) {
9947 FnType = FnTypeRef->getPointeeType();
9948 isRValueReference = true;
9949 }
9950 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
9951 FnType = FnTypePtr->getPointeeType();
9952 isPointer = true;
9953 }
9954 // Desugar down to a function type.
9955 FnType = QualType(FnType->getAs<FunctionType>(), 0);
9956 // Reconstruct the pointer/reference as appropriate.
9957 if (isPointer) FnType = S.Context.getPointerType(FnType);
9958 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
9959 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
9960
9961 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
9962 << FnType;
9963}
9964
Richard Smith17c00b42014-11-12 01:24:00 +00009965static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
9966 SourceLocation OpLoc,
9967 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00009968 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalld3224162010-01-08 00:58:21 +00009969 std::string TypeStr("operator");
9970 TypeStr += Opc;
9971 TypeStr += "(";
9972 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramerb0095172012-01-14 16:32:05 +00009973 if (Cand->NumConversions == 1) {
John McCalld3224162010-01-08 00:58:21 +00009974 TypeStr += ")";
9975 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
9976 } else {
9977 TypeStr += ", ";
9978 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
9979 TypeStr += ")";
9980 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
9981 }
9982}
9983
Richard Smith17c00b42014-11-12 01:24:00 +00009984static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
9985 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00009986 unsigned NoOperands = Cand->NumConversions;
John McCalld3224162010-01-08 00:58:21 +00009987 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
9988 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00009989 if (ICS.isBad()) break; // all meaningless after first invalid
9990 if (!ICS.isAmbiguous()) continue;
9991
Richard Smithc2bebe92016-05-11 20:37:46 +00009992 ICS.DiagnoseAmbiguousConversion(
9993 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00009994 }
9995}
9996
Larisse Voufo98b20f12013-07-19 23:00:19 +00009997static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
John McCall3712d9e2010-01-15 23:32:50 +00009998 if (Cand->Function)
9999 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +000010000 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +000010001 return Cand->Surrogate->getLocation();
10002 return SourceLocation();
10003}
10004
Larisse Voufo98b20f12013-07-19 23:00:19 +000010005static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
Chandler Carruth73fddfe2011-09-10 00:51:24 +000010006 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010007 case Sema::TDK_Success:
David Blaikie83d382b2011-09-23 05:06:16 +000010008 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramer8a8051f2011-09-10 21:52:04 +000010009
Douglas Gregorc5c01a62012-09-13 21:01:57 +000010010 case Sema::TDK_Invalid:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010011 case Sema::TDK_Incomplete:
10012 return 1;
10013
10014 case Sema::TDK_Underqualified:
10015 case Sema::TDK_Inconsistent:
10016 return 2;
10017
10018 case Sema::TDK_SubstitutionFailure:
Richard Smith9b534542015-12-31 02:02:54 +000010019 case Sema::TDK_DeducedMismatch:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010020 case Sema::TDK_NonDeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +000010021 case Sema::TDK_MiscellaneousDeductionFailure:
Artem Belevich13e9b4d2016-12-07 19:27:16 +000010022 case Sema::TDK_CUDATargetMismatch:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010023 return 3;
10024
10025 case Sema::TDK_InstantiationDepth:
10026 case Sema::TDK_FailedOverloadResolution:
10027 return 4;
10028
10029 case Sema::TDK_InvalidExplicitArguments:
10030 return 5;
10031
10032 case Sema::TDK_TooManyArguments:
10033 case Sema::TDK_TooFewArguments:
10034 return 6;
10035 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +000010036 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010037}
10038
Richard Smith17c00b42014-11-12 01:24:00 +000010039namespace {
John McCallad2587a2010-01-12 00:48:53 +000010040struct CompareOverloadCandidatesForDisplay {
10041 Sema &S;
Richard Smith0f59cb32015-12-18 21:45:41 +000010042 SourceLocation Loc;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +000010043 size_t NumArgs;
10044
Richard Smith0f59cb32015-12-18 21:45:41 +000010045 CompareOverloadCandidatesForDisplay(Sema &S, SourceLocation Loc, size_t nArgs)
Kaelyn Takatab96b3be2014-05-01 21:15:24 +000010046 : S(S), NumArgs(nArgs) {}
John McCall12f97bc2010-01-08 04:41:39 +000010047
10048 bool operator()(const OverloadCandidate *L,
10049 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +000010050 // Fast-path this check.
10051 if (L == R) return false;
10052
John McCall12f97bc2010-01-08 04:41:39 +000010053 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +000010054 if (L->Viable) {
10055 if (!R->Viable) return true;
10056
10057 // TODO: introduce a tri-valued comparison for overload
10058 // candidates. Would be more worthwhile if we had a sort
10059 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +000010060 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
10061 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +000010062 } else if (R->Viable)
10063 return false;
John McCall12f97bc2010-01-08 04:41:39 +000010064
John McCall3712d9e2010-01-15 23:32:50 +000010065 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +000010066
John McCall3712d9e2010-01-15 23:32:50 +000010067 // Criteria by which we can sort non-viable candidates:
10068 if (!L->Viable) {
10069 // 1. Arity mismatches come after other candidates.
10070 if (L->FailureKind == ovl_fail_too_many_arguments ||
Kaelyn Takatab96b3be2014-05-01 21:15:24 +000010071 L->FailureKind == ovl_fail_too_few_arguments) {
10072 if (R->FailureKind == ovl_fail_too_many_arguments ||
10073 R->FailureKind == ovl_fail_too_few_arguments) {
Kaelyn Takata50c4ffc2014-05-07 00:43:38 +000010074 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
10075 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
10076 if (LDist == RDist) {
10077 if (L->FailureKind == R->FailureKind)
10078 // Sort non-surrogates before surrogates.
10079 return !L->IsSurrogate && R->IsSurrogate;
10080 // Sort candidates requiring fewer parameters than there were
10081 // arguments given after candidates requiring more parameters
10082 // than there were arguments given.
10083 return L->FailureKind == ovl_fail_too_many_arguments;
10084 }
Kaelyn Takatab96b3be2014-05-01 21:15:24 +000010085 return LDist < RDist;
10086 }
John McCall3712d9e2010-01-15 23:32:50 +000010087 return false;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +000010088 }
John McCall3712d9e2010-01-15 23:32:50 +000010089 if (R->FailureKind == ovl_fail_too_many_arguments ||
10090 R->FailureKind == ovl_fail_too_few_arguments)
10091 return true;
John McCall12f97bc2010-01-08 04:41:39 +000010092
John McCallfe796dd2010-01-23 05:17:32 +000010093 // 2. Bad conversions come first and are ordered by the number
10094 // of bad conversions and quality of good conversions.
10095 if (L->FailureKind == ovl_fail_bad_conversion) {
10096 if (R->FailureKind != ovl_fail_bad_conversion)
10097 return true;
10098
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010099 // The conversion that can be fixed with a smaller number of changes,
10100 // comes first.
10101 unsigned numLFixes = L->Fix.NumConversionsFixed;
10102 unsigned numRFixes = R->Fix.NumConversionsFixed;
10103 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
10104 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +000010105 if (numLFixes != numRFixes) {
David Blaikie7a3cbb22015-03-09 02:02:07 +000010106 return numLFixes < numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +000010107 }
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010108
John McCallfe796dd2010-01-23 05:17:32 +000010109 // If there's any ordering between the defined conversions...
10110 // FIXME: this might not be transitive.
Benjamin Kramerb0095172012-01-14 16:32:05 +000010111 assert(L->NumConversions == R->NumConversions);
John McCallfe796dd2010-01-23 05:17:32 +000010112
10113 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +000010114 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramerb0095172012-01-14 16:32:05 +000010115 for (unsigned E = L->NumConversions; I != E; ++I) {
Richard Smith0f59cb32015-12-18 21:45:41 +000010116 switch (CompareImplicitConversionSequences(S, Loc,
John McCall5c32be02010-08-24 20:38:10 +000010117 L->Conversions[I],
10118 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +000010119 case ImplicitConversionSequence::Better:
10120 leftBetter++;
10121 break;
10122
10123 case ImplicitConversionSequence::Worse:
10124 leftBetter--;
10125 break;
10126
10127 case ImplicitConversionSequence::Indistinguishable:
10128 break;
10129 }
10130 }
10131 if (leftBetter > 0) return true;
10132 if (leftBetter < 0) return false;
10133
10134 } else if (R->FailureKind == ovl_fail_bad_conversion)
10135 return false;
10136
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010137 if (L->FailureKind == ovl_fail_bad_deduction) {
10138 if (R->FailureKind != ovl_fail_bad_deduction)
10139 return true;
10140
10141 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10142 return RankDeductionFailure(L->DeductionFailure)
Eli Friedman1e7a0c62011-10-14 23:10:30 +000010143 < RankDeductionFailure(R->DeductionFailure);
Eli Friedmane2c600c2011-10-14 21:52:24 +000010144 } else if (R->FailureKind == ovl_fail_bad_deduction)
10145 return false;
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010146
John McCall3712d9e2010-01-15 23:32:50 +000010147 // TODO: others?
10148 }
10149
10150 // Sort everything else by location.
10151 SourceLocation LLoc = GetLocationForCandidate(L);
10152 SourceLocation RLoc = GetLocationForCandidate(R);
10153
10154 // Put candidates without locations (e.g. builtins) at the end.
10155 if (LLoc.isInvalid()) return false;
10156 if (RLoc.isInvalid()) return true;
10157
10158 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +000010159 }
10160};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010161}
John McCall12f97bc2010-01-08 04:41:39 +000010162
John McCallfe796dd2010-01-23 05:17:32 +000010163/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010164/// computes up to the first. Produces the FixIt set if possible.
Richard Smith17c00b42014-11-12 01:24:00 +000010165static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
10166 ArrayRef<Expr *> Args) {
John McCallfe796dd2010-01-23 05:17:32 +000010167 assert(!Cand->Viable);
10168
10169 // Don't do anything on failures other than bad conversion.
10170 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
10171
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010172 // We only want the FixIts if all the arguments can be corrected.
10173 bool Unfixable = false;
Anna Zaks1b068122011-07-28 19:46:48 +000010174 // Use a implicit copy initialization to check conversion fixes.
10175 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010176
John McCallfe796dd2010-01-23 05:17:32 +000010177 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +000010178 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +000010179 unsigned ConvCount = Cand->NumConversions;
John McCallfe796dd2010-01-23 05:17:32 +000010180 while (true) {
10181 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
10182 ConvIdx++;
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010183 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaks1b068122011-07-28 19:46:48 +000010184 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCallfe796dd2010-01-23 05:17:32 +000010185 break;
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010186 }
John McCallfe796dd2010-01-23 05:17:32 +000010187 }
10188
10189 if (ConvIdx == ConvCount)
10190 return;
10191
John McCall65eb8792010-02-25 01:37:24 +000010192 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
10193 "remaining conversion is initialized?");
10194
Douglas Gregoradc7a702010-04-16 17:45:54 +000010195 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +000010196 // operation somehow.
10197 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +000010198
10199 const FunctionProtoType* Proto;
10200 unsigned ArgIdx = ConvIdx;
10201
10202 if (Cand->IsSurrogate) {
10203 QualType ConvType
10204 = Cand->Surrogate->getConversionType().getNonReferenceType();
10205 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10206 ConvType = ConvPtrType->getPointeeType();
10207 Proto = ConvType->getAs<FunctionProtoType>();
10208 ArgIdx--;
10209 } else if (Cand->Function) {
10210 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
10211 if (isa<CXXMethodDecl>(Cand->Function) &&
10212 !isa<CXXConstructorDecl>(Cand->Function))
10213 ArgIdx--;
10214 } else {
10215 // Builtin binary operator with a bad first conversion.
10216 assert(ConvCount <= 3);
10217 for (; ConvIdx != ConvCount; ++ConvIdx)
10218 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +000010219 = TryCopyInitialization(S, Args[ConvIdx],
10220 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010221 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +000010222 /*InOverloadResolution*/ true,
10223 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +000010224 S.getLangOpts().ObjCAutoRefCount);
John McCallfe796dd2010-01-23 05:17:32 +000010225 return;
10226 }
10227
10228 // Fill in the rest of the conversions.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000010229 unsigned NumParams = Proto->getNumParams();
John McCallfe796dd2010-01-23 05:17:32 +000010230 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000010231 if (ArgIdx < NumParams) {
Alp Toker9cacbab2014-01-20 20:26:09 +000010232 Cand->Conversions[ConvIdx] = TryCopyInitialization(
10233 S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions,
10234 /*InOverloadResolution=*/true,
10235 /*AllowObjCWritebackConversion=*/
10236 S.getLangOpts().ObjCAutoRefCount);
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010237 // Store the FixIt in the candidate if it exists.
10238 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaks1b068122011-07-28 19:46:48 +000010239 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010240 }
John McCallfe796dd2010-01-23 05:17:32 +000010241 else
10242 Cand->Conversions[ConvIdx].setEllipsis();
10243 }
10244}
10245
Douglas Gregor5251f1b2008-10-21 16:13:35 +000010246/// PrintOverloadCandidates - When overload resolution fails, prints
10247/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +000010248/// set.
Richard Smithb2f0f052016-10-10 18:54:32 +000010249void OverloadCandidateSet::NoteCandidates(
10250 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
10251 StringRef Opc, SourceLocation OpLoc,
10252 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
John McCall12f97bc2010-01-08 04:41:39 +000010253 // Sort the candidates by viability and position. Sorting directly would
10254 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010255 SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +000010256 if (OCD == OCD_AllCandidates) Cands.reserve(size());
10257 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
Richard Smithb2f0f052016-10-10 18:54:32 +000010258 if (!Filter(*Cand))
10259 continue;
John McCallfe796dd2010-01-23 05:17:32 +000010260 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +000010261 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +000010262 else if (OCD == OCD_AllCandidates) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010263 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010264 if (Cand->Function || Cand->IsSurrogate)
10265 Cands.push_back(Cand);
10266 // Otherwise, this a non-viable builtin candidate. We do not, in general,
10267 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +000010268 }
10269 }
10270
John McCallad2587a2010-01-12 00:48:53 +000010271 std::sort(Cands.begin(), Cands.end(),
Richard Smith0f59cb32015-12-18 21:45:41 +000010272 CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size()));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010273
John McCall0d1da222010-01-12 00:44:57 +000010274 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +000010275
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010276 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Douglas Gregor79591782012-10-23 23:11:23 +000010277 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010278 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +000010279 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10280 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +000010281
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010282 // Set an arbitrary limit on the number of candidate functions we'll spam
10283 // the user with. FIXME: This limit should depend on details of the
10284 // candidate list.
Douglas Gregor79591782012-10-23 23:11:23 +000010285 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010286 break;
10287 }
10288 ++CandsShown;
10289
John McCalld3224162010-01-08 00:58:21 +000010290 if (Cand->Function)
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010291 NoteFunctionCandidate(S, Cand, Args.size(),
10292 /*TakingCandidateAddress=*/false);
John McCalld3224162010-01-08 00:58:21 +000010293 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +000010294 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010295 else {
10296 assert(Cand->Viable &&
10297 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +000010298 // Generally we only see ambiguities including viable builtin
10299 // operators if overload resolution got screwed up by an
10300 // ambiguous user-defined conversion.
10301 //
10302 // FIXME: It's quite possible for different conversions to see
10303 // different ambiguities, though.
10304 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +000010305 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +000010306 ReportedAmbiguousConversions = true;
10307 }
John McCalld3224162010-01-08 00:58:21 +000010308
John McCall0d1da222010-01-12 00:44:57 +000010309 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +000010310 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +000010311 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +000010312 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010313
10314 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +000010315 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +000010316}
10317
Larisse Voufo98b20f12013-07-19 23:00:19 +000010318static SourceLocation
10319GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
10320 return Cand->Specialization ? Cand->Specialization->getLocation()
10321 : SourceLocation();
10322}
10323
Richard Smith17c00b42014-11-12 01:24:00 +000010324namespace {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010325struct CompareTemplateSpecCandidatesForDisplay {
10326 Sema &S;
10327 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
10328
10329 bool operator()(const TemplateSpecCandidate *L,
10330 const TemplateSpecCandidate *R) {
10331 // Fast-path this check.
10332 if (L == R)
10333 return false;
10334
10335 // Assuming that both candidates are not matches...
10336
10337 // Sort by the ranking of deduction failures.
10338 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10339 return RankDeductionFailure(L->DeductionFailure) <
10340 RankDeductionFailure(R->DeductionFailure);
10341
10342 // Sort everything else by location.
10343 SourceLocation LLoc = GetLocationForCandidate(L);
10344 SourceLocation RLoc = GetLocationForCandidate(R);
10345
10346 // Put candidates without locations (e.g. builtins) at the end.
10347 if (LLoc.isInvalid())
10348 return false;
10349 if (RLoc.isInvalid())
10350 return true;
10351
10352 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10353 }
10354};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010355}
Larisse Voufo98b20f12013-07-19 23:00:19 +000010356
10357/// Diagnose a template argument deduction failure.
10358/// We are treating these failures as overload failures due to bad
10359/// deductions.
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010360void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
10361 bool ForTakingAddress) {
Richard Smithc2bebe92016-05-11 20:37:46 +000010362 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010363 DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010364}
10365
10366void TemplateSpecCandidateSet::destroyCandidates() {
10367 for (iterator i = begin(), e = end(); i != e; ++i) {
10368 i->DeductionFailure.Destroy();
10369 }
10370}
10371
10372void TemplateSpecCandidateSet::clear() {
10373 destroyCandidates();
10374 Candidates.clear();
10375}
10376
10377/// NoteCandidates - When no template specialization match is found, prints
10378/// diagnostic messages containing the non-matching specializations that form
10379/// the candidate set.
10380/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
10381/// OCD == OCD_AllCandidates and Cand->Viable == false.
10382void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
10383 // Sort the candidates by position (assuming no candidate is a match).
10384 // Sorting directly would be prohibitive, so we make a set of pointers
10385 // and sort those.
10386 SmallVector<TemplateSpecCandidate *, 32> Cands;
10387 Cands.reserve(size());
10388 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10389 if (Cand->Specialization)
10390 Cands.push_back(Cand);
Alp Tokerd4733632013-12-05 04:47:09 +000010391 // Otherwise, this is a non-matching builtin candidate. We do not,
Larisse Voufo98b20f12013-07-19 23:00:19 +000010392 // in general, want to list every possible builtin candidate.
10393 }
10394
10395 std::sort(Cands.begin(), Cands.end(),
10396 CompareTemplateSpecCandidatesForDisplay(S));
10397
10398 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
10399 // for generalization purposes (?).
10400 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10401
10402 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
10403 unsigned CandsShown = 0;
10404 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10405 TemplateSpecCandidate *Cand = *I;
10406
10407 // Set an arbitrary limit on the number of candidates we'll spam
10408 // the user with. FIXME: This limit should depend on details of the
10409 // candidate list.
10410 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10411 break;
10412 ++CandsShown;
10413
10414 assert(Cand->Specialization &&
10415 "Non-matching built-in candidates are not added to Cands.");
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010416 Cand->NoteDeductionFailure(S, ForTakingAddress);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010417 }
10418
10419 if (I != E)
10420 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
10421}
10422
Douglas Gregorb491ed32011-02-19 21:32:49 +000010423// [PossiblyAFunctionType] --> [Return]
10424// NonFunctionType --> NonFunctionType
10425// R (A) --> R(A)
10426// R (*)(A) --> R (A)
10427// R (&)(A) --> R (A)
10428// R (S::*)(A) --> R (A)
10429QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
10430 QualType Ret = PossiblyAFunctionType;
10431 if (const PointerType *ToTypePtr =
10432 PossiblyAFunctionType->getAs<PointerType>())
10433 Ret = ToTypePtr->getPointeeType();
10434 else if (const ReferenceType *ToTypeRef =
10435 PossiblyAFunctionType->getAs<ReferenceType>())
10436 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +000010437 else if (const MemberPointerType *MemTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +000010438 PossiblyAFunctionType->getAs<MemberPointerType>())
10439 Ret = MemTypePtr->getPointeeType();
10440 Ret =
10441 Context.getCanonicalType(Ret).getUnqualifiedType();
10442 return Ret;
10443}
Douglas Gregorcd695e52008-11-10 20:40:00 +000010444
Richard Smith9095e5b2016-11-01 01:31:23 +000010445static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
10446 bool Complain = true) {
10447 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
10448 S.DeduceReturnType(FD, Loc, Complain))
10449 return true;
10450
10451 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
10452 if (S.getLangOpts().CPlusPlus1z &&
10453 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
10454 !S.ResolveExceptionSpec(Loc, FPT))
10455 return true;
10456
10457 return false;
10458}
10459
Richard Smith17c00b42014-11-12 01:24:00 +000010460namespace {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010461// A helper class to help with address of function resolution
10462// - allows us to avoid passing around all those ugly parameters
Richard Smith17c00b42014-11-12 01:24:00 +000010463class AddressOfFunctionResolver {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010464 Sema& S;
10465 Expr* SourceExpr;
10466 const QualType& TargetType;
10467 QualType TargetFunctionType; // Extracted function type from target type
10468
10469 bool Complain;
10470 //DeclAccessPair& ResultFunctionAccessPair;
10471 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010472
Douglas Gregorb491ed32011-02-19 21:32:49 +000010473 bool TargetTypeIsNonStaticMemberFunction;
10474 bool FoundNonTemplateFunction;
David Majnemera4f7c7a2013-08-01 06:13:59 +000010475 bool StaticMemberFunctionFromBoundPointer;
George Burgess IV5f2ef452015-10-12 18:40:58 +000010476 bool HasComplained;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010477
Douglas Gregorb491ed32011-02-19 21:32:49 +000010478 OverloadExpr::FindResult OvlExprInfo;
10479 OverloadExpr *OvlExpr;
10480 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010481 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Larisse Voufo98b20f12013-07-19 23:00:19 +000010482 TemplateSpecCandidateSet FailedCandidates;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010483
Douglas Gregorb491ed32011-02-19 21:32:49 +000010484public:
Larisse Voufo98b20f12013-07-19 23:00:19 +000010485 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
10486 const QualType &TargetType, bool Complain)
10487 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
10488 Complain(Complain), Context(S.getASTContext()),
10489 TargetTypeIsNonStaticMemberFunction(
10490 !!TargetType->getAs<MemberPointerType>()),
10491 FoundNonTemplateFunction(false),
David Majnemera4f7c7a2013-08-01 06:13:59 +000010492 StaticMemberFunctionFromBoundPointer(false),
George Burgess IV5f2ef452015-10-12 18:40:58 +000010493 HasComplained(false),
Larisse Voufo98b20f12013-07-19 23:00:19 +000010494 OvlExprInfo(OverloadExpr::find(SourceExpr)),
10495 OvlExpr(OvlExprInfo.Expression),
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010496 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010497 ExtractUnqualifiedFunctionTypeFromTargetType();
Chandler Carruthffce2452011-03-29 08:08:18 +000010498
David Majnemera4f7c7a2013-08-01 06:13:59 +000010499 if (TargetFunctionType->isFunctionType()) {
10500 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
10501 if (!UME->isImplicitAccess() &&
10502 !S.ResolveSingleFunctionTemplateSpecialization(UME))
10503 StaticMemberFunctionFromBoundPointer = true;
10504 } else if (OvlExpr->hasExplicitTemplateArgs()) {
10505 DeclAccessPair dap;
10506 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
10507 OvlExpr, false, &dap)) {
10508 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
10509 if (!Method->isStatic()) {
10510 // If the target type is a non-function type and the function found
10511 // is a non-static member function, pretend as if that was the
10512 // target, it's the only possible type to end up with.
10513 TargetTypeIsNonStaticMemberFunction = true;
Chandler Carruthffce2452011-03-29 08:08:18 +000010514
David Majnemera4f7c7a2013-08-01 06:13:59 +000010515 // And skip adding the function if its not in the proper form.
10516 // We'll diagnose this due to an empty set of functions.
10517 if (!OvlExprInfo.HasFormOfMemberPointer)
10518 return;
Chandler Carruthffce2452011-03-29 08:08:18 +000010519 }
10520
David Majnemera4f7c7a2013-08-01 06:13:59 +000010521 Matches.push_back(std::make_pair(dap, Fn));
Douglas Gregor9b146582009-07-08 20:55:45 +000010522 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010523 return;
Douglas Gregor9b146582009-07-08 20:55:45 +000010524 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010525
10526 if (OvlExpr->hasExplicitTemplateArgs())
James Y Knight04ec5bf2015-12-24 02:59:37 +000010527 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +000010528
Douglas Gregorb491ed32011-02-19 21:32:49 +000010529 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
10530 // C++ [over.over]p4:
10531 // If more than one function is selected, [...]
George Burgess IV2a6150d2015-10-16 01:17:38 +000010532 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010533 if (FoundNonTemplateFunction)
10534 EliminateAllTemplateMatches();
10535 else
10536 EliminateAllExceptMostSpecializedTemplate();
10537 }
10538 }
Artem Belevich94a55e82015-09-22 17:22:59 +000010539
Justin Lebar25c4a812016-03-29 16:24:16 +000010540 if (S.getLangOpts().CUDA && Matches.size() > 1)
Artem Belevich94a55e82015-09-22 17:22:59 +000010541 EliminateSuboptimalCudaMatches();
Douglas Gregorb491ed32011-02-19 21:32:49 +000010542 }
George Burgess IV5f2ef452015-10-12 18:40:58 +000010543
10544 bool hasComplained() const { return HasComplained; }
10545
Douglas Gregorb491ed32011-02-19 21:32:49 +000010546private:
George Burgess IV6da4c202016-03-23 02:33:58 +000010547 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
10548 QualType Discard;
10549 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
Richard Smith3c4f8d22016-10-16 17:54:23 +000010550 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
George Burgess IV2a6150d2015-10-16 01:17:38 +000010551 }
10552
George Burgess IV6da4c202016-03-23 02:33:58 +000010553 /// \return true if A is considered a better overload candidate for the
10554 /// desired type than B.
10555 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
10556 // If A doesn't have exactly the correct type, we don't want to classify it
10557 // as "better" than anything else. This way, the user is required to
10558 // disambiguate for us if there are multiple candidates and no exact match.
10559 return candidateHasExactlyCorrectType(A) &&
10560 (!candidateHasExactlyCorrectType(B) ||
George Burgess IV3dc166912016-05-10 01:59:34 +000010561 compareEnableIfAttrs(S, A, B) == Comparison::Better);
George Burgess IV6da4c202016-03-23 02:33:58 +000010562 }
10563
10564 /// \return true if we were able to eliminate all but one overload candidate,
10565 /// false otherwise.
George Burgess IV2a6150d2015-10-16 01:17:38 +000010566 bool eliminiateSuboptimalOverloadCandidates() {
10567 // Same algorithm as overload resolution -- one pass to pick the "best",
10568 // another pass to be sure that nothing is better than the best.
10569 auto Best = Matches.begin();
10570 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
10571 if (isBetterCandidate(I->second, Best->second))
10572 Best = I;
10573
10574 const FunctionDecl *BestFn = Best->second;
10575 auto IsBestOrInferiorToBest = [this, BestFn](
10576 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
10577 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
10578 };
10579
10580 // Note: We explicitly leave Matches unmodified if there isn't a clear best
10581 // option, so we can potentially give the user a better error
10582 if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest))
10583 return false;
10584 Matches[0] = *Best;
10585 Matches.resize(1);
10586 return true;
10587 }
10588
Douglas Gregorb491ed32011-02-19 21:32:49 +000010589 bool isTargetTypeAFunction() const {
10590 return TargetFunctionType->isFunctionType();
10591 }
10592
10593 // [ToType] [Return]
10594
10595 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
10596 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
10597 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
10598 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
10599 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
10600 }
10601
10602 // return true if any matching specializations were found
10603 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
10604 const DeclAccessPair& CurAccessFunPair) {
10605 if (CXXMethodDecl *Method
10606 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
10607 // Skip non-static function templates when converting to pointer, and
10608 // static when converting to member pointer.
10609 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10610 return false;
10611 }
10612 else if (TargetTypeIsNonStaticMemberFunction)
10613 return false;
10614
10615 // C++ [over.over]p2:
10616 // If the name is a function template, template argument deduction is
10617 // done (14.8.2.2), and if the argument deduction succeeds, the
10618 // resulting template argument list is used to generate a single
10619 // function template specialization, which is added to the set of
10620 // overloaded functions considered.
Craig Topperc3ec1492014-05-26 06:22:03 +000010621 FunctionDecl *Specialization = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +000010622 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregorb491ed32011-02-19 21:32:49 +000010623 if (Sema::TemplateDeductionResult Result
10624 = S.DeduceTemplateArguments(FunctionTemplate,
10625 &OvlExplicitTemplateArgs,
10626 TargetFunctionType, Specialization,
Richard Smithbaa47832016-12-01 02:11:49 +000010627 Info, /*IsAddressOfFunction*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010628 // Make a note of the failed deduction for diagnostics.
10629 FailedCandidates.addCandidate()
Richard Smithc2bebe92016-05-11 20:37:46 +000010630 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
Larisse Voufo98b20f12013-07-19 23:00:19 +000010631 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregorb491ed32011-02-19 21:32:49 +000010632 return false;
10633 }
10634
Douglas Gregor19a41f12013-04-17 08:45:07 +000010635 // Template argument deduction ensures that we have an exact match or
10636 // compatible pointer-to-function arguments that would be adjusted by ICS.
Douglas Gregorb491ed32011-02-19 21:32:49 +000010637 // This function template specicalization works.
Douglas Gregor19a41f12013-04-17 08:45:07 +000010638 assert(S.isSameOrCompatibleFunctionType(
10639 Context.getCanonicalType(Specialization->getType()),
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010640 Context.getCanonicalType(TargetFunctionType)));
George Burgess IV5f21c712015-10-12 19:57:04 +000010641
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010642 if (!S.checkAddressOfFunctionIsAvailable(Specialization))
George Burgess IV5f21c712015-10-12 19:57:04 +000010643 return false;
10644
Douglas Gregorb491ed32011-02-19 21:32:49 +000010645 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
10646 return true;
10647 }
10648
10649 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
10650 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +000010651 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +000010652 // Skip non-static functions when converting to pointer, and static
10653 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +000010654 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10655 return false;
10656 }
10657 else if (TargetTypeIsNonStaticMemberFunction)
10658 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010659
Chandler Carruthc25c6ee2009-12-29 06:17:27 +000010660 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000010661 if (S.getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010662 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
Justin Lebarb0080032016-08-10 01:09:11 +000010663 if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010664 return false;
10665
Richard Smith2a7d4812013-05-04 07:00:32 +000010666 // If any candidate has a placeholder return type, trigger its deduction
10667 // now.
Richard Smith9095e5b2016-11-01 01:31:23 +000010668 if (completeFunctionType(S, FunDecl, SourceExpr->getLocStart(),
10669 Complain)) {
George Burgess IV5f2ef452015-10-12 18:40:58 +000010670 HasComplained |= Complain;
Richard Smith2a7d4812013-05-04 07:00:32 +000010671 return false;
George Burgess IV5f2ef452015-10-12 18:40:58 +000010672 }
Richard Smith2a7d4812013-05-04 07:00:32 +000010673
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010674 if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
George Burgess IV5f21c712015-10-12 19:57:04 +000010675 return false;
10676
George Burgess IV6da4c202016-03-23 02:33:58 +000010677 // If we're in C, we need to support types that aren't exactly identical.
10678 if (!S.getLangOpts().CPlusPlus ||
10679 candidateHasExactlyCorrectType(FunDecl)) {
George Burgess IV5f21c712015-10-12 19:57:04 +000010680 Matches.push_back(std::make_pair(
10681 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +000010682 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010683 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +000010684 }
Mike Stump11289f42009-09-09 15:08:12 +000010685 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010686
10687 return false;
10688 }
10689
10690 bool FindAllFunctionsThatMatchTargetTypeExactly() {
10691 bool Ret = false;
10692
10693 // If the overload expression doesn't have the form of a pointer to
10694 // member, don't try to convert it to a pointer-to-member type.
10695 if (IsInvalidFormOfPointerToMemberFunction())
10696 return false;
10697
10698 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10699 E = OvlExpr->decls_end();
10700 I != E; ++I) {
10701 // Look through any using declarations to find the underlying function.
10702 NamedDecl *Fn = (*I)->getUnderlyingDecl();
10703
10704 // C++ [over.over]p3:
10705 // Non-member functions and static member functions match
10706 // targets of type "pointer-to-function" or "reference-to-function."
10707 // Nonstatic member functions match targets of
10708 // type "pointer-to-member-function."
10709 // Note that according to DR 247, the containing class does not matter.
10710 if (FunctionTemplateDecl *FunctionTemplate
10711 = dyn_cast<FunctionTemplateDecl>(Fn)) {
10712 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
10713 Ret = true;
10714 }
10715 // If we have explicit template arguments supplied, skip non-templates.
10716 else if (!OvlExpr->hasExplicitTemplateArgs() &&
10717 AddMatchingNonTemplateFunction(Fn, I.getPair()))
10718 Ret = true;
10719 }
10720 assert(Ret || Matches.empty());
10721 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010722 }
10723
Douglas Gregorb491ed32011-02-19 21:32:49 +000010724 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +000010725 // [...] and any given function template specialization F1 is
10726 // eliminated if the set contains a second function template
10727 // specialization whose function template is more specialized
10728 // than the function template of F1 according to the partial
10729 // ordering rules of 14.5.5.2.
10730
10731 // The algorithm specified above is quadratic. We instead use a
10732 // two-pass algorithm (similar to the one used to identify the
10733 // best viable function in an overload set) that identifies the
10734 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +000010735
10736 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
10737 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
10738 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010739
Larisse Voufo98b20f12013-07-19 23:00:19 +000010740 // TODO: It looks like FailedCandidates does not serve much purpose
10741 // here, since the no_viable diagnostic has index 0.
10742 UnresolvedSetIterator Result = S.getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +000010743 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +000010744 SourceExpr->getLocStart(), S.PDiag(),
Richard Smith5179eb72016-06-28 19:03:57 +000010745 S.PDiag(diag::err_addr_ovl_ambiguous)
10746 << Matches[0].second->getDeclName(),
10747 S.PDiag(diag::note_ovl_candidate)
10748 << (unsigned)oc_function_template,
Larisse Voufo98b20f12013-07-19 23:00:19 +000010749 Complain, TargetFunctionType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010750
Douglas Gregorb491ed32011-02-19 21:32:49 +000010751 if (Result != MatchesCopy.end()) {
10752 // Make it the first and only element
10753 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
10754 Matches[0].second = cast<FunctionDecl>(*Result);
10755 Matches.resize(1);
George Burgess IV5f2ef452015-10-12 18:40:58 +000010756 } else
10757 HasComplained |= Complain;
John McCall58cc69d2010-01-27 01:50:18 +000010758 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010759
Douglas Gregorb491ed32011-02-19 21:32:49 +000010760 void EliminateAllTemplateMatches() {
10761 // [...] any function template specializations in the set are
10762 // eliminated if the set also contains a non-template function, [...]
10763 for (unsigned I = 0, N = Matches.size(); I != N; ) {
Craig Topperc3ec1492014-05-26 06:22:03 +000010764 if (Matches[I].second->getPrimaryTemplate() == nullptr)
Douglas Gregorb491ed32011-02-19 21:32:49 +000010765 ++I;
10766 else {
10767 Matches[I] = Matches[--N];
Artem Belevich94a55e82015-09-22 17:22:59 +000010768 Matches.resize(N);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010769 }
10770 }
10771 }
10772
Artem Belevich94a55e82015-09-22 17:22:59 +000010773 void EliminateSuboptimalCudaMatches() {
10774 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
10775 }
10776
Douglas Gregorb491ed32011-02-19 21:32:49 +000010777public:
10778 void ComplainNoMatchesFound() const {
10779 assert(Matches.empty());
10780 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
10781 << OvlExpr->getName() << TargetFunctionType
10782 << OvlExpr->getSourceRange();
Richard Smith0d905472013-08-14 00:00:44 +000010783 if (FailedCandidates.empty())
George Burgess IV5f21c712015-10-12 19:57:04 +000010784 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
10785 /*TakingAddress=*/true);
Richard Smith0d905472013-08-14 00:00:44 +000010786 else {
10787 // We have some deduction failure messages. Use them to diagnose
10788 // the function templates, and diagnose the non-template candidates
10789 // normally.
10790 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10791 IEnd = OvlExpr->decls_end();
10792 I != IEnd; ++I)
10793 if (FunctionDecl *Fun =
10794 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010795 if (!functionHasPassObjectSizeParams(Fun))
Richard Smithc2bebe92016-05-11 20:37:46 +000010796 S.NoteOverloadCandidate(*I, Fun, TargetFunctionType,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010797 /*TakingAddress=*/true);
Richard Smith0d905472013-08-14 00:00:44 +000010798 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
10799 }
10800 }
10801
Douglas Gregorb491ed32011-02-19 21:32:49 +000010802 bool IsInvalidFormOfPointerToMemberFunction() const {
10803 return TargetTypeIsNonStaticMemberFunction &&
10804 !OvlExprInfo.HasFormOfMemberPointer;
10805 }
David Majnemera4f7c7a2013-08-01 06:13:59 +000010806
Douglas Gregorb491ed32011-02-19 21:32:49 +000010807 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
10808 // TODO: Should we condition this on whether any functions might
10809 // have matched, or is it more appropriate to do that in callers?
10810 // TODO: a fixit wouldn't hurt.
10811 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
10812 << TargetType << OvlExpr->getSourceRange();
10813 }
David Majnemera4f7c7a2013-08-01 06:13:59 +000010814
10815 bool IsStaticMemberFunctionFromBoundPointer() const {
10816 return StaticMemberFunctionFromBoundPointer;
10817 }
10818
10819 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
10820 S.Diag(OvlExpr->getLocStart(),
10821 diag::err_invalid_form_pointer_member_function)
10822 << OvlExpr->getSourceRange();
10823 }
10824
Douglas Gregorb491ed32011-02-19 21:32:49 +000010825 void ComplainOfInvalidConversion() const {
10826 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
10827 << OvlExpr->getName() << TargetType;
10828 }
10829
10830 void ComplainMultipleMatchesFound() const {
10831 assert(Matches.size() > 1);
10832 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
10833 << OvlExpr->getName()
10834 << OvlExpr->getSourceRange();
George Burgess IV5f21c712015-10-12 19:57:04 +000010835 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
10836 /*TakingAddress=*/true);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010837 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010838
10839 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
10840
Douglas Gregorb491ed32011-02-19 21:32:49 +000010841 int getNumMatches() const { return Matches.size(); }
10842
10843 FunctionDecl* getMatchingFunctionDecl() const {
Craig Topperc3ec1492014-05-26 06:22:03 +000010844 if (Matches.size() != 1) return nullptr;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010845 return Matches[0].second;
10846 }
10847
10848 const DeclAccessPair* getMatchingFunctionAccessPair() const {
Craig Topperc3ec1492014-05-26 06:22:03 +000010849 if (Matches.size() != 1) return nullptr;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010850 return &Matches[0].first;
10851 }
10852};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010853}
Richard Smith17c00b42014-11-12 01:24:00 +000010854
Douglas Gregorb491ed32011-02-19 21:32:49 +000010855/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
10856/// an overloaded function (C++ [over.over]), where @p From is an
10857/// expression with overloaded function type and @p ToType is the type
10858/// we're trying to resolve to. For example:
10859///
10860/// @code
10861/// int f(double);
10862/// int f(int);
10863///
10864/// int (*pfd)(double) = f; // selects f(double)
10865/// @endcode
10866///
10867/// This routine returns the resulting FunctionDecl if it could be
10868/// resolved, and NULL otherwise. When @p Complain is true, this
10869/// routine will emit diagnostics if there is an error.
10870FunctionDecl *
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010871Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
10872 QualType TargetType,
10873 bool Complain,
10874 DeclAccessPair &FoundResult,
10875 bool *pHadMultipleCandidates) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010876 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010877
10878 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
10879 Complain);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010880 int NumMatches = Resolver.getNumMatches();
Craig Topperc3ec1492014-05-26 06:22:03 +000010881 FunctionDecl *Fn = nullptr;
George Burgess IV5f2ef452015-10-12 18:40:58 +000010882 bool ShouldComplain = Complain && !Resolver.hasComplained();
10883 if (NumMatches == 0 && ShouldComplain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010884 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
10885 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
10886 else
10887 Resolver.ComplainNoMatchesFound();
10888 }
George Burgess IV5f2ef452015-10-12 18:40:58 +000010889 else if (NumMatches > 1 && ShouldComplain)
Douglas Gregorb491ed32011-02-19 21:32:49 +000010890 Resolver.ComplainMultipleMatchesFound();
10891 else if (NumMatches == 1) {
10892 Fn = Resolver.getMatchingFunctionDecl();
10893 assert(Fn);
Richard Smith9095e5b2016-11-01 01:31:23 +000010894 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
10895 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010896 FoundResult = *Resolver.getMatchingFunctionAccessPair();
David Majnemera4f7c7a2013-08-01 06:13:59 +000010897 if (Complain) {
10898 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
10899 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
10900 else
10901 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
10902 }
Sebastian Redldf4b80e2009-10-17 21:12:09 +000010903 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010904
10905 if (pHadMultipleCandidates)
10906 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregorb491ed32011-02-19 21:32:49 +000010907 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010908}
10909
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010910/// \brief Given an expression that refers to an overloaded function, try to
George Burgess IV3cde9bf2016-03-19 21:36:10 +000010911/// resolve that function to a single function that can have its address taken.
10912/// This will modify `Pair` iff it returns non-null.
10913///
10914/// This routine can only realistically succeed if all but one candidates in the
10915/// overload set for SrcExpr cannot have their addresses taken.
10916FunctionDecl *
10917Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
10918 DeclAccessPair &Pair) {
10919 OverloadExpr::FindResult R = OverloadExpr::find(E);
10920 OverloadExpr *Ovl = R.Expression;
10921 FunctionDecl *Result = nullptr;
10922 DeclAccessPair DAP;
10923 // Don't use the AddressOfResolver because we're specifically looking for
10924 // cases where we have one overload candidate that lacks
10925 // enable_if/pass_object_size/...
10926 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
10927 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
10928 if (!FD)
10929 return nullptr;
10930
10931 if (!checkAddressOfFunctionIsAvailable(FD))
10932 continue;
10933
10934 // We have more than one result; quit.
10935 if (Result)
10936 return nullptr;
10937 DAP = I.getPair();
10938 Result = FD;
10939 }
10940
10941 if (Result)
10942 Pair = DAP;
10943 return Result;
10944}
10945
George Burgess IVbeca4a32016-06-08 00:34:22 +000010946/// \brief Given an overloaded function, tries to turn it into a non-overloaded
10947/// function reference using resolveAddressOfOnlyViableOverloadCandidate. This
10948/// will perform access checks, diagnose the use of the resultant decl, and, if
10949/// necessary, perform a function-to-pointer decay.
10950///
10951/// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails.
10952/// Otherwise, returns true. This may emit diagnostics and return true.
10953bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate(
10954 ExprResult &SrcExpr) {
10955 Expr *E = SrcExpr.get();
10956 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
10957
10958 DeclAccessPair DAP;
10959 FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP);
10960 if (!Found)
10961 return false;
10962
10963 // Emitting multiple diagnostics for a function that is both inaccessible and
10964 // unavailable is consistent with our behavior elsewhere. So, always check
10965 // for both.
10966 DiagnoseUseOfDecl(Found, E->getExprLoc());
10967 CheckAddressOfMemberAccess(E, DAP);
10968 Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
10969 if (Fixed->getType()->isFunctionType())
10970 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
10971 else
10972 SrcExpr = Fixed;
10973 return true;
10974}
10975
George Burgess IV3cde9bf2016-03-19 21:36:10 +000010976/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010977/// resolve that overloaded function expression down to a single function.
10978///
10979/// This routine can only resolve template-ids that refer to a single function
10980/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010981/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010982/// as described in C++0x [temp.arg.explicit]p3.
Alp Toker67b47ac2013-10-20 18:48:56 +000010983///
10984/// If no template-ids are found, no diagnostics are emitted and NULL is
10985/// returned.
John McCall0009fcc2011-04-26 20:42:42 +000010986FunctionDecl *
10987Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
10988 bool Complain,
10989 DeclAccessPair *FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010990 // C++ [over.over]p1:
10991 // [...] [Note: any redundant set of parentheses surrounding the
10992 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010993 // C++ [over.over]p1:
10994 // [...] The overloaded function name can be preceded by the &
10995 // operator.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010996
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010997 // If we didn't actually find any template-ids, we're done.
John McCall0009fcc2011-04-26 20:42:42 +000010998 if (!ovl->hasExplicitTemplateArgs())
Craig Topperc3ec1492014-05-26 06:22:03 +000010999 return nullptr;
John McCall1acbbb52010-02-02 06:20:04 +000011000
11001 TemplateArgumentListInfo ExplicitTemplateArgs;
James Y Knight04ec5bf2015-12-24 02:59:37 +000011002 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
Larisse Voufo98b20f12013-07-19 23:00:19 +000011003 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011004
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011005 // Look through all of the overloaded functions, searching for one
11006 // whose type matches exactly.
Craig Topperc3ec1492014-05-26 06:22:03 +000011007 FunctionDecl *Matched = nullptr;
John McCall0009fcc2011-04-26 20:42:42 +000011008 for (UnresolvedSetIterator I = ovl->decls_begin(),
11009 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011010 // C++0x [temp.arg.explicit]p3:
11011 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011012 // where deduction is not done, if a template argument list is
11013 // specified and it, along with any default template arguments,
11014 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011015 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +000011016 FunctionTemplateDecl *FunctionTemplate
11017 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011018
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011019 // C++ [over.over]p2:
11020 // If the name is a function template, template argument deduction is
11021 // done (14.8.2.2), and if the argument deduction succeeds, the
11022 // resulting template argument list is used to generate a single
11023 // function template specialization, which is added to the set of
11024 // overloaded functions considered.
Craig Topperc3ec1492014-05-26 06:22:03 +000011025 FunctionDecl *Specialization = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +000011026 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011027 if (TemplateDeductionResult Result
11028 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
Douglas Gregor19a41f12013-04-17 08:45:07 +000011029 Specialization, Info,
Richard Smithbaa47832016-12-01 02:11:49 +000011030 /*IsAddressOfFunction*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000011031 // Make a note of the failed deduction for diagnostics.
11032 // TODO: Actually use the failed-deduction info?
11033 FailedCandidates.addCandidate()
Richard Smithc2bebe92016-05-11 20:37:46 +000011034 .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
Larisse Voufo98b20f12013-07-19 23:00:19 +000011035 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011036 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011037 }
11038
John McCall0009fcc2011-04-26 20:42:42 +000011039 assert(Specialization && "no specialization and no error?");
11040
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011041 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +000011042 if (Matched) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000011043 if (Complain) {
John McCall0009fcc2011-04-26 20:42:42 +000011044 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
11045 << ovl->getName();
11046 NoteAllOverloadCandidates(ovl);
Douglas Gregorb491ed32011-02-19 21:32:49 +000011047 }
Craig Topperc3ec1492014-05-26 06:22:03 +000011048 return nullptr;
John McCall0009fcc2011-04-26 20:42:42 +000011049 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000011050
John McCall0009fcc2011-04-26 20:42:42 +000011051 Matched = Specialization;
11052 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011053 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011054
Richard Smith9095e5b2016-11-01 01:31:23 +000011055 if (Matched &&
11056 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
Craig Topperc3ec1492014-05-26 06:22:03 +000011057 return nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +000011058
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011059 return Matched;
11060}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011061
Douglas Gregor1beec452011-03-12 01:48:56 +000011062
11063
11064
John McCall50a2c2c2011-10-11 23:14:30 +000011065// Resolve and fix an overloaded expression that can be resolved
11066// because it identifies a single function template specialization.
11067//
Douglas Gregor1beec452011-03-12 01:48:56 +000011068// Last three arguments should only be supplied if Complain = true
John McCall50a2c2c2011-10-11 23:14:30 +000011069//
11070// Return true if it was logically possible to so resolve the
11071// expression, regardless of whether or not it succeeded. Always
11072// returns true if 'complain' is set.
11073bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
11074 ExprResult &SrcExpr, bool doFunctionPointerConverion,
Craig Toppere335f252015-10-04 04:53:55 +000011075 bool complain, SourceRange OpRangeForComplaining,
Douglas Gregor1beec452011-03-12 01:48:56 +000011076 QualType DestTypeForComplaining,
John McCall0009fcc2011-04-26 20:42:42 +000011077 unsigned DiagIDForComplaining) {
John McCall50a2c2c2011-10-11 23:14:30 +000011078 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregor1beec452011-03-12 01:48:56 +000011079
John McCall50a2c2c2011-10-11 23:14:30 +000011080 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregor1beec452011-03-12 01:48:56 +000011081
John McCall0009fcc2011-04-26 20:42:42 +000011082 DeclAccessPair found;
11083 ExprResult SingleFunctionExpression;
11084 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
11085 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011086 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall50a2c2c2011-10-11 23:14:30 +000011087 SrcExpr = ExprError();
11088 return true;
11089 }
John McCall0009fcc2011-04-26 20:42:42 +000011090
11091 // It is only correct to resolve to an instance method if we're
11092 // resolving a form that's permitted to be a pointer to member.
11093 // Otherwise we'll end up making a bound member expression, which
11094 // is illegal in all the contexts we resolve like this.
11095 if (!ovl.HasFormOfMemberPointer &&
11096 isa<CXXMethodDecl>(fn) &&
11097 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall50a2c2c2011-10-11 23:14:30 +000011098 if (!complain) return false;
11099
11100 Diag(ovl.Expression->getExprLoc(),
11101 diag::err_bound_member_function)
11102 << 0 << ovl.Expression->getSourceRange();
11103
11104 // TODO: I believe we only end up here if there's a mix of
11105 // static and non-static candidates (otherwise the expression
11106 // would have 'bound member' type, not 'overload' type).
11107 // Ideally we would note which candidate was chosen and why
11108 // the static candidates were rejected.
11109 SrcExpr = ExprError();
11110 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000011111 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +000011112
Sylvestre Ledrua5202662012-07-31 06:56:50 +000011113 // Fix the expression to refer to 'fn'.
John McCall0009fcc2011-04-26 20:42:42 +000011114 SingleFunctionExpression =
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011115 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
John McCall0009fcc2011-04-26 20:42:42 +000011116
11117 // If desired, do function-to-pointer decay.
John McCall50a2c2c2011-10-11 23:14:30 +000011118 if (doFunctionPointerConverion) {
John McCall0009fcc2011-04-26 20:42:42 +000011119 SingleFunctionExpression =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011120 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
John McCall50a2c2c2011-10-11 23:14:30 +000011121 if (SingleFunctionExpression.isInvalid()) {
11122 SrcExpr = ExprError();
11123 return true;
11124 }
11125 }
John McCall0009fcc2011-04-26 20:42:42 +000011126 }
11127
11128 if (!SingleFunctionExpression.isUsable()) {
11129 if (complain) {
11130 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
11131 << ovl.Expression->getName()
11132 << DestTypeForComplaining
11133 << OpRangeForComplaining
11134 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall50a2c2c2011-10-11 23:14:30 +000011135 NoteAllOverloadCandidates(SrcExpr.get());
11136
11137 SrcExpr = ExprError();
11138 return true;
11139 }
11140
11141 return false;
John McCall0009fcc2011-04-26 20:42:42 +000011142 }
11143
John McCall50a2c2c2011-10-11 23:14:30 +000011144 SrcExpr = SingleFunctionExpression;
11145 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000011146}
11147
Douglas Gregorcabea402009-09-22 15:41:20 +000011148/// \brief Add a single candidate to the overload set.
11149static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +000011150 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +000011151 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011152 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000011153 OverloadCandidateSet &CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +000011154 bool PartialOverloading,
11155 bool KnownValid) {
John McCalla0296f72010-03-19 07:35:19 +000011156 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +000011157 if (isa<UsingShadowDecl>(Callee))
11158 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
11159
Douglas Gregorcabea402009-09-22 15:41:20 +000011160 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith95ce4f62011-06-26 22:19:54 +000011161 if (ExplicitTemplateArgs) {
11162 assert(!KnownValid && "Explicit template arguments?");
11163 return;
11164 }
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011165 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
11166 /*SuppressUsedConversions=*/false,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011167 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000011168 return;
John McCalld14a8642009-11-21 08:51:07 +000011169 }
11170
11171 if (FunctionTemplateDecl *FuncTemplate
11172 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +000011173 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011174 ExplicitTemplateArgs, Args, CandidateSet,
11175 /*SuppressUsedConversions=*/false,
11176 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +000011177 return;
11178 }
11179
Richard Smith95ce4f62011-06-26 22:19:54 +000011180 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregorcabea402009-09-22 15:41:20 +000011181}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011182
Douglas Gregorcabea402009-09-22 15:41:20 +000011183/// \brief Add the overload candidates named by callee and/or found by argument
11184/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +000011185void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011186 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000011187 OverloadCandidateSet &CandidateSet,
11188 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +000011189
11190#ifndef NDEBUG
11191 // Verify that ArgumentDependentLookup is consistent with the rules
11192 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +000011193 //
Douglas Gregorcabea402009-09-22 15:41:20 +000011194 // Let X be the lookup set produced by unqualified lookup (3.4.1)
11195 // and let Y be the lookup set produced by argument dependent
11196 // lookup (defined as follows). If X contains
11197 //
11198 // -- a declaration of a class member, or
11199 //
11200 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +000011201 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +000011202 //
11203 // -- a declaration that is neither a function or a function
11204 // template
11205 //
11206 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +000011207
John McCall57500772009-12-16 12:17:52 +000011208 if (ULE->requiresADL()) {
11209 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11210 E = ULE->decls_end(); I != E; ++I) {
11211 assert(!(*I)->getDeclContext()->isRecord());
11212 assert(isa<UsingShadowDecl>(*I) ||
11213 !(*I)->getDeclContext()->isFunctionOrMethod());
11214 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +000011215 }
11216 }
11217#endif
11218
John McCall57500772009-12-16 12:17:52 +000011219 // It would be nice to avoid this copy.
11220 TemplateArgumentListInfo TABuffer;
Craig Topperc3ec1492014-05-26 06:22:03 +000011221 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
John McCall57500772009-12-16 12:17:52 +000011222 if (ULE->hasExplicitTemplateArgs()) {
11223 ULE->copyTemplateArgumentsInto(TABuffer);
11224 ExplicitTemplateArgs = &TABuffer;
11225 }
11226
11227 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11228 E = ULE->decls_end(); I != E; ++I)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011229 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
11230 CandidateSet, PartialOverloading,
11231 /*KnownValid*/ true);
John McCalld14a8642009-11-21 08:51:07 +000011232
John McCall57500772009-12-16 12:17:52 +000011233 if (ULE->requiresADL())
Richard Smith100b24a2014-04-17 01:52:14 +000011234 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011235 Args, ExplicitTemplateArgs,
Richard Smithb6626742012-10-18 17:56:02 +000011236 CandidateSet, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000011237}
John McCalld681c392009-12-16 08:11:27 +000011238
Richard Smith0603bbb2013-06-12 22:56:54 +000011239/// Determine whether a declaration with the specified name could be moved into
11240/// a different namespace.
11241static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
11242 switch (Name.getCXXOverloadedOperator()) {
11243 case OO_New: case OO_Array_New:
11244 case OO_Delete: case OO_Array_Delete:
11245 return false;
11246
11247 default:
11248 return true;
11249 }
11250}
11251
Richard Smith998a5912011-06-05 22:42:48 +000011252/// Attempt to recover from an ill-formed use of a non-dependent name in a
11253/// template, where the non-dependent name was declared after the template
11254/// was defined. This is common in code written for a compilers which do not
11255/// correctly implement two-stage name lookup.
11256///
11257/// Returns true if a viable candidate was found and a diagnostic was issued.
11258static bool
11259DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
11260 const CXXScopeSpec &SS, LookupResult &R,
Richard Smith100b24a2014-04-17 01:52:14 +000011261 OverloadCandidateSet::CandidateSetKind CSK,
Richard Smith998a5912011-06-05 22:42:48 +000011262 TemplateArgumentListInfo *ExplicitTemplateArgs,
Hans Wennborg64937c62015-06-11 21:21:57 +000011263 ArrayRef<Expr *> Args,
11264 bool *DoDiagnoseEmptyLookup = nullptr) {
Richard Smith998a5912011-06-05 22:42:48 +000011265 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
11266 return false;
11267
11268 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewyckyfcd5e7a2012-03-14 20:41:00 +000011269 if (DC->isTransparentContext())
11270 continue;
11271
Richard Smith998a5912011-06-05 22:42:48 +000011272 SemaRef.LookupQualifiedName(R, DC);
11273
11274 if (!R.empty()) {
11275 R.suppressDiagnostics();
11276
11277 if (isa<CXXRecordDecl>(DC)) {
11278 // Don't diagnose names we find in classes; we get much better
11279 // diagnostics for these from DiagnoseEmptyLookup.
11280 R.clear();
Hans Wennborg64937c62015-06-11 21:21:57 +000011281 if (DoDiagnoseEmptyLookup)
11282 *DoDiagnoseEmptyLookup = true;
Richard Smith998a5912011-06-05 22:42:48 +000011283 return false;
11284 }
11285
Richard Smith100b24a2014-04-17 01:52:14 +000011286 OverloadCandidateSet Candidates(FnLoc, CSK);
Richard Smith998a5912011-06-05 22:42:48 +000011287 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
11288 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011289 ExplicitTemplateArgs, Args,
Richard Smith95ce4f62011-06-26 22:19:54 +000011290 Candidates, false, /*KnownValid*/ false);
Richard Smith998a5912011-06-05 22:42:48 +000011291
11292 OverloadCandidateSet::iterator Best;
Richard Smith95ce4f62011-06-26 22:19:54 +000011293 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smith998a5912011-06-05 22:42:48 +000011294 // No viable functions. Don't bother the user with notes for functions
11295 // which don't work and shouldn't be found anyway.
Richard Smith95ce4f62011-06-26 22:19:54 +000011296 R.clear();
Richard Smith998a5912011-06-05 22:42:48 +000011297 return false;
Richard Smith95ce4f62011-06-26 22:19:54 +000011298 }
Richard Smith998a5912011-06-05 22:42:48 +000011299
11300 // Find the namespaces where ADL would have looked, and suggest
11301 // declaring the function there instead.
11302 Sema::AssociatedNamespaceSet AssociatedNamespaces;
11303 Sema::AssociatedClassSet AssociatedClasses;
John McCall7d8b0412012-08-24 20:38:34 +000011304 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
Richard Smith998a5912011-06-05 22:42:48 +000011305 AssociatedNamespaces,
11306 AssociatedClasses);
Chandler Carruthd50f1692011-06-05 23:36:55 +000011307 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smith0603bbb2013-06-12 22:56:54 +000011308 if (canBeDeclaredInNamespace(R.getLookupName())) {
11309 DeclContext *Std = SemaRef.getStdNamespace();
11310 for (Sema::AssociatedNamespaceSet::iterator
11311 it = AssociatedNamespaces.begin(),
11312 end = AssociatedNamespaces.end(); it != end; ++it) {
11313 // Never suggest declaring a function within namespace 'std'.
11314 if (Std && Std->Encloses(*it))
11315 continue;
Richard Smith21bae432012-12-22 02:46:14 +000011316
Richard Smith0603bbb2013-06-12 22:56:54 +000011317 // Never suggest declaring a function within a namespace with a
11318 // reserved name, like __gnu_cxx.
11319 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
11320 if (NS &&
11321 NS->getQualifiedNameAsString().find("__") != std::string::npos)
11322 continue;
11323
11324 SuggestedNamespaces.insert(*it);
11325 }
Richard Smith998a5912011-06-05 22:42:48 +000011326 }
11327
11328 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
11329 << R.getLookupName();
Chandler Carruthd50f1692011-06-05 23:36:55 +000011330 if (SuggestedNamespaces.empty()) {
Richard Smith998a5912011-06-05 22:42:48 +000011331 SemaRef.Diag(Best->Function->getLocation(),
11332 diag::note_not_found_by_two_phase_lookup)
11333 << R.getLookupName() << 0;
Chandler Carruthd50f1692011-06-05 23:36:55 +000011334 } else if (SuggestedNamespaces.size() == 1) {
Richard Smith998a5912011-06-05 22:42:48 +000011335 SemaRef.Diag(Best->Function->getLocation(),
11336 diag::note_not_found_by_two_phase_lookup)
Chandler Carruthd50f1692011-06-05 23:36:55 +000011337 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smith998a5912011-06-05 22:42:48 +000011338 } else {
11339 // FIXME: It would be useful to list the associated namespaces here,
11340 // but the diagnostics infrastructure doesn't provide a way to produce
11341 // a localized representation of a list of items.
11342 SemaRef.Diag(Best->Function->getLocation(),
11343 diag::note_not_found_by_two_phase_lookup)
11344 << R.getLookupName() << 2;
11345 }
11346
11347 // Try to recover by calling this function.
11348 return true;
11349 }
11350
11351 R.clear();
11352 }
11353
11354 return false;
11355}
11356
11357/// Attempt to recover from ill-formed use of a non-dependent operator in a
11358/// template, where the non-dependent operator was declared after the template
11359/// was defined.
11360///
11361/// Returns true if a viable candidate was found and a diagnostic was issued.
11362static bool
11363DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
11364 SourceLocation OpLoc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011365 ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +000011366 DeclarationName OpName =
11367 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
11368 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
11369 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Richard Smith100b24a2014-04-17 01:52:14 +000011370 OverloadCandidateSet::CSK_Operator,
Craig Topperc3ec1492014-05-26 06:22:03 +000011371 /*ExplicitTemplateArgs=*/nullptr, Args);
Richard Smith998a5912011-06-05 22:42:48 +000011372}
11373
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000011374namespace {
Richard Smith88d67f32012-09-25 04:46:05 +000011375class BuildRecoveryCallExprRAII {
11376 Sema &SemaRef;
11377public:
11378 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
11379 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
11380 SemaRef.IsBuildingRecoveryCallExpr = true;
11381 }
11382
11383 ~BuildRecoveryCallExprRAII() {
11384 SemaRef.IsBuildingRecoveryCallExpr = false;
11385 }
11386};
11387
Alexander Kornienkoab9db512015-06-22 23:07:51 +000011388}
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000011389
Kaelyn Takata89c881b2014-10-27 18:07:29 +000011390static std::unique_ptr<CorrectionCandidateCallback>
11391MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
11392 bool HasTemplateArgs, bool AllowTypoCorrection) {
11393 if (!AllowTypoCorrection)
11394 return llvm::make_unique<NoTypoCorrectionCCC>();
11395 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
11396 HasTemplateArgs, ME);
11397}
11398
John McCalld681c392009-12-16 08:11:27 +000011399/// Attempts to recover from a call where no functions were found.
11400///
11401/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +000011402static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +000011403BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +000011404 UnresolvedLookupExpr *ULE,
11405 SourceLocation LParenLoc,
Craig Toppere3d2ecbe2014-06-28 23:22:33 +000011406 MutableArrayRef<Expr *> Args,
Richard Smith998a5912011-06-05 22:42:48 +000011407 SourceLocation RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000011408 bool EmptyLookup, bool AllowTypoCorrection) {
Richard Smith88d67f32012-09-25 04:46:05 +000011409 // Do not try to recover if it is already building a recovery call.
11410 // This stops infinite loops for template instantiations like
11411 //
11412 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
11413 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
11414 //
11415 if (SemaRef.IsBuildingRecoveryCallExpr)
11416 return ExprError();
11417 BuildRecoveryCallExprRAII RCE(SemaRef);
John McCalld681c392009-12-16 08:11:27 +000011418
11419 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +000011420 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +000011421 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCalld681c392009-12-16 08:11:27 +000011422
John McCall57500772009-12-16 12:17:52 +000011423 TemplateArgumentListInfo TABuffer;
Craig Topperc3ec1492014-05-26 06:22:03 +000011424 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
John McCall57500772009-12-16 12:17:52 +000011425 if (ULE->hasExplicitTemplateArgs()) {
11426 ULE->copyTemplateArgumentsInto(TABuffer);
11427 ExplicitTemplateArgs = &TABuffer;
11428 }
11429
John McCalld681c392009-12-16 08:11:27 +000011430 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
11431 Sema::LookupOrdinaryName);
Hans Wennborg64937c62015-06-11 21:21:57 +000011432 bool DoDiagnoseEmptyLookup = EmptyLookup;
Richard Smith998a5912011-06-05 22:42:48 +000011433 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Richard Smith100b24a2014-04-17 01:52:14 +000011434 OverloadCandidateSet::CSK_Normal,
Hans Wennborg64937c62015-06-11 21:21:57 +000011435 ExplicitTemplateArgs, Args,
11436 &DoDiagnoseEmptyLookup) &&
11437 (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup(
11438 S, SS, R,
11439 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
11440 ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
11441 ExplicitTemplateArgs, Args)))
John McCallfaf5fb42010-08-26 23:41:50 +000011442 return ExprError();
John McCalld681c392009-12-16 08:11:27 +000011443
John McCall57500772009-12-16 12:17:52 +000011444 assert(!R.empty() && "lookup results empty despite recovery");
11445
Richard Smith151c4562016-12-20 21:35:28 +000011446 // If recovery created an ambiguity, just bail out.
11447 if (R.isAmbiguous()) {
11448 R.suppressDiagnostics();
11449 return ExprError();
11450 }
11451
John McCall57500772009-12-16 12:17:52 +000011452 // Build an implicit member call if appropriate. Just drop the
11453 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +000011454 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +000011455 if ((*R.begin())->isCXXClassMember())
Aaron Ballman6924dcd2015-09-01 14:49:24 +000011456 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
11457 ExplicitTemplateArgs, S);
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000011458 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnara7945c982012-01-27 09:46:47 +000011459 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000011460 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +000011461 else
11462 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
11463
11464 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +000011465 return ExprError();
John McCall57500772009-12-16 12:17:52 +000011466
11467 // This shouldn't cause an infinite loop because we're giving it
Richard Smith998a5912011-06-05 22:42:48 +000011468 // an expression with viable lookup results, which should never
John McCall57500772009-12-16 12:17:52 +000011469 // end up here.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011470 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011471 MultiExprArg(Args.data(), Args.size()),
11472 RParenLoc);
John McCalld681c392009-12-16 08:11:27 +000011473}
Douglas Gregor4038cf42010-06-08 17:35:15 +000011474
Sam Panzer0f384432012-08-21 00:52:01 +000011475/// \brief Constructs and populates an OverloadedCandidateSet from
11476/// the given function.
11477/// \returns true when an the ExprResult output parameter has been set.
11478bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
11479 UnresolvedLookupExpr *ULE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011480 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011481 SourceLocation RParenLoc,
11482 OverloadCandidateSet *CandidateSet,
11483 ExprResult *Result) {
John McCall57500772009-12-16 12:17:52 +000011484#ifndef NDEBUG
11485 if (ULE->requiresADL()) {
11486 // To do ADL, we must have found an unqualified name.
11487 assert(!ULE->getQualifier() && "qualified name with ADL");
11488
11489 // We don't perform ADL for implicit declarations of builtins.
11490 // Verify that this was correctly set up.
11491 FunctionDecl *F;
11492 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
11493 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
11494 F->getBuiltinID() && F->isImplicit())
David Blaikie83d382b2011-09-23 05:06:16 +000011495 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011496
John McCall57500772009-12-16 12:17:52 +000011497 // We don't perform ADL in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011498 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smithb6626742012-10-18 17:56:02 +000011499 }
John McCall57500772009-12-16 12:17:52 +000011500#endif
11501
John McCall4124c492011-10-17 18:40:02 +000011502 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011503 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
Sam Panzer0f384432012-08-21 00:52:01 +000011504 *Result = ExprError();
11505 return true;
11506 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +000011507
John McCall57500772009-12-16 12:17:52 +000011508 // Add the functions denoted by the callee to the set of candidate
11509 // functions, including those from argument-dependent lookup.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011510 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
John McCalld681c392009-12-16 08:11:27 +000011511
Hans Wennborgb2747382015-06-12 21:23:23 +000011512 if (getLangOpts().MSVCCompat &&
11513 CurContext->isDependentContext() && !isSFINAEContext() &&
Hans Wennborg64937c62015-06-11 21:21:57 +000011514 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
11515
11516 OverloadCandidateSet::iterator Best;
11517 if (CandidateSet->empty() ||
11518 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) ==
11519 OR_No_Viable_Function) {
11520 // In Microsoft mode, if we are inside a template class member function then
11521 // create a type dependent CallExpr. The goal is to postpone name lookup
11522 // to instantiation time to be able to search into type dependent base
11523 // classes.
11524 CallExpr *CE = new (Context) CallExpr(
11525 Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc);
Sebastian Redlb49c46c2011-09-24 17:48:00 +000011526 CE->setTypeDependent(true);
Richard Smithed9b8f02015-09-23 21:30:47 +000011527 CE->setValueDependent(true);
11528 CE->setInstantiationDependent(true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011529 *Result = CE;
Sam Panzer0f384432012-08-21 00:52:01 +000011530 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +000011531 }
Francois Pichetbcf64712011-09-07 00:14:57 +000011532 }
John McCalld681c392009-12-16 08:11:27 +000011533
Hans Wennborg64937c62015-06-11 21:21:57 +000011534 if (CandidateSet->empty())
11535 return false;
11536
John McCall4124c492011-10-17 18:40:02 +000011537 UnbridgedCasts.restore();
Sam Panzer0f384432012-08-21 00:52:01 +000011538 return false;
11539}
John McCall4124c492011-10-17 18:40:02 +000011540
Sam Panzer0f384432012-08-21 00:52:01 +000011541/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
11542/// the completed call expression. If overload resolution fails, emits
11543/// diagnostics and returns ExprError()
11544static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11545 UnresolvedLookupExpr *ULE,
11546 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011547 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011548 SourceLocation RParenLoc,
11549 Expr *ExecConfig,
11550 OverloadCandidateSet *CandidateSet,
11551 OverloadCandidateSet::iterator *Best,
11552 OverloadingResult OverloadResult,
11553 bool AllowTypoCorrection) {
11554 if (CandidateSet->empty())
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011555 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011556 RParenLoc, /*EmptyLookup=*/true,
11557 AllowTypoCorrection);
11558
11559 switch (OverloadResult) {
John McCall57500772009-12-16 12:17:52 +000011560 case OR_Success: {
Sam Panzer0f384432012-08-21 00:52:01 +000011561 FunctionDecl *FDecl = (*Best)->Function;
Sam Panzer0f384432012-08-21 00:52:01 +000011562 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000011563 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
11564 return ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000011565 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011566 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11567 ExecConfig);
John McCall57500772009-12-16 12:17:52 +000011568 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011569
Richard Smith998a5912011-06-05 22:42:48 +000011570 case OR_No_Viable_Function: {
11571 // Try to recover by looking for viable functions which the user might
11572 // have meant to call.
Sam Panzer0f384432012-08-21 00:52:01 +000011573 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011574 Args, RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000011575 /*EmptyLookup=*/false,
11576 AllowTypoCorrection);
Richard Smith998a5912011-06-05 22:42:48 +000011577 if (!Recovery.isInvalid())
11578 return Recovery;
11579
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011580 // If the user passes in a function that we can't take the address of, we
11581 // generally end up emitting really bad error messages. Here, we attempt to
11582 // emit better ones.
11583 for (const Expr *Arg : Args) {
11584 if (!Arg->getType()->isFunctionType())
11585 continue;
11586 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
11587 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
11588 if (FD &&
11589 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
11590 Arg->getExprLoc()))
11591 return ExprError();
11592 }
11593 }
11594
11595 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_no_viable_function_in_call)
11596 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011597 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011598 break;
Richard Smith998a5912011-06-05 22:42:48 +000011599 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011600
11601 case OR_Ambiguous:
Sam Panzer0f384432012-08-21 00:52:01 +000011602 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +000011603 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011604 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011605 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000011606
Sam Panzer0f384432012-08-21 00:52:01 +000011607 case OR_Deleted: {
11608 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
11609 << (*Best)->Function->isDeleted()
11610 << ULE->getName()
11611 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
11612 << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011613 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Argyrios Kyrtzidis3eaa22a2011-11-04 15:58:13 +000011614
Sam Panzer0f384432012-08-21 00:52:01 +000011615 // We emitted an error for the unvailable/deleted function call but keep
11616 // the call in the AST.
11617 FunctionDecl *FDecl = (*Best)->Function;
11618 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011619 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11620 ExecConfig);
Sam Panzer0f384432012-08-21 00:52:01 +000011621 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011622 }
11623
Douglas Gregorb412e172010-07-25 18:17:45 +000011624 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +000011625 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011626}
11627
George Burgess IV7204ed92016-01-07 02:26:57 +000011628static void markUnaddressableCandidatesUnviable(Sema &S,
11629 OverloadCandidateSet &CS) {
11630 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
11631 if (I->Viable &&
11632 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
11633 I->Viable = false;
11634 I->FailureKind = ovl_fail_addr_not_available;
11635 }
11636 }
11637}
11638
Sam Panzer0f384432012-08-21 00:52:01 +000011639/// BuildOverloadedCallExpr - Given the call expression that calls Fn
11640/// (which eventually refers to the declaration Func) and the call
11641/// arguments Args/NumArgs, attempt to resolve the function call down
11642/// to a specific function. If overload resolution succeeds, returns
11643/// the call expression produced by overload resolution.
11644/// Otherwise, emits diagnostics and returns ExprError.
11645ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
11646 UnresolvedLookupExpr *ULE,
11647 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011648 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011649 SourceLocation RParenLoc,
11650 Expr *ExecConfig,
George Burgess IV7204ed92016-01-07 02:26:57 +000011651 bool AllowTypoCorrection,
11652 bool CalleesAddressIsTaken) {
Richard Smith100b24a2014-04-17 01:52:14 +000011653 OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
11654 OverloadCandidateSet::CSK_Normal);
Sam Panzer0f384432012-08-21 00:52:01 +000011655 ExprResult result;
11656
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011657 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
11658 &result))
Sam Panzer0f384432012-08-21 00:52:01 +000011659 return result;
11660
George Burgess IV7204ed92016-01-07 02:26:57 +000011661 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
11662 // functions that aren't addressible are considered unviable.
11663 if (CalleesAddressIsTaken)
11664 markUnaddressableCandidatesUnviable(*this, CandidateSet);
11665
Sam Panzer0f384432012-08-21 00:52:01 +000011666 OverloadCandidateSet::iterator Best;
11667 OverloadingResult OverloadResult =
11668 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
11669
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011670 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011671 RParenLoc, ExecConfig, &CandidateSet,
11672 &Best, OverloadResult,
11673 AllowTypoCorrection);
11674}
11675
John McCall4c4c1df2010-01-26 03:27:55 +000011676static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +000011677 return Functions.size() > 1 ||
11678 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
11679}
11680
Douglas Gregor084d8552009-03-13 23:49:33 +000011681/// \brief Create a unary operation that may resolve to an overloaded
11682/// operator.
11683///
11684/// \param OpLoc The location of the operator itself (e.g., '*').
11685///
Craig Toppera92ffb02015-12-10 08:51:49 +000011686/// \param Opc The UnaryOperatorKind that describes this operator.
Douglas Gregor084d8552009-03-13 23:49:33 +000011687///
James Dennett18348b62012-06-22 08:52:37 +000011688/// \param Fns The set of non-member functions that will be
Douglas Gregor084d8552009-03-13 23:49:33 +000011689/// considered by overload resolution. The caller needs to build this
11690/// set based on the context using, e.g.,
11691/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11692/// set should not contain any member functions; those will be added
11693/// by CreateOverloadedUnaryOp().
11694///
James Dennett91738ff2012-06-22 10:32:46 +000011695/// \param Input The input argument.
John McCalldadc5752010-08-24 06:29:42 +000011696ExprResult
Craig Toppera92ffb02015-12-10 08:51:49 +000011697Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
John McCall4c4c1df2010-01-26 03:27:55 +000011698 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +000011699 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +000011700 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
11701 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
11702 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011703 // TODO: provide better source location info.
11704 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +000011705
John McCall4124c492011-10-17 18:40:02 +000011706 if (checkPlaceholderForOverload(*this, Input))
11707 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011708
Craig Topperc3ec1492014-05-26 06:22:03 +000011709 Expr *Args[2] = { Input, nullptr };
Douglas Gregor084d8552009-03-13 23:49:33 +000011710 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +000011711
Douglas Gregor084d8552009-03-13 23:49:33 +000011712 // For post-increment and post-decrement, add the implicit '0' as
11713 // the second argument, so that we know this is a post-increment or
11714 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +000011715 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +000011716 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +000011717 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
11718 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +000011719 NumArgs = 2;
11720 }
11721
Richard Smithe54c3072013-05-05 15:51:06 +000011722 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
11723
Douglas Gregor084d8552009-03-13 23:49:33 +000011724 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +000011725 if (Fns.empty())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011726 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
11727 VK_RValue, OK_Ordinary, OpLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011728
Craig Topperc3ec1492014-05-26 06:22:03 +000011729 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +000011730 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000011731 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000011732 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000011733 /*ADL*/ true, IsOverloaded(Fns),
11734 Fns.begin(), Fns.end());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011735 return new (Context)
11736 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
11737 VK_RValue, OpLoc, false);
Douglas Gregor084d8552009-03-13 23:49:33 +000011738 }
11739
11740 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000011741 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
Douglas Gregor084d8552009-03-13 23:49:33 +000011742
11743 // Add the candidates from the given function set.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011744 AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000011745
11746 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000011747 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000011748
John McCall4c4c1df2010-01-26 03:27:55 +000011749 // Add candidates from ADL.
Richard Smith100b24a2014-04-17 01:52:14 +000011750 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
Craig Topperc3ec1492014-05-26 06:22:03 +000011751 /*ExplicitTemplateArgs*/nullptr,
11752 CandidateSet);
John McCall4c4c1df2010-01-26 03:27:55 +000011753
Douglas Gregor084d8552009-03-13 23:49:33 +000011754 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011755 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000011756
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011757 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11758
Douglas Gregor084d8552009-03-13 23:49:33 +000011759 // Perform overload resolution.
11760 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011761 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +000011762 case OR_Success: {
11763 // We found a built-in operator or an overloaded operator.
11764 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +000011765
Douglas Gregor084d8552009-03-13 23:49:33 +000011766 if (FnDecl) {
11767 // We matched an overloaded operator. Build a call to that
11768 // operator.
Mike Stump11289f42009-09-09 15:08:12 +000011769
Douglas Gregor084d8552009-03-13 23:49:33 +000011770 // Convert the arguments.
11771 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Craig Topperc3ec1492014-05-26 06:22:03 +000011772 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000011773
John Wiegley01296292011-04-08 18:41:53 +000011774 ExprResult InputRes =
Craig Topperc3ec1492014-05-26 06:22:03 +000011775 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000011776 Best->FoundDecl, Method);
11777 if (InputRes.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000011778 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011779 Input = InputRes.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000011780 } else {
11781 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000011782 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +000011783 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000011784 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +000011785 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011786 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +000011787 Input);
Douglas Gregore6600372009-12-23 17:40:29 +000011788 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000011789 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011790 Input = InputInit.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000011791 }
11792
Douglas Gregor084d8552009-03-13 23:49:33 +000011793 // Build the actual expression node.
Nick Lewycky134af912013-02-07 05:08:22 +000011794 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011795 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011796 if (FnExpr.isInvalid())
11797 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +000011798
Richard Smithc1564702013-11-15 02:58:23 +000011799 // Determine the result type.
Alp Toker314cc812014-01-25 16:55:45 +000011800 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000011801 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11802 ResultTy = ResultTy.getNonLValueExprType(Context);
11803
Eli Friedman030eee42009-11-18 03:58:17 +000011804 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +000011805 CallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011806 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
Lang Hames5de91cc2012-10-02 04:45:10 +000011807 ResultTy, VK, OpLoc, false);
John McCall4fa0d5f2010-05-06 18:15:07 +000011808
Alp Toker314cc812014-01-25 16:55:45 +000011809 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
Anders Carlssonf64a3da2009-10-13 21:19:37 +000011810 return ExprError();
11811
John McCallb268a282010-08-23 23:25:46 +000011812 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +000011813 } else {
11814 // We matched a built-in operator. Convert the arguments, then
11815 // break out so that we will build the appropriate built-in
11816 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000011817 ExprResult InputRes =
11818 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
11819 Best->Conversions[0], AA_Passing);
11820 if (InputRes.isInvalid())
11821 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011822 Input = InputRes.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000011823 break;
Douglas Gregor084d8552009-03-13 23:49:33 +000011824 }
John Wiegley01296292011-04-08 18:41:53 +000011825 }
11826
11827 case OR_No_Viable_Function:
Richard Smith998a5912011-06-05 22:42:48 +000011828 // This is an erroneous use of an operator which can be overloaded by
11829 // a non-member function. Check for non-member operators which were
11830 // defined too late to be candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011831 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
Richard Smith998a5912011-06-05 22:42:48 +000011832 // FIXME: Recover by calling the found function.
11833 return ExprError();
11834
John Wiegley01296292011-04-08 18:41:53 +000011835 // No viable function; fall through to handling this as a
11836 // built-in operator, which will produce an error message for us.
11837 break;
11838
11839 case OR_Ambiguous:
11840 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
11841 << UnaryOperator::getOpcodeStr(Opc)
11842 << Input->getType()
11843 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000011844 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
John Wiegley01296292011-04-08 18:41:53 +000011845 UnaryOperator::getOpcodeStr(Opc), OpLoc);
11846 return ExprError();
11847
11848 case OR_Deleted:
11849 Diag(OpLoc, diag::err_ovl_deleted_oper)
11850 << Best->Function->isDeleted()
11851 << UnaryOperator::getOpcodeStr(Opc)
11852 << getDeletedOrUnavailableSuffix(Best->Function)
11853 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000011854 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000011855 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011856 return ExprError();
11857 }
Douglas Gregor084d8552009-03-13 23:49:33 +000011858
11859 // Either we found no viable overloaded operator or we matched a
11860 // built-in operator. In either case, fall through to trying to
11861 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +000011862 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +000011863}
11864
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011865/// \brief Create a binary operation that may resolve to an overloaded
11866/// operator.
11867///
11868/// \param OpLoc The location of the operator itself (e.g., '+').
11869///
Craig Toppera92ffb02015-12-10 08:51:49 +000011870/// \param Opc The BinaryOperatorKind that describes this operator.
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011871///
James Dennett18348b62012-06-22 08:52:37 +000011872/// \param Fns The set of non-member functions that will be
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011873/// considered by overload resolution. The caller needs to build this
11874/// set based on the context using, e.g.,
11875/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11876/// set should not contain any member functions; those will be added
11877/// by CreateOverloadedBinOp().
11878///
11879/// \param LHS Left-hand argument.
11880/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +000011881ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011882Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Craig Toppera92ffb02015-12-10 08:51:49 +000011883 BinaryOperatorKind Opc,
John McCall4c4c1df2010-01-26 03:27:55 +000011884 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011885 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011886 Expr *Args[2] = { LHS, RHS };
Craig Topperc3ec1492014-05-26 06:22:03 +000011887 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011888
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011889 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
11890 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
11891
11892 // If either side is type-dependent, create an appropriate dependent
11893 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +000011894 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +000011895 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011896 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +000011897 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +000011898 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011899 return new (Context) BinaryOperator(
11900 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
11901 OpLoc, FPFeatures.fp_contract);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011902
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011903 return new (Context) CompoundAssignOperator(
11904 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
11905 Context.DependentTy, Context.DependentTy, OpLoc,
11906 FPFeatures.fp_contract);
Douglas Gregor5287f092009-11-05 00:51:44 +000011907 }
John McCall4c4c1df2010-01-26 03:27:55 +000011908
11909 // FIXME: save results of ADL from here?
Craig Topperc3ec1492014-05-26 06:22:03 +000011910 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011911 // TODO: provide better source location info in DNLoc component.
11912 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +000011913 UnresolvedLookupExpr *Fn
Douglas Gregor0da1d432011-02-28 20:01:57 +000011914 = UnresolvedLookupExpr::Create(Context, NamingClass,
11915 NestedNameSpecifierLoc(), OpNameInfo,
11916 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000011917 Fns.begin(), Fns.end());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011918 return new (Context)
11919 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
11920 VK_RValue, OpLoc, FPFeatures.fp_contract);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011921 }
11922
John McCall4124c492011-10-17 18:40:02 +000011923 // Always do placeholder-like conversions on the RHS.
11924 if (checkPlaceholderForOverload(*this, Args[1]))
11925 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011926
John McCall526ab472011-10-25 17:37:35 +000011927 // Do placeholder-like conversion on the LHS; note that we should
11928 // not get here with a PseudoObject LHS.
11929 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall4124c492011-10-17 18:40:02 +000011930 if (checkPlaceholderForOverload(*this, Args[0]))
11931 return ExprError();
11932
Sebastian Redl6a96bf72009-11-18 23:10:33 +000011933 // If this is the assignment operator, we only perform overload resolution
11934 // if the left-hand side is a class or enumeration type. This is actually
11935 // a hack. The standard requires that we do overload resolution between the
11936 // various built-in candidates, but as DR507 points out, this can lead to
11937 // problems. So we do it this way, which pretty much follows what GCC does.
11938 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +000011939 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +000011940 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011941
John McCalle26a8722010-12-04 08:14:53 +000011942 // If this is the .* operator, which is not overloadable, just
11943 // create a built-in binary operator.
11944 if (Opc == BO_PtrMemD)
11945 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11946
Douglas Gregor084d8552009-03-13 23:49:33 +000011947 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000011948 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011949
11950 // Add the candidates from the given function set.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011951 AddFunctionCandidates(Fns, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011952
11953 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000011954 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011955
Richard Smith0daabd72014-09-23 20:31:39 +000011956 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
11957 // performed for an assignment operator (nor for operator[] nor operator->,
11958 // which don't get here).
11959 if (Opc != BO_Assign)
11960 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
11961 /*ExplicitTemplateArgs*/ nullptr,
11962 CandidateSet);
John McCall4c4c1df2010-01-26 03:27:55 +000011963
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011964 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011965 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011966
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011967 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11968
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011969 // Perform overload resolution.
11970 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011971 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +000011972 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011973 // We found a built-in operator or an overloaded operator.
11974 FunctionDecl *FnDecl = Best->Function;
11975
11976 if (FnDecl) {
11977 // We matched an overloaded operator. Build a call to that
11978 // operator.
11979
11980 // Convert the arguments.
11981 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +000011982 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +000011983 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000011984
Chandler Carruth8e543b32010-12-12 08:17:55 +000011985 ExprResult Arg1 =
11986 PerformCopyInitialization(
11987 InitializedEntity::InitializeParameter(Context,
11988 FnDecl->getParamDecl(0)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011989 SourceLocation(), Args[1]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011990 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011991 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011992
John Wiegley01296292011-04-08 18:41:53 +000011993 ExprResult Arg0 =
Craig Topperc3ec1492014-05-26 06:22:03 +000011994 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000011995 Best->FoundDecl, Method);
11996 if (Arg0.isInvalid())
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011997 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011998 Args[0] = Arg0.getAs<Expr>();
11999 Args[1] = RHS = Arg1.getAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012000 } else {
12001 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +000012002 ExprResult Arg0 = PerformCopyInitialization(
12003 InitializedEntity::InitializeParameter(Context,
12004 FnDecl->getParamDecl(0)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012005 SourceLocation(), Args[0]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000012006 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012007 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000012008
Chandler Carruth8e543b32010-12-12 08:17:55 +000012009 ExprResult Arg1 =
12010 PerformCopyInitialization(
12011 InitializedEntity::InitializeParameter(Context,
12012 FnDecl->getParamDecl(1)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012013 SourceLocation(), Args[1]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000012014 if (Arg1.isInvalid())
12015 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012016 Args[0] = LHS = Arg0.getAs<Expr>();
12017 Args[1] = RHS = Arg1.getAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012018 }
12019
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012020 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012021 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000012022 Best->FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012023 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000012024 if (FnExpr.isInvalid())
12025 return ExprError();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012026
Richard Smithc1564702013-11-15 02:58:23 +000012027 // Determine the result type.
Alp Toker314cc812014-01-25 16:55:45 +000012028 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000012029 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12030 ResultTy = ResultTy.getNonLValueExprType(Context);
12031
John McCallb268a282010-08-23 23:25:46 +000012032 CXXOperatorCallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012033 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
Lang Hames5de91cc2012-10-02 04:45:10 +000012034 Args, ResultTy, VK, OpLoc,
12035 FPFeatures.fp_contract);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012036
Alp Toker314cc812014-01-25 16:55:45 +000012037 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000012038 FnDecl))
12039 return ExprError();
12040
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000012041 ArrayRef<const Expr *> ArgsArray(Args, 2);
12042 // Cut off the implicit 'this'.
12043 if (isa<CXXMethodDecl>(FnDecl))
12044 ArgsArray = ArgsArray.slice(1);
Richard Trieu36d0b2b2015-01-13 02:32:02 +000012045
12046 // Check for a self move.
12047 if (Op == OO_Equal)
12048 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
12049
Douglas Gregorb4866e82015-06-19 18:13:19 +000012050 checkCall(FnDecl, nullptr, ArgsArray, isa<CXXMethodDecl>(FnDecl), OpLoc,
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000012051 TheCall->getSourceRange(), VariadicDoesNotApply);
12052
John McCallb268a282010-08-23 23:25:46 +000012053 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012054 } else {
12055 // We matched a built-in operator. Convert the arguments, then
12056 // break out so that we will build the appropriate built-in
12057 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000012058 ExprResult ArgsRes0 =
12059 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
12060 Best->Conversions[0], AA_Passing);
12061 if (ArgsRes0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012062 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012063 Args[0] = ArgsRes0.get();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012064
John Wiegley01296292011-04-08 18:41:53 +000012065 ExprResult ArgsRes1 =
12066 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
12067 Best->Conversions[1], AA_Passing);
12068 if (ArgsRes1.isInvalid())
12069 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012070 Args[1] = ArgsRes1.get();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012071 break;
12072 }
12073 }
12074
Douglas Gregor66950a32009-09-30 21:46:01 +000012075 case OR_No_Viable_Function: {
12076 // C++ [over.match.oper]p9:
12077 // If the operator is the operator , [...] and there are no
12078 // viable functions, then the operator is assumed to be the
12079 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +000012080 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +000012081 break;
12082
Chandler Carruth8e543b32010-12-12 08:17:55 +000012083 // For class as left operand for assignment or compound assigment
12084 // operator do not fall through to handling in built-in, but report that
12085 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +000012086 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012087 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +000012088 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +000012089 Diag(OpLoc, diag::err_ovl_no_viable_oper)
12090 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +000012091 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Eli Friedmana31efa02013-08-28 20:35:35 +000012092 if (Args[0]->getType()->isIncompleteType()) {
12093 Diag(OpLoc, diag::note_assign_lhs_incomplete)
12094 << Args[0]->getType()
12095 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12096 }
Douglas Gregor66950a32009-09-30 21:46:01 +000012097 } else {
Richard Smith998a5912011-06-05 22:42:48 +000012098 // This is an erroneous use of an operator which can be overloaded by
12099 // a non-member function. Check for non-member operators which were
12100 // defined too late to be candidates.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012101 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smith998a5912011-06-05 22:42:48 +000012102 // FIXME: Recover by calling the found function.
12103 return ExprError();
12104
Douglas Gregor66950a32009-09-30 21:46:01 +000012105 // No viable function; try to create a built-in operation, which will
12106 // produce an error. Then, show the non-viable candidates.
12107 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +000012108 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012109 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +000012110 "C++ binary operator overloading is missing candidates!");
12111 if (Result.isInvalid())
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012112 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012113 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012114 return Result;
Douglas Gregor66950a32009-09-30 21:46:01 +000012115 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012116
12117 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000012118 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012119 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +000012120 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +000012121 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012122 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012123 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012124 return ExprError();
12125
12126 case OR_Deleted:
Douglas Gregor74f7d502012-02-15 19:33:52 +000012127 if (isImplicitlyDeleted(Best->Function)) {
12128 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12129 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
Richard Smithde1a4872012-12-28 12:23:24 +000012130 << Context.getRecordType(Method->getParent())
12131 << getSpecialMember(Method);
Richard Smith6f1e2c62012-04-02 20:59:25 +000012132
Richard Smithde1a4872012-12-28 12:23:24 +000012133 // The user probably meant to call this special member. Just
12134 // explain why it's deleted.
12135 NoteDeletedFunction(Method);
12136 return ExprError();
Douglas Gregor74f7d502012-02-15 19:33:52 +000012137 } else {
12138 Diag(OpLoc, diag::err_ovl_deleted_oper)
12139 << Best->Function->isDeleted()
12140 << BinaryOperator::getOpcodeStr(Opc)
12141 << getDeletedOrUnavailableSuffix(Best->Function)
12142 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12143 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012144 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000012145 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012146 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +000012147 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012148
Douglas Gregor66950a32009-09-30 21:46:01 +000012149 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +000012150 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012151}
12152
John McCalldadc5752010-08-24 06:29:42 +000012153ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +000012154Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
12155 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +000012156 Expr *Base, Expr *Idx) {
12157 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +000012158 DeclarationName OpName =
12159 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
12160
12161 // If either side is type-dependent, create an appropriate dependent
12162 // expression.
12163 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12164
Craig Topperc3ec1492014-05-26 06:22:03 +000012165 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000012166 // CHECKME: no 'operator' keyword?
12167 DeclarationNameInfo OpNameInfo(OpName, LLoc);
12168 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +000012169 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000012170 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000012171 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000012172 /*ADL*/ true, /*Overloaded*/ false,
12173 UnresolvedSetIterator(),
12174 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +000012175 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +000012176
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012177 return new (Context)
12178 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
12179 Context.DependentTy, VK_RValue, RLoc, false);
Sebastian Redladba46e2009-10-29 20:17:01 +000012180 }
12181
John McCall4124c492011-10-17 18:40:02 +000012182 // Handle placeholders on both operands.
12183 if (checkPlaceholderForOverload(*this, Args[0]))
12184 return ExprError();
12185 if (checkPlaceholderForOverload(*this, Args[1]))
12186 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012187
Sebastian Redladba46e2009-10-29 20:17:01 +000012188 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000012189 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
Sebastian Redladba46e2009-10-29 20:17:01 +000012190
12191 // Subscript can only be overloaded as a member function.
12192
12193 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000012194 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000012195
12196 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000012197 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000012198
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012199 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12200
Sebastian Redladba46e2009-10-29 20:17:01 +000012201 // Perform overload resolution.
12202 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012203 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +000012204 case OR_Success: {
12205 // We found a built-in operator or an overloaded operator.
12206 FunctionDecl *FnDecl = Best->Function;
12207
12208 if (FnDecl) {
12209 // We matched an overloaded operator. Build a call to that
12210 // operator.
12211
John McCalla0296f72010-03-19 07:35:19 +000012212 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall58cc69d2010-01-27 01:50:18 +000012213
Sebastian Redladba46e2009-10-29 20:17:01 +000012214 // Convert the arguments.
12215 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley01296292011-04-08 18:41:53 +000012216 ExprResult Arg0 =
Craig Topperc3ec1492014-05-26 06:22:03 +000012217 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012218 Best->FoundDecl, Method);
12219 if (Arg0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000012220 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012221 Args[0] = Arg0.get();
Sebastian Redladba46e2009-10-29 20:17:01 +000012222
Anders Carlssona68e51e2010-01-29 18:37:50 +000012223 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000012224 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +000012225 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000012226 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +000012227 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012228 SourceLocation(),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012229 Args[1]);
Anders Carlssona68e51e2010-01-29 18:37:50 +000012230 if (InputInit.isInvalid())
12231 return ExprError();
12232
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012233 Args[1] = InputInit.getAs<Expr>();
Anders Carlssona68e51e2010-01-29 18:37:50 +000012234
Sebastian Redladba46e2009-10-29 20:17:01 +000012235 // Build the actual expression node.
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012236 DeclarationNameInfo OpLocInfo(OpName, LLoc);
12237 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012238 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000012239 Best->FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012240 HadMultipleCandidates,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012241 OpLocInfo.getLoc(),
12242 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000012243 if (FnExpr.isInvalid())
12244 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000012245
Richard Smithc1564702013-11-15 02:58:23 +000012246 // Determine the result type
Alp Toker314cc812014-01-25 16:55:45 +000012247 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000012248 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12249 ResultTy = ResultTy.getNonLValueExprType(Context);
12250
John McCallb268a282010-08-23 23:25:46 +000012251 CXXOperatorCallExpr *TheCall =
12252 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012253 FnExpr.get(), Args,
Lang Hames5de91cc2012-10-02 04:45:10 +000012254 ResultTy, VK, RLoc,
12255 false);
Sebastian Redladba46e2009-10-29 20:17:01 +000012256
Alp Toker314cc812014-01-25 16:55:45 +000012257 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
Sebastian Redladba46e2009-10-29 20:17:01 +000012258 return ExprError();
12259
John McCallb268a282010-08-23 23:25:46 +000012260 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +000012261 } else {
12262 // We matched a built-in operator. Convert the arguments, then
12263 // break out so that we will build the appropriate built-in
12264 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000012265 ExprResult ArgsRes0 =
12266 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
12267 Best->Conversions[0], AA_Passing);
12268 if (ArgsRes0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000012269 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012270 Args[0] = ArgsRes0.get();
John Wiegley01296292011-04-08 18:41:53 +000012271
12272 ExprResult ArgsRes1 =
12273 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
12274 Best->Conversions[1], AA_Passing);
12275 if (ArgsRes1.isInvalid())
12276 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012277 Args[1] = ArgsRes1.get();
Sebastian Redladba46e2009-10-29 20:17:01 +000012278
12279 break;
12280 }
12281 }
12282
12283 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +000012284 if (CandidateSet.empty())
12285 Diag(LLoc, diag::err_ovl_no_oper)
12286 << Args[0]->getType() << /*subscript*/ 0
12287 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12288 else
12289 Diag(LLoc, diag::err_ovl_no_viable_subscript)
12290 << Args[0]->getType()
12291 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012292 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012293 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +000012294 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000012295 }
12296
12297 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000012298 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012299 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +000012300 << Args[0]->getType() << Args[1]->getType()
12301 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012302 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012303 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000012304 return ExprError();
12305
12306 case OR_Deleted:
12307 Diag(LLoc, diag::err_ovl_deleted_oper)
12308 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012309 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +000012310 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012311 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012312 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000012313 return ExprError();
12314 }
12315
12316 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +000012317 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000012318}
12319
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012320/// BuildCallToMemberFunction - Build a call to a member
12321/// function. MemExpr is the expression that refers to the member
12322/// function (and includes the object parameter), Args/NumArgs are the
12323/// arguments to the function call (not including the object
12324/// parameter). The caller needs to validate that the member
John McCall0009fcc2011-04-26 20:42:42 +000012325/// expression refers to a non-static member function or an overloaded
12326/// member function.
John McCalldadc5752010-08-24 06:29:42 +000012327ExprResult
Mike Stump11289f42009-09-09 15:08:12 +000012328Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012329 SourceLocation LParenLoc,
12330 MultiExprArg Args,
12331 SourceLocation RParenLoc) {
John McCall0009fcc2011-04-26 20:42:42 +000012332 assert(MemExprE->getType() == Context.BoundMemberTy ||
12333 MemExprE->getType() == Context.OverloadTy);
12334
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012335 // Dig out the member expression. This holds both the object
12336 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +000012337 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012338
John McCall0009fcc2011-04-26 20:42:42 +000012339 // Determine whether this is a call to a pointer-to-member function.
12340 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
12341 assert(op->getType() == Context.BoundMemberTy);
12342 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
12343
12344 QualType fnType =
12345 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
12346
12347 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
12348 QualType resultType = proto->getCallResultType(Context);
Alp Toker314cc812014-01-25 16:55:45 +000012349 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
John McCall0009fcc2011-04-26 20:42:42 +000012350
12351 // Check that the object type isn't more qualified than the
12352 // member function we're calling.
12353 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
12354
12355 QualType objectType = op->getLHS()->getType();
12356 if (op->getOpcode() == BO_PtrMemI)
12357 objectType = objectType->castAs<PointerType>()->getPointeeType();
12358 Qualifiers objectQuals = objectType.getQualifiers();
12359
12360 Qualifiers difference = objectQuals - funcQuals;
12361 difference.removeObjCGCAttr();
12362 difference.removeAddressSpace();
12363 if (difference) {
12364 std::string qualsString = difference.getAsString();
12365 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
12366 << fnType.getUnqualifiedType()
12367 << qualsString
12368 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
12369 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +000012370
John McCall0009fcc2011-04-26 20:42:42 +000012371 CXXMemberCallExpr *call
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012372 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall0009fcc2011-04-26 20:42:42 +000012373 resultType, valueKind, RParenLoc);
12374
Alp Toker314cc812014-01-25 16:55:45 +000012375 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
Craig Topperc3ec1492014-05-26 06:22:03 +000012376 call, nullptr))
John McCall0009fcc2011-04-26 20:42:42 +000012377 return ExprError();
12378
Craig Topperc3ec1492014-05-26 06:22:03 +000012379 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
John McCall0009fcc2011-04-26 20:42:42 +000012380 return ExprError();
12381
Richard Trieu9be9c682013-06-22 02:30:38 +000012382 if (CheckOtherCall(call, proto))
12383 return ExprError();
12384
John McCall0009fcc2011-04-26 20:42:42 +000012385 return MaybeBindToTemporary(call);
12386 }
12387
David Majnemerced8bdf2015-02-25 17:36:15 +000012388 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
12389 return new (Context)
12390 CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc);
12391
John McCall4124c492011-10-17 18:40:02 +000012392 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012393 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000012394 return ExprError();
12395
John McCall10eae182009-11-30 22:42:35 +000012396 MemberExpr *MemExpr;
Craig Topperc3ec1492014-05-26 06:22:03 +000012397 CXXMethodDecl *Method = nullptr;
12398 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
12399 NestedNameSpecifier *Qualifier = nullptr;
John McCall10eae182009-11-30 22:42:35 +000012400 if (isa<MemberExpr>(NakedMemExpr)) {
12401 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +000012402 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +000012403 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +000012404 Qualifier = MemExpr->getQualifier();
John McCall4124c492011-10-17 18:40:02 +000012405 UnbridgedCasts.restore();
John McCall10eae182009-11-30 22:42:35 +000012406 } else {
12407 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +000012408 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012409
John McCall6e9f8f62009-12-03 04:06:58 +000012410 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +000012411 Expr::Classification ObjectClassification
12412 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
12413 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +000012414
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012415 // Add overload candidates
Richard Smith100b24a2014-04-17 01:52:14 +000012416 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
12417 OverloadCandidateSet::CSK_Normal);
Mike Stump11289f42009-09-09 15:08:12 +000012418
John McCall2d74de92009-12-01 22:10:20 +000012419 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000012420 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCall2d74de92009-12-01 22:10:20 +000012421 if (UnresExpr->hasExplicitTemplateArgs()) {
12422 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12423 TemplateArgs = &TemplateArgsBuffer;
12424 }
12425
John McCall10eae182009-11-30 22:42:35 +000012426 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
12427 E = UnresExpr->decls_end(); I != E; ++I) {
12428
John McCall6e9f8f62009-12-03 04:06:58 +000012429 NamedDecl *Func = *I;
12430 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
12431 if (isa<UsingShadowDecl>(Func))
12432 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
12433
Douglas Gregor02824322011-01-26 19:30:28 +000012434
Francois Pichet64225792011-01-18 05:04:39 +000012435 // Microsoft supports direct constructor calls.
David Blaikiebbafb8a2012-03-11 07:00:24 +000012436 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012437 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012438 Args, CandidateSet);
Francois Pichet64225792011-01-18 05:04:39 +000012439 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +000012440 // If explicit template arguments were provided, we can't call a
12441 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +000012442 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +000012443 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012444
John McCalla0296f72010-03-19 07:35:19 +000012445 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012446 ObjectClassification, Args, CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +000012447 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000012448 } else {
John McCall10eae182009-11-30 22:42:35 +000012449 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +000012450 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012451 ObjectType, ObjectClassification,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012452 Args, CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000012453 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000012454 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000012455 }
Mike Stump11289f42009-09-09 15:08:12 +000012456
John McCall10eae182009-11-30 22:42:35 +000012457 DeclarationName DeclName = UnresExpr->getMemberName();
12458
John McCall4124c492011-10-17 18:40:02 +000012459 UnbridgedCasts.restore();
12460
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012461 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012462 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +000012463 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012464 case OR_Success:
12465 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +000012466 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +000012467 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000012468 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
12469 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000012470 // If FoundDecl is different from Method (such as if one is a template
12471 // and the other a specialization), make sure DiagnoseUseOfDecl is
12472 // called on both.
12473 // FIXME: This would be more comprehensively addressed by modifying
12474 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
12475 // being used.
12476 if (Method != FoundDecl.getDecl() &&
12477 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
12478 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012479 break;
12480
12481 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +000012482 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012483 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000012484 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012485 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012486 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000012487 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012488
12489 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +000012490 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000012491 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012492 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012493 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000012494 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000012495
12496 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +000012497 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +000012498 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012499 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012500 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012501 << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012502 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000012503 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000012504 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012505 }
12506
John McCall16df1e52010-03-30 21:47:33 +000012507 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +000012508
John McCall2d74de92009-12-01 22:10:20 +000012509 // If overload resolution picked a static member, build a
12510 // non-member call based on that function.
12511 if (Method->isStatic()) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012512 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
12513 RParenLoc);
John McCall2d74de92009-12-01 22:10:20 +000012514 }
12515
John McCall10eae182009-11-30 22:42:35 +000012516 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012517 }
12518
Alp Toker314cc812014-01-25 16:55:45 +000012519 QualType ResultType = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000012520 ExprValueKind VK = Expr::getValueKindForType(ResultType);
12521 ResultType = ResultType.getNonLValueExprType(Context);
12522
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012523 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012524 CXXMemberCallExpr *TheCall =
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012525 new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall7decc9e2010-11-18 06:31:45 +000012526 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012527
Anders Carlssonc4859ba2009-10-10 00:06:20 +000012528 // Check for a valid return type.
Alp Toker314cc812014-01-25 16:55:45 +000012529 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +000012530 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +000012531 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012532
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012533 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +000012534 // We only need to do this if there was actually an overload; otherwise
12535 // it was done at lookup.
John Wiegley01296292011-04-08 18:41:53 +000012536 if (!Method->isStatic()) {
12537 ExprResult ObjectArg =
12538 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
12539 FoundDecl, Method);
12540 if (ObjectArg.isInvalid())
12541 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012542 MemExpr->setBase(ObjectArg.get());
John Wiegley01296292011-04-08 18:41:53 +000012543 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012544
12545 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +000012546 const FunctionProtoType *Proto =
12547 Method->getType()->getAs<FunctionProtoType>();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012548 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012549 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +000012550 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012551
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012552 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000012553
Richard Smith55ce3522012-06-25 20:30:08 +000012554 if (CheckFunctionCall(Method, TheCall, Proto))
John McCall2d74de92009-12-01 22:10:20 +000012555 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +000012556
George Burgess IVaea6ade2015-09-25 17:53:16 +000012557 // In the case the method to call was not selected by the overloading
12558 // resolution process, we still need to handle the enable_if attribute. Do
George Burgess IV0d546532016-11-10 21:47:12 +000012559 // that here, so it will not hide previous -- and more relevant -- errors.
George Burgess IVadd6ab52016-11-16 21:31:25 +000012560 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
George Burgess IVaea6ade2015-09-25 17:53:16 +000012561 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
George Burgess IVadd6ab52016-11-16 21:31:25 +000012562 Diag(MemE->getMemberLoc(),
George Burgess IVaea6ade2015-09-25 17:53:16 +000012563 diag::err_ovl_no_viable_member_function_in_call)
12564 << Method << Method->getSourceRange();
12565 Diag(Method->getLocation(),
12566 diag::note_ovl_candidate_disabled_by_enable_if_attr)
12567 << Attr->getCond()->getSourceRange() << Attr->getMessage();
12568 return ExprError();
12569 }
12570 }
12571
Anders Carlsson47061ee2011-05-06 14:25:31 +000012572 if ((isa<CXXConstructorDecl>(CurContext) ||
12573 isa<CXXDestructorDecl>(CurContext)) &&
12574 TheCall->getMethodDecl()->isPure()) {
12575 const CXXMethodDecl *MD = TheCall->getMethodDecl();
12576
Davide Italianoccb37382015-07-14 23:36:10 +000012577 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
12578 MemExpr->performsVirtualDispatch(getLangOpts())) {
12579 Diag(MemExpr->getLocStart(),
Anders Carlsson47061ee2011-05-06 14:25:31 +000012580 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
12581 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
12582 << MD->getParent()->getDeclName();
12583
12584 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Davide Italianoccb37382015-07-14 23:36:10 +000012585 if (getLangOpts().AppleKext)
12586 Diag(MemExpr->getLocStart(),
12587 diag::note_pure_qualified_call_kext)
12588 << MD->getParent()->getDeclName()
12589 << MD->getDeclName();
Chandler Carruth59259262011-06-27 08:31:58 +000012590 }
Anders Carlsson47061ee2011-05-06 14:25:31 +000012591 }
Nico Weber5a9259c2016-01-15 21:45:31 +000012592
12593 if (CXXDestructorDecl *DD =
12594 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
12595 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
Justin Lebard35f7062016-07-12 23:23:01 +000012596 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
Nico Weber5a9259c2016-01-15 21:45:31 +000012597 CheckVirtualDtorCall(DD, MemExpr->getLocStart(), /*IsDelete=*/false,
12598 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
12599 MemExpr->getMemberLoc());
12600 }
12601
John McCallb268a282010-08-23 23:25:46 +000012602 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012603}
12604
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012605/// BuildCallToObjectOfClassType - Build a call to an object of class
12606/// type (C++ [over.call.object]), which can end up invoking an
12607/// overloaded function call operator (@c operator()) or performing a
12608/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +000012609ExprResult
John Wiegley01296292011-04-08 18:41:53 +000012610Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregorb0846b02008-12-06 00:22:45 +000012611 SourceLocation LParenLoc,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012612 MultiExprArg Args,
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012613 SourceLocation RParenLoc) {
John McCall4124c492011-10-17 18:40:02 +000012614 if (checkPlaceholderForOverload(*this, Obj))
12615 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012616 ExprResult Object = Obj;
John McCall4124c492011-10-17 18:40:02 +000012617
12618 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012619 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000012620 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012621
Nico Weberb58e51c2014-11-19 05:21:39 +000012622 assert(Object.get()->getType()->isRecordType() &&
12623 "Requires object type argument");
John Wiegley01296292011-04-08 18:41:53 +000012624 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +000012625
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012626 // C++ [over.call.object]p1:
12627 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +000012628 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012629 // candidate functions includes at least the function call
12630 // operators of T. The function call operators of T are obtained by
12631 // ordinary lookup of the name operator() in the context of
12632 // (E).operator().
Richard Smith100b24a2014-04-17 01:52:14 +000012633 OverloadCandidateSet CandidateSet(LParenLoc,
12634 OverloadCandidateSet::CSK_Operator);
Douglas Gregor91f84212008-12-11 16:49:14 +000012635 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +000012636
John Wiegley01296292011-04-08 18:41:53 +000012637 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012638 diag::err_incomplete_object_call, Object.get()))
Douglas Gregorc473cbb2009-11-15 07:48:03 +000012639 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012640
John McCall27b18f82009-11-17 02:14:36 +000012641 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
12642 LookupQualifiedName(R, Record->getDecl());
12643 R.suppressDiagnostics();
12644
Douglas Gregorc473cbb2009-11-15 07:48:03 +000012645 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +000012646 Oper != OperEnd; ++Oper) {
John Wiegley01296292011-04-08 18:41:53 +000012647 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012648 Object.get()->Classify(Context),
12649 Args, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +000012650 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +000012651 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012652
Douglas Gregorab7897a2008-11-19 22:57:39 +000012653 // C++ [over.call.object]p2:
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012654 // In addition, for each (non-explicit in C++0x) conversion function
12655 // declared in T of the form
Douglas Gregorab7897a2008-11-19 22:57:39 +000012656 //
12657 // operator conversion-type-id () cv-qualifier;
12658 //
12659 // where cv-qualifier is the same cv-qualification as, or a
12660 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +000012661 // denotes the type "pointer to function of (P1,...,Pn) returning
12662 // R", or the type "reference to pointer to function of
12663 // (P1,...,Pn) returning R", or the type "reference to function
12664 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +000012665 // is also considered as a candidate function. Similarly,
12666 // surrogate call functions are added to the set of candidate
12667 // functions for each conversion function declared in an
12668 // accessible base class provided the function is not hidden
12669 // within T by another intervening declaration.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +000012670 const auto &Conversions =
12671 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
12672 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +000012673 NamedDecl *D = *I;
12674 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
12675 if (isa<UsingShadowDecl>(D))
12676 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012677
Douglas Gregor74ba25c2009-10-21 06:18:39 +000012678 // Skip over templated conversion functions; they aren't
12679 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +000012680 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +000012681 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +000012682
John McCall6e9f8f62009-12-03 04:06:58 +000012683 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012684 if (!Conv->isExplicit()) {
12685 // Strip the reference type (if any) and then the pointer type (if
12686 // any) to get down to what might be a function type.
12687 QualType ConvType = Conv->getConversionType().getNonReferenceType();
12688 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
12689 ConvType = ConvPtrType->getPointeeType();
John McCalld14a8642009-11-21 08:51:07 +000012690
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012691 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
12692 {
12693 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012694 Object.get(), Args, CandidateSet);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012695 }
12696 }
Douglas Gregorab7897a2008-11-19 22:57:39 +000012697 }
Mike Stump11289f42009-09-09 15:08:12 +000012698
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012699 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12700
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012701 // Perform overload resolution.
12702 OverloadCandidateSet::iterator Best;
John Wiegley01296292011-04-08 18:41:53 +000012703 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall5c32be02010-08-24 20:38:10 +000012704 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012705 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +000012706 // Overload resolution succeeded; we'll build the appropriate call
12707 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012708 break;
12709
12710 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +000012711 if (CandidateSet.empty())
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012712 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley01296292011-04-08 18:41:53 +000012713 << Object.get()->getType() << /*call*/ 1
12714 << Object.get()->getSourceRange();
John McCall02374852010-01-07 02:04:15 +000012715 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012716 Diag(Object.get()->getLocStart(),
John McCall02374852010-01-07 02:04:15 +000012717 diag::err_ovl_no_viable_object_call)
John Wiegley01296292011-04-08 18:41:53 +000012718 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012719 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012720 break;
12721
12722 case OR_Ambiguous:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012723 Diag(Object.get()->getLocStart(),
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012724 diag::err_ovl_ambiguous_object_call)
John Wiegley01296292011-04-08 18:41:53 +000012725 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012726 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012727 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000012728
12729 case OR_Deleted:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012730 Diag(Object.get()->getLocStart(),
Douglas Gregor171c45a2009-02-18 21:56:37 +000012731 diag::err_ovl_deleted_object_call)
12732 << Best->Function->isDeleted()
John Wiegley01296292011-04-08 18:41:53 +000012733 << Object.get()->getType()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012734 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley01296292011-04-08 18:41:53 +000012735 << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012736 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000012737 break;
Mike Stump11289f42009-09-09 15:08:12 +000012738 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012739
Douglas Gregorb412e172010-07-25 18:17:45 +000012740 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012741 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012742
John McCall4124c492011-10-17 18:40:02 +000012743 UnbridgedCasts.restore();
12744
Craig Topperc3ec1492014-05-26 06:22:03 +000012745 if (Best->Function == nullptr) {
Douglas Gregorab7897a2008-11-19 22:57:39 +000012746 // Since there is no function declaration, this is one of the
12747 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +000012748 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +000012749 = cast<CXXConversionDecl>(
12750 Best->Conversions[0].UserDefined.ConversionFunction);
12751
Craig Topperc3ec1492014-05-26 06:22:03 +000012752 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
12753 Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000012754 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
12755 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000012756 assert(Conv == Best->FoundDecl.getDecl() &&
12757 "Found Decl & conversion-to-functionptr should be same, right?!");
Douglas Gregorab7897a2008-11-19 22:57:39 +000012758 // We selected one of the surrogate functions that converts the
12759 // object parameter to a function pointer. Perform the conversion
12760 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012761
Fariborz Jahanian774cf792009-09-28 18:35:46 +000012762 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +000012763 // and then call it.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012764 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
12765 Conv, HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +000012766 if (Call.isInvalid())
12767 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +000012768 // Record usage of conversion in an implicit cast.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012769 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
12770 CK_UserDefinedConversion, Call.get(),
12771 nullptr, VK_RValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012772
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012773 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +000012774 }
12775
Craig Topperc3ec1492014-05-26 06:22:03 +000012776 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
John McCall49ec2e62010-01-28 01:54:34 +000012777
Douglas Gregorab7897a2008-11-19 22:57:39 +000012778 // We found an overloaded operator(). Build a CXXOperatorCallExpr
12779 // that calls this method, using Object for the implicit object
12780 // parameter and passing along the remaining arguments.
12781 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Nico Weber1fefe412012-11-09 06:06:14 +000012782
12783 // An error diagnostic has already been printed when parsing the declaration.
Nico Weber9512d3f2012-11-09 08:38:04 +000012784 if (Method->isInvalidDecl())
Nico Weber1fefe412012-11-09 06:06:14 +000012785 return ExprError();
12786
Chandler Carruth8e543b32010-12-12 08:17:55 +000012787 const FunctionProtoType *Proto =
12788 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012789
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012790 unsigned NumParams = Proto->getNumParams();
Mike Stump11289f42009-09-09 15:08:12 +000012791
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012792 DeclarationNameInfo OpLocInfo(
12793 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
12794 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Nick Lewycky134af912013-02-07 05:08:22 +000012795 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012796 HadMultipleCandidates,
12797 OpLocInfo.getLoc(),
12798 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000012799 if (NewFn.isInvalid())
12800 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012801
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012802 // Build the full argument list for the method call (the implicit object
12803 // parameter is placed at the beginning of the list).
George Burgess IV215f6e72016-12-13 19:22:56 +000012804 SmallVector<Expr *, 8> MethodArgs(Args.size() + 1);
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012805 MethodArgs[0] = Object.get();
George Burgess IV215f6e72016-12-13 19:22:56 +000012806 std::copy(Args.begin(), Args.end(), MethodArgs.begin() + 1);
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012807
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012808 // Once we've built TheCall, all of the expressions are properly
12809 // owned.
Alp Toker314cc812014-01-25 16:55:45 +000012810 QualType ResultTy = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000012811 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12812 ResultTy = ResultTy.getNonLValueExprType(Context);
12813
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012814 CXXOperatorCallExpr *TheCall = new (Context)
George Burgess IV215f6e72016-12-13 19:22:56 +000012815 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(), MethodArgs, ResultTy,
12816 VK, RParenLoc, false);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012817
Alp Toker314cc812014-01-25 16:55:45 +000012818 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
Anders Carlsson3d5829c2009-10-13 21:49:31 +000012819 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012820
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012821 // We may have default arguments. If so, we need to allocate more
12822 // slots in the call for them.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012823 if (Args.size() < NumParams)
12824 TheCall->setNumArgs(Context, NumParams + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012825
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000012826 bool IsError = false;
12827
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012828 // Initialize the implicit object parameter.
John Wiegley01296292011-04-08 18:41:53 +000012829 ExprResult ObjRes =
Craig Topperc3ec1492014-05-26 06:22:03 +000012830 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012831 Best->FoundDecl, Method);
12832 if (ObjRes.isInvalid())
12833 IsError = true;
12834 else
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012835 Object = ObjRes;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012836 TheCall->setArg(0, Object.get());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000012837
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012838 // Check the argument types.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012839 for (unsigned i = 0; i != NumParams; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012840 Expr *Arg;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012841 if (i < Args.size()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012842 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +000012843
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012844 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012845
John McCalldadc5752010-08-24 06:29:42 +000012846 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012847 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000012848 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012849 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +000012850 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012851
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012852 IsError |= InputInit.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012853 Arg = InputInit.getAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012854 } else {
John McCalldadc5752010-08-24 06:29:42 +000012855 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +000012856 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
12857 if (DefArg.isInvalid()) {
12858 IsError = true;
12859 break;
12860 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012861
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012862 Arg = DefArg.getAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012863 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012864
12865 TheCall->setArg(i + 1, Arg);
12866 }
12867
12868 // If this is a variadic call, handle args passed through "...".
12869 if (Proto->isVariadic()) {
12870 // Promote the arguments (C99 6.5.2.2p7).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012871 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
Craig Topperc3ec1492014-05-26 06:22:03 +000012872 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
12873 nullptr);
John Wiegley01296292011-04-08 18:41:53 +000012874 IsError |= Arg.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012875 TheCall->setArg(i + 1, Arg.get());
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012876 }
12877 }
12878
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000012879 if (IsError) return true;
12880
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012881 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000012882
Richard Smith55ce3522012-06-25 20:30:08 +000012883 if (CheckFunctionCall(Method, TheCall, Proto))
Anders Carlssonbc4c1072009-08-16 01:56:34 +000012884 return true;
12885
John McCalle172be52010-08-24 06:09:16 +000012886 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012887}
12888
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012889/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +000012890/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012891/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +000012892ExprResult
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000012893Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
12894 bool *NoArrowOperatorFound) {
Chandler Carruth8e543b32010-12-12 08:17:55 +000012895 assert(Base->getType()->isRecordType() &&
12896 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +000012897
John McCall4124c492011-10-17 18:40:02 +000012898 if (checkPlaceholderForOverload(*this, Base))
12899 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012900
John McCallbc077cf2010-02-08 23:07:23 +000012901 SourceLocation Loc = Base->getExprLoc();
12902
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012903 // C++ [over.ref]p1:
12904 //
12905 // [...] An expression x->m is interpreted as (x.operator->())->m
12906 // for a class object x of type T if T::operator->() exists and if
12907 // the operator is selected as the best match function by the
12908 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +000012909 DeclarationName OpName =
12910 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
Richard Smith100b24a2014-04-17 01:52:14 +000012911 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
Ted Kremenekc23c7e62009-07-29 21:53:49 +000012912 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +000012913
John McCallbc077cf2010-02-08 23:07:23 +000012914 if (RequireCompleteType(Loc, Base->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012915 diag::err_typecheck_incomplete_tag, Base))
Eli Friedman132e70b2009-11-18 01:28:03 +000012916 return ExprError();
12917
John McCall27b18f82009-11-17 02:14:36 +000012918 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
12919 LookupQualifiedName(R, BaseRecord->getDecl());
12920 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +000012921
12922 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +000012923 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +000012924 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +000012925 None, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +000012926 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012927
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012928 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12929
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012930 // Perform overload resolution.
12931 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012932 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012933 case OR_Success:
12934 // Overload resolution succeeded; we'll build the call below.
12935 break;
12936
12937 case OR_No_Viable_Function:
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012938 if (CandidateSet.empty()) {
12939 QualType BaseType = Base->getType();
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000012940 if (NoArrowOperatorFound) {
12941 // Report this specific error to the caller instead of emitting a
12942 // diagnostic, as requested.
12943 *NoArrowOperatorFound = true;
12944 return ExprError();
12945 }
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000012946 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
12947 << BaseType << Base->getSourceRange();
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012948 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000012949 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012950 << FixItHint::CreateReplacement(OpLoc, ".");
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012951 }
12952 } else
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012953 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +000012954 << "operator->" << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012955 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012956 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012957
12958 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000012959 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
12960 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012961 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012962 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000012963
12964 case OR_Deleted:
12965 Diag(OpLoc, diag::err_ovl_deleted_oper)
12966 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012967 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012968 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012969 << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012970 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012971 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012972 }
12973
Craig Topperc3ec1492014-05-26 06:22:03 +000012974 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
John McCalla0296f72010-03-19 07:35:19 +000012975
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012976 // Convert the object parameter.
12977 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000012978 ExprResult BaseResult =
Craig Topperc3ec1492014-05-26 06:22:03 +000012979 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012980 Best->FoundDecl, Method);
12981 if (BaseResult.isInvalid())
Douglas Gregord8061562009-08-06 03:17:00 +000012982 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012983 Base = BaseResult.get();
Douglas Gregor9ecea262008-11-21 03:04:22 +000012984
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012985 // Build the operator call.
Nick Lewycky134af912013-02-07 05:08:22 +000012986 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012987 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000012988 if (FnExpr.isInvalid())
12989 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012990
Alp Toker314cc812014-01-25 16:55:45 +000012991 QualType ResultTy = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000012992 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12993 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +000012994 CXXOperatorCallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012995 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
Lang Hames5de91cc2012-10-02 04:45:10 +000012996 Base, ResultTy, VK, OpLoc, false);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000012997
Alp Toker314cc812014-01-25 16:55:45 +000012998 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000012999 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +000013000
13001 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013002}
13003
Richard Smithbcc22fc2012-03-09 08:00:36 +000013004/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
13005/// a literal operator described by the provided lookup results.
13006ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
13007 DeclarationNameInfo &SuffixInfo,
13008 ArrayRef<Expr*> Args,
13009 SourceLocation LitEndLoc,
13010 TemplateArgumentListInfo *TemplateArgs) {
13011 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smithc67fdd42012-03-07 08:35:16 +000013012
Richard Smith100b24a2014-04-17 01:52:14 +000013013 OverloadCandidateSet CandidateSet(UDSuffixLoc,
13014 OverloadCandidateSet::CSK_Normal);
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000013015 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
13016 /*SuppressUserConversions=*/true);
Richard Smithc67fdd42012-03-07 08:35:16 +000013017
Richard Smithbcc22fc2012-03-09 08:00:36 +000013018 bool HadMultipleCandidates = (CandidateSet.size() > 1);
13019
Richard Smithbcc22fc2012-03-09 08:00:36 +000013020 // Perform overload resolution. This will usually be trivial, but might need
13021 // to perform substitutions for a literal operator template.
13022 OverloadCandidateSet::iterator Best;
13023 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
13024 case OR_Success:
13025 case OR_Deleted:
13026 break;
13027
13028 case OR_No_Viable_Function:
13029 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
13030 << R.getLookupName();
13031 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13032 return ExprError();
13033
13034 case OR_Ambiguous:
13035 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
13036 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
13037 return ExprError();
Richard Smithc67fdd42012-03-07 08:35:16 +000013038 }
13039
Richard Smithbcc22fc2012-03-09 08:00:36 +000013040 FunctionDecl *FD = Best->Function;
Nick Lewycky134af912013-02-07 05:08:22 +000013041 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
13042 HadMultipleCandidates,
Richard Smithbcc22fc2012-03-09 08:00:36 +000013043 SuffixInfo.getLoc(),
13044 SuffixInfo.getInfo());
13045 if (Fn.isInvalid())
13046 return true;
Richard Smithc67fdd42012-03-07 08:35:16 +000013047
13048 // Check the argument types. This should almost always be a no-op, except
13049 // that array-to-pointer decay is applied to string literals.
Richard Smithc67fdd42012-03-07 08:35:16 +000013050 Expr *ConvArgs[2];
Richard Smithe54c3072013-05-05 15:51:06 +000013051 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Richard Smithc67fdd42012-03-07 08:35:16 +000013052 ExprResult InputInit = PerformCopyInitialization(
13053 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
13054 SourceLocation(), Args[ArgIdx]);
13055 if (InputInit.isInvalid())
13056 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013057 ConvArgs[ArgIdx] = InputInit.get();
Richard Smithc67fdd42012-03-07 08:35:16 +000013058 }
13059
Alp Toker314cc812014-01-25 16:55:45 +000013060 QualType ResultTy = FD->getReturnType();
Richard Smithc67fdd42012-03-07 08:35:16 +000013061 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13062 ResultTy = ResultTy.getNonLValueExprType(Context);
13063
Richard Smithc67fdd42012-03-07 08:35:16 +000013064 UserDefinedLiteral *UDL =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013065 new (Context) UserDefinedLiteral(Context, Fn.get(),
Benjamin Kramerc215e762012-08-24 11:54:20 +000013066 llvm::makeArrayRef(ConvArgs, Args.size()),
Richard Smithc67fdd42012-03-07 08:35:16 +000013067 ResultTy, VK, LitEndLoc, UDSuffixLoc);
13068
Alp Toker314cc812014-01-25 16:55:45 +000013069 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
Richard Smithc67fdd42012-03-07 08:35:16 +000013070 return ExprError();
13071
Craig Topperc3ec1492014-05-26 06:22:03 +000013072 if (CheckFunctionCall(FD, UDL, nullptr))
Richard Smithc67fdd42012-03-07 08:35:16 +000013073 return ExprError();
13074
13075 return MaybeBindToTemporary(UDL);
13076}
13077
Sam Panzer0f384432012-08-21 00:52:01 +000013078/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
13079/// given LookupResult is non-empty, it is assumed to describe a member which
13080/// will be invoked. Otherwise, the function will be found via argument
13081/// dependent lookup.
13082/// CallExpr is set to a valid expression and FRS_Success returned on success,
13083/// otherwise CallExpr is set to ExprError() and some non-success value
13084/// is returned.
13085Sema::ForRangeStatus
Richard Smith9f690bd2015-10-27 06:02:45 +000013086Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
13087 SourceLocation RangeLoc,
Sam Panzer0f384432012-08-21 00:52:01 +000013088 const DeclarationNameInfo &NameInfo,
13089 LookupResult &MemberLookup,
13090 OverloadCandidateSet *CandidateSet,
13091 Expr *Range, ExprResult *CallExpr) {
Richard Smith9f690bd2015-10-27 06:02:45 +000013092 Scope *S = nullptr;
13093
Sam Panzer0f384432012-08-21 00:52:01 +000013094 CandidateSet->clear();
13095 if (!MemberLookup.empty()) {
13096 ExprResult MemberRef =
13097 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
13098 /*IsPtr=*/false, CXXScopeSpec(),
13099 /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +000013100 /*FirstQualifierInScope=*/nullptr,
Sam Panzer0f384432012-08-21 00:52:01 +000013101 MemberLookup,
Aaron Ballman6924dcd2015-09-01 14:49:24 +000013102 /*TemplateArgs=*/nullptr, S);
Sam Panzer0f384432012-08-21 00:52:01 +000013103 if (MemberRef.isInvalid()) {
13104 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000013105 return FRS_DiagnosticIssued;
13106 }
Craig Topperc3ec1492014-05-26 06:22:03 +000013107 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
Sam Panzer0f384432012-08-21 00:52:01 +000013108 if (CallExpr->isInvalid()) {
13109 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000013110 return FRS_DiagnosticIssued;
13111 }
13112 } else {
13113 UnresolvedSet<0> FoundNames;
Sam Panzer0f384432012-08-21 00:52:01 +000013114 UnresolvedLookupExpr *Fn =
Craig Topperc3ec1492014-05-26 06:22:03 +000013115 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
Sam Panzer0f384432012-08-21 00:52:01 +000013116 NestedNameSpecifierLoc(), NameInfo,
13117 /*NeedsADL=*/true, /*Overloaded=*/false,
Richard Smithb6626742012-10-18 17:56:02 +000013118 FoundNames.begin(), FoundNames.end());
Sam Panzer0f384432012-08-21 00:52:01 +000013119
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000013120 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
Sam Panzer0f384432012-08-21 00:52:01 +000013121 CandidateSet, CallExpr);
13122 if (CandidateSet->empty() || CandidateSetError) {
13123 *CallExpr = ExprError();
13124 return FRS_NoViableFunction;
13125 }
13126 OverloadCandidateSet::iterator Best;
13127 OverloadingResult OverloadResult =
13128 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
13129
13130 if (OverloadResult == OR_No_Viable_Function) {
13131 *CallExpr = ExprError();
13132 return FRS_NoViableFunction;
13133 }
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000013134 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
Craig Topperc3ec1492014-05-26 06:22:03 +000013135 Loc, nullptr, CandidateSet, &Best,
Sam Panzer0f384432012-08-21 00:52:01 +000013136 OverloadResult,
13137 /*AllowTypoCorrection=*/false);
13138 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
13139 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000013140 return FRS_DiagnosticIssued;
13141 }
13142 }
13143 return FRS_Success;
13144}
13145
13146
Douglas Gregorcd695e52008-11-10 20:40:00 +000013147/// FixOverloadedFunctionReference - E is an expression that refers to
13148/// a C++ overloaded function (possibly with some parentheses and
13149/// perhaps a '&' around it). We have resolved the overloaded function
13150/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +000013151/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +000013152Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +000013153 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +000013154 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000013155 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
13156 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000013157 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000013158 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013159
Douglas Gregor51c538b2009-11-20 19:42:02 +000013160 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013161 }
13162
Douglas Gregor51c538b2009-11-20 19:42:02 +000013163 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000013164 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
13165 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013166 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +000013167 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +000013168 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +000013169 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +000013170 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000013171 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013172
13173 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +000013174 ICE->getCastKind(),
Craig Topperc3ec1492014-05-26 06:22:03 +000013175 SubExpr, nullptr,
John McCall2536c6d2010-08-25 10:28:54 +000013176 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013177 }
13178
Aaron Ballmanff7bd8b2016-09-02 13:45:40 +000013179 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
13180 if (!GSE->isResultDependent()) {
13181 Expr *SubExpr =
13182 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
13183 if (SubExpr == GSE->getResultExpr())
13184 return GSE;
13185
13186 // Replace the resulting type information before rebuilding the generic
13187 // selection expression.
Aaron Ballman8b871d92016-09-02 18:31:31 +000013188 ArrayRef<Expr *> A = GSE->getAssocExprs();
13189 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
Aaron Ballmanff7bd8b2016-09-02 13:45:40 +000013190 unsigned ResultIdx = GSE->getResultIndex();
13191 AssocExprs[ResultIdx] = SubExpr;
13192
13193 return new (Context) GenericSelectionExpr(
13194 Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
13195 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
13196 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
13197 ResultIdx);
13198 }
13199 // Rather than fall through to the unreachable, return the original generic
13200 // selection expression.
13201 return GSE;
13202 }
13203
Douglas Gregor51c538b2009-11-20 19:42:02 +000013204 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +000013205 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +000013206 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +000013207 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13208 if (Method->isStatic()) {
13209 // Do nothing: static member functions aren't any different
13210 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +000013211 } else {
Alp Toker028ed912013-12-06 17:56:43 +000013212 // Fix the subexpression, which really has to be an
John McCalle66edc12009-11-24 19:00:30 +000013213 // UnresolvedLookupExpr holding an overloaded member function
13214 // or template.
John McCall16df1e52010-03-30 21:47:33 +000013215 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13216 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +000013217 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000013218 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +000013219
John McCalld14a8642009-11-21 08:51:07 +000013220 assert(isa<DeclRefExpr>(SubExpr)
13221 && "fixed to something other than a decl ref");
13222 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
13223 && "fixed to a member ref with no nested name qualifier");
13224
13225 // We have taken the address of a pointer to member
13226 // function. Perform the computation here so that we get the
13227 // appropriate pointer to member type.
13228 QualType ClassType
13229 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
13230 QualType MemPtrType
13231 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
David Majnemer02d57cc2016-06-30 03:02:03 +000013232 // Under the MS ABI, lock down the inheritance model now.
13233 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13234 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
John McCalld14a8642009-11-21 08:51:07 +000013235
John McCall7decc9e2010-11-18 06:31:45 +000013236 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
13237 VK_RValue, OK_Ordinary,
13238 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +000013239 }
13240 }
John McCall16df1e52010-03-30 21:47:33 +000013241 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13242 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000013243 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000013244 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013245
John McCalle3027922010-08-25 11:45:40 +000013246 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +000013247 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +000013248 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +000013249 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013250 }
John McCalld14a8642009-11-21 08:51:07 +000013251
Richard Smith84a0b6d2016-10-18 23:39:12 +000013252 // C++ [except.spec]p17:
13253 // An exception-specification is considered to be needed when:
13254 // - in an expression the function is the unique lookup result or the
13255 // selected member of a set of overloaded functions
13256 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13257 ResolveExceptionSpec(E->getExprLoc(), FPT);
13258
John McCalld14a8642009-11-21 08:51:07 +000013259 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +000013260 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000013261 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCalle66edc12009-11-24 19:00:30 +000013262 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +000013263 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
13264 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +000013265 }
13266
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013267 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13268 ULE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000013269 ULE->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013270 Fn,
John McCall113bee02012-03-10 09:33:50 +000013271 /*enclosing*/ false, // FIXME?
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013272 ULE->getNameLoc(),
13273 Fn->getType(),
13274 VK_LValue,
13275 Found.getDecl(),
13276 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000013277 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013278 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
13279 return DRE;
John McCalld14a8642009-11-21 08:51:07 +000013280 }
13281
John McCall10eae182009-11-30 22:42:35 +000013282 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +000013283 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000013284 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCall2d74de92009-12-01 22:10:20 +000013285 if (MemExpr->hasExplicitTemplateArgs()) {
13286 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
13287 TemplateArgs = &TemplateArgsBuffer;
13288 }
John McCall6b51f282009-11-23 01:53:49 +000013289
John McCall2d74de92009-12-01 22:10:20 +000013290 Expr *Base;
13291
John McCall7decc9e2010-11-18 06:31:45 +000013292 // If we're filling in a static method where we used to have an
13293 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +000013294 if (MemExpr->isImplicitAccess()) {
13295 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013296 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13297 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000013298 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013299 Fn,
John McCall113bee02012-03-10 09:33:50 +000013300 /*enclosing*/ false,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013301 MemExpr->getMemberLoc(),
13302 Fn->getType(),
13303 VK_LValue,
13304 Found.getDecl(),
13305 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000013306 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013307 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
13308 return DRE;
Douglas Gregorb15af892010-01-07 23:12:05 +000013309 } else {
13310 SourceLocation Loc = MemExpr->getMemberLoc();
13311 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +000013312 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman73a04092012-01-07 04:59:52 +000013313 CheckCXXThisCapture(Loc);
Douglas Gregorb15af892010-01-07 23:12:05 +000013314 Base = new (Context) CXXThisExpr(Loc,
13315 MemExpr->getBaseType(),
13316 /*isImplicit=*/true);
13317 }
John McCall2d74de92009-12-01 22:10:20 +000013318 } else
John McCallc3007a22010-10-26 07:05:15 +000013319 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +000013320
John McCall4adb38c2011-04-27 00:36:17 +000013321 ExprValueKind valueKind;
13322 QualType type;
13323 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13324 valueKind = VK_LValue;
13325 type = Fn->getType();
13326 } else {
13327 valueKind = VK_RValue;
Yunzhong Gaoeba323a2015-05-01 02:04:32 +000013328 type = Context.BoundMemberTy;
13329 }
13330
13331 MemberExpr *ME = MemberExpr::Create(
13332 Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
13333 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
13334 MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
13335 OK_Ordinary);
13336 ME->setHadMultipleCandidates(true);
13337 MarkMemberReferenced(ME);
13338 return ME;
Douglas Gregor51c538b2009-11-20 19:42:02 +000013339 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013340
John McCallc3007a22010-10-26 07:05:15 +000013341 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregorcd695e52008-11-10 20:40:00 +000013342}
13343
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013344ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +000013345 DeclAccessPair Found,
13346 FunctionDecl *Fn) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000013347 return FixOverloadedFunctionReference(E.get(), Found, Fn);
Douglas Gregor3e1e5272009-12-09 23:02:17 +000013348}