blob: 2e567863261c9b9f1a256c88d65e43140081303e [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);
332 if (Initializer &&
333 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
334 // Convert the integer to the floating type.
335 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
336 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
337 llvm::APFloat::rmNearestTiesToEven);
338 // And back.
339 llvm::APSInt ConvertedValue = IntConstantValue;
340 bool ignored;
341 Result.convertToInteger(ConvertedValue,
342 llvm::APFloat::rmTowardZero, &ignored);
343 // If the resulting value is different, this was a narrowing conversion.
344 if (IntConstantValue != ConvertedValue) {
345 ConstantValue = APValue(IntConstantValue);
Richard Smith5614ca72012-03-23 23:55:39 +0000346 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000347 return NK_Constant_Narrowing;
348 }
349 } else {
350 // Variables are always narrowings.
351 return NK_Variable_Narrowing;
352 }
353 }
354 return NK_Not_Narrowing;
355
356 // -- from long double to double or float, or from double to float, except
357 // where the source is a constant expression and the actual value after
358 // conversion is within the range of values that can be represented (even
359 // if it cannot be represented exactly), or
360 case ICK_Floating_Conversion:
361 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
362 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
363 // FromType is larger than ToType.
364 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
365 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
366 // Constant!
367 assert(ConstantValue.isFloat());
368 llvm::APFloat FloatVal = ConstantValue.getFloat();
369 // Convert the source value into the target type.
370 bool ignored;
371 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
372 Ctx.getFloatTypeSemantics(ToType),
373 llvm::APFloat::rmNearestTiesToEven, &ignored);
374 // If there was no overflow, the source value is within the range of
375 // values that can be represented.
Richard Smith5614ca72012-03-23 23:55:39 +0000376 if (ConvertStatus & llvm::APFloat::opOverflow) {
377 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000378 return NK_Constant_Narrowing;
Richard Smith5614ca72012-03-23 23:55:39 +0000379 }
Richard Smith66e05fe2012-01-18 05:21:49 +0000380 } else {
381 return NK_Variable_Narrowing;
382 }
383 }
384 return NK_Not_Narrowing;
385
386 // -- from an integer type or unscoped enumeration type to an integer type
387 // that cannot represent all the values of the original type, except where
388 // the source is a constant expression and the actual value after
389 // conversion will fit into the target type and will produce the original
390 // value when converted back to the original type.
Richard Smith64ecacf2015-02-19 00:39:05 +0000391 case ICK_Integral_Conversion:
392 IntegralConversion: {
Richard Smith66e05fe2012-01-18 05:21:49 +0000393 assert(FromType->isIntegralOrUnscopedEnumerationType());
394 assert(ToType->isIntegralOrUnscopedEnumerationType());
395 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
396 const unsigned FromWidth = Ctx.getIntWidth(FromType);
397 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
398 const unsigned ToWidth = Ctx.getIntWidth(ToType);
399
400 if (FromWidth > ToWidth ||
Richard Smith25a80d42012-06-13 01:07:41 +0000401 (FromWidth == ToWidth && FromSigned != ToSigned) ||
402 (FromSigned && !ToSigned)) {
Richard Smith66e05fe2012-01-18 05:21:49 +0000403 // Not all values of FromType can be represented in ToType.
404 llvm::APSInt InitializerValue;
405 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
Richard Smith25a80d42012-06-13 01:07:41 +0000406 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
407 // Such conversions on variables are always narrowing.
408 return NK_Variable_Narrowing;
Richard Smith72cd8ea2012-06-19 21:28:35 +0000409 }
410 bool Narrowing = false;
411 if (FromWidth < ToWidth) {
Richard Smith25a80d42012-06-13 01:07:41 +0000412 // Negative -> unsigned is narrowing. Otherwise, more bits is never
413 // narrowing.
414 if (InitializerValue.isSigned() && InitializerValue.isNegative())
Richard Smith72cd8ea2012-06-19 21:28:35 +0000415 Narrowing = true;
Richard Smith25a80d42012-06-13 01:07:41 +0000416 } else {
Richard Smith66e05fe2012-01-18 05:21:49 +0000417 // Add a bit to the InitializerValue so we don't have to worry about
418 // signed vs. unsigned comparisons.
419 InitializerValue = InitializerValue.extend(
420 InitializerValue.getBitWidth() + 1);
421 // Convert the initializer to and from the target width and signed-ness.
422 llvm::APSInt ConvertedValue = InitializerValue;
423 ConvertedValue = ConvertedValue.trunc(ToWidth);
424 ConvertedValue.setIsSigned(ToSigned);
425 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
426 ConvertedValue.setIsSigned(InitializerValue.isSigned());
427 // If the result is different, this was a narrowing conversion.
Richard Smith72cd8ea2012-06-19 21:28:35 +0000428 if (ConvertedValue != InitializerValue)
429 Narrowing = true;
430 }
431 if (Narrowing) {
432 ConstantType = Initializer->getType();
433 ConstantValue = APValue(InitializerValue);
434 return NK_Constant_Narrowing;
Richard Smith66e05fe2012-01-18 05:21:49 +0000435 }
436 }
437 return NK_Not_Narrowing;
438 }
439
440 default:
441 // Other kinds of conversions are not narrowings.
442 return NK_Not_Narrowing;
443 }
444}
445
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000446/// dump - Print this standard conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000447/// error. Useful for debugging overloading issues.
Yaron Kerencdae9412016-01-29 19:38:18 +0000448LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000449 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000450 bool PrintedSomething = false;
451 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000452 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000453 PrintedSomething = true;
454 }
455
456 if (Second != ICK_Identity) {
457 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000458 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000459 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000460 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000461
462 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000463 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000464 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000465 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000466 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000467 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000468 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000469 PrintedSomething = true;
470 }
471
472 if (Third != ICK_Identity) {
473 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000474 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000475 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000476 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000477 PrintedSomething = true;
478 }
479
480 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000481 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000482 }
483}
484
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000485/// dump - Print this user-defined conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000486/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000487void UserDefinedConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000488 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000489 if (Before.First || Before.Second || Before.Third) {
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000490 Before.dump();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000491 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000492 }
Sebastian Redl72ef7bc2011-11-01 15:53:09 +0000493 if (ConversionFunction)
494 OS << '\'' << *ConversionFunction << '\'';
495 else
496 OS << "aggregate initialization";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000497 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000498 OS << " -> ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000499 After.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000500 }
501}
502
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000503/// dump - Print this implicit conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000504/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000505void ImplicitConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000506 raw_ostream &OS = llvm::errs();
Richard Smitha93f1022013-09-06 22:30:28 +0000507 if (isStdInitializerListElement())
508 OS << "Worst std::initializer_list element conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000509 switch (ConversionKind) {
510 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000511 OS << "Standard conversion: ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000512 Standard.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000513 break;
514 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000515 OS << "User-defined conversion: ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000516 UserDefined.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000517 break;
518 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000519 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000520 break;
John McCall0d1da222010-01-12 00:44:57 +0000521 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000522 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000523 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000524 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000525 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000526 break;
527 }
528
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000529 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000530}
531
John McCall0d1da222010-01-12 00:44:57 +0000532void AmbiguousConversionSequence::construct() {
533 new (&conversions()) ConversionSet();
534}
535
536void AmbiguousConversionSequence::destruct() {
537 conversions().~ConversionSet();
538}
539
540void
541AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
542 FromTypePtr = O.FromTypePtr;
543 ToTypePtr = O.ToTypePtr;
544 new (&conversions()) ConversionSet(O.conversions());
545}
546
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000547namespace {
Larisse Voufo98b20f12013-07-19 23:00:19 +0000548 // Structure used by DeductionFailureInfo to store
Richard Smith44ecdbd2013-01-31 05:19:49 +0000549 // template argument information.
550 struct DFIArguments {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000551 TemplateArgument FirstArg;
552 TemplateArgument SecondArg;
553 };
Larisse Voufo98b20f12013-07-19 23:00:19 +0000554 // Structure used by DeductionFailureInfo to store
Richard Smith44ecdbd2013-01-31 05:19:49 +0000555 // template parameter and template argument information.
556 struct DFIParamWithArguments : DFIArguments {
557 TemplateParameter Param;
558 };
Richard Smith9b534542015-12-31 02:02:54 +0000559 // Structure used by DeductionFailureInfo to store template argument
560 // information and the index of the problematic call argument.
561 struct DFIDeducedMismatchArgs : DFIArguments {
562 TemplateArgumentList *TemplateArgs;
563 unsigned CallArgIndex;
564 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000565}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000566
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000567/// \brief Convert from Sema's representation of template deduction information
568/// to the form used in overload-candidate information.
Richard Smith17c00b42014-11-12 01:24:00 +0000569DeductionFailureInfo
570clang::MakeDeductionFailureInfo(ASTContext &Context,
571 Sema::TemplateDeductionResult TDK,
572 TemplateDeductionInfo &Info) {
Larisse Voufo98b20f12013-07-19 23:00:19 +0000573 DeductionFailureInfo Result;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000574 Result.Result = static_cast<unsigned>(TDK);
Richard Smith9ca64612012-05-07 09:03:25 +0000575 Result.HasDiagnostic = false;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000576 switch (TDK) {
577 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000578 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000579 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000580 case Sema::TDK_TooManyArguments:
581 case Sema::TDK_TooFewArguments:
Richard Smith9b534542015-12-31 02:02:54 +0000582 case Sema::TDK_MiscellaneousDeductionFailure:
583 Result.Data = nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000584 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000585
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000586 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000587 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000588 Result.Data = Info.Param.getOpaqueValue();
589 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000590
Richard Smith9b534542015-12-31 02:02:54 +0000591 case Sema::TDK_DeducedMismatch: {
592 // FIXME: Should allocate from normal heap so that we can free this later.
593 auto *Saved = new (Context) DFIDeducedMismatchArgs;
594 Saved->FirstArg = Info.FirstArg;
595 Saved->SecondArg = Info.SecondArg;
596 Saved->TemplateArgs = Info.take();
597 Saved->CallArgIndex = Info.CallArgIndex;
598 Result.Data = Saved;
599 break;
600 }
601
Richard Smith44ecdbd2013-01-31 05:19:49 +0000602 case Sema::TDK_NonDeducedMismatch: {
603 // FIXME: Should allocate from normal heap so that we can free this later.
604 DFIArguments *Saved = new (Context) DFIArguments;
605 Saved->FirstArg = Info.FirstArg;
606 Saved->SecondArg = Info.SecondArg;
607 Result.Data = Saved;
608 break;
609 }
610
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000611 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000612 case Sema::TDK_Underqualified: {
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000613 // FIXME: Should allocate from normal heap so that we can free this later.
614 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000615 Saved->Param = Info.Param;
616 Saved->FirstArg = Info.FirstArg;
617 Saved->SecondArg = Info.SecondArg;
618 Result.Data = Saved;
619 break;
620 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000621
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000622 case Sema::TDK_SubstitutionFailure:
Douglas Gregord09efd42010-05-08 20:07:26 +0000623 Result.Data = Info.take();
Richard Smith9ca64612012-05-07 09:03:25 +0000624 if (Info.hasSFINAEDiagnostic()) {
625 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
626 SourceLocation(), PartialDiagnostic::NullDiagnostic());
627 Info.takeSFINAEDiagnostic(*Diag);
628 Result.HasDiagnostic = true;
629 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000630 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000631
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000632 case Sema::TDK_FailedOverloadResolution:
Richard Smith8c6eeb92013-01-31 04:03:12 +0000633 Result.Data = Info.Expression;
634 break;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000635 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000636
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000637 return Result;
638}
John McCall0d1da222010-01-12 00:44:57 +0000639
Larisse Voufo98b20f12013-07-19 23:00:19 +0000640void DeductionFailureInfo::Destroy() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000641 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
642 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000643 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000644 case Sema::TDK_InstantiationDepth:
645 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000646 case Sema::TDK_TooManyArguments:
647 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000648 case Sema::TDK_InvalidExplicitArguments:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000649 case Sema::TDK_FailedOverloadResolution:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000650 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000651
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000652 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000653 case Sema::TDK_Underqualified:
Richard Smith9b534542015-12-31 02:02:54 +0000654 case Sema::TDK_DeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000655 case Sema::TDK_NonDeducedMismatch:
Douglas Gregorb02d6b32010-05-08 20:20:05 +0000656 // FIXME: Destroy the data?
Craig Topperc3ec1492014-05-26 06:22:03 +0000657 Data = nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000658 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000659
660 case Sema::TDK_SubstitutionFailure:
Richard Smith9ca64612012-05-07 09:03:25 +0000661 // FIXME: Destroy the template argument list?
Craig Topperc3ec1492014-05-26 06:22:03 +0000662 Data = nullptr;
Richard Smith9ca64612012-05-07 09:03:25 +0000663 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
664 Diag->~PartialDiagnosticAt();
665 HasDiagnostic = false;
666 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000667 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000668
Douglas Gregor461761d2010-05-08 18:20:53 +0000669 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000670 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000671 break;
672 }
673}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000674
Larisse Voufo98b20f12013-07-19 23:00:19 +0000675PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
Richard Smith9ca64612012-05-07 09:03:25 +0000676 if (HasDiagnostic)
677 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
Craig Topperc3ec1492014-05-26 06:22:03 +0000678 return nullptr;
Richard Smith9ca64612012-05-07 09:03:25 +0000679}
680
Larisse Voufo98b20f12013-07-19 23:00:19 +0000681TemplateParameter DeductionFailureInfo::getTemplateParameter() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000682 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
683 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000684 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000685 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000686 case Sema::TDK_TooManyArguments:
687 case Sema::TDK_TooFewArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000688 case Sema::TDK_SubstitutionFailure:
Richard Smith9b534542015-12-31 02:02:54 +0000689 case Sema::TDK_DeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000690 case Sema::TDK_NonDeducedMismatch:
691 case Sema::TDK_FailedOverloadResolution:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000692 return TemplateParameter();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000693
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000694 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000695 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000696 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000697
698 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000699 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000700 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000701
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000702 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000703 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000704 break;
705 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000706
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000707 return TemplateParameter();
708}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000709
Larisse Voufo98b20f12013-07-19 23:00:19 +0000710TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
Douglas Gregord09efd42010-05-08 20:07:26 +0000711 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
Richard Smith44ecdbd2013-01-31 05:19:49 +0000712 case Sema::TDK_Success:
713 case Sema::TDK_Invalid:
714 case Sema::TDK_InstantiationDepth:
715 case Sema::TDK_TooManyArguments:
716 case Sema::TDK_TooFewArguments:
717 case Sema::TDK_Incomplete:
718 case Sema::TDK_InvalidExplicitArguments:
719 case Sema::TDK_Inconsistent:
720 case Sema::TDK_Underqualified:
721 case Sema::TDK_NonDeducedMismatch:
722 case Sema::TDK_FailedOverloadResolution:
Craig Topperc3ec1492014-05-26 06:22:03 +0000723 return nullptr;
Douglas Gregord09efd42010-05-08 20:07:26 +0000724
Richard Smith9b534542015-12-31 02:02:54 +0000725 case Sema::TDK_DeducedMismatch:
726 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
727
Richard Smith44ecdbd2013-01-31 05:19:49 +0000728 case Sema::TDK_SubstitutionFailure:
729 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000730
Richard Smith44ecdbd2013-01-31 05:19:49 +0000731 // Unhandled
732 case Sema::TDK_MiscellaneousDeductionFailure:
733 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000734 }
735
Craig Topperc3ec1492014-05-26 06:22:03 +0000736 return nullptr;
Douglas Gregord09efd42010-05-08 20:07:26 +0000737}
738
Larisse Voufo98b20f12013-07-19 23:00:19 +0000739const TemplateArgument *DeductionFailureInfo::getFirstArg() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000740 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
741 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000742 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000743 case Sema::TDK_InstantiationDepth:
744 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000745 case Sema::TDK_TooManyArguments:
746 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000747 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000748 case Sema::TDK_SubstitutionFailure:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000749 case Sema::TDK_FailedOverloadResolution:
Craig Topperc3ec1492014-05-26 06:22:03 +0000750 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000751
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000752 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000753 case Sema::TDK_Underqualified:
Richard Smith9b534542015-12-31 02:02:54 +0000754 case Sema::TDK_DeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000755 case Sema::TDK_NonDeducedMismatch:
756 return &static_cast<DFIArguments*>(Data)->FirstArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000757
Douglas Gregor461761d2010-05-08 18:20:53 +0000758 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000759 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000760 break;
761 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000762
Craig Topperc3ec1492014-05-26 06:22:03 +0000763 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000764}
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000765
Larisse Voufo98b20f12013-07-19 23:00:19 +0000766const TemplateArgument *DeductionFailureInfo::getSecondArg() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000767 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
768 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000769 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000770 case Sema::TDK_InstantiationDepth:
771 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000772 case Sema::TDK_TooManyArguments:
773 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000774 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000775 case Sema::TDK_SubstitutionFailure:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000776 case Sema::TDK_FailedOverloadResolution:
Craig Topperc3ec1492014-05-26 06:22:03 +0000777 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000778
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000779 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000780 case Sema::TDK_Underqualified:
Richard Smith9b534542015-12-31 02:02:54 +0000781 case Sema::TDK_DeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000782 case Sema::TDK_NonDeducedMismatch:
783 return &static_cast<DFIArguments*>(Data)->SecondArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000784
Douglas Gregor461761d2010-05-08 18:20:53 +0000785 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000786 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000787 break;
788 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000789
Craig Topperc3ec1492014-05-26 06:22:03 +0000790 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000791}
792
Larisse Voufo98b20f12013-07-19 23:00:19 +0000793Expr *DeductionFailureInfo::getExpr() {
Richard Smith8c6eeb92013-01-31 04:03:12 +0000794 if (static_cast<Sema::TemplateDeductionResult>(Result) ==
795 Sema::TDK_FailedOverloadResolution)
796 return static_cast<Expr*>(Data);
797
Craig Topperc3ec1492014-05-26 06:22:03 +0000798 return nullptr;
Richard Smith8c6eeb92013-01-31 04:03:12 +0000799}
800
Richard Smith9b534542015-12-31 02:02:54 +0000801llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
802 if (static_cast<Sema::TemplateDeductionResult>(Result) ==
803 Sema::TDK_DeducedMismatch)
804 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
805
806 return llvm::None;
807}
808
Benjamin Kramer97e59492012-10-09 15:52:25 +0000809void OverloadCandidateSet::destroyCandidates() {
Richard Smith0bf93aa2012-07-18 23:52:59 +0000810 for (iterator i = begin(), e = end(); i != e; ++i) {
Benjamin Kramer02b08432012-01-14 20:16:52 +0000811 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
812 i->Conversions[ii].~ImplicitConversionSequence();
Richard Smith0bf93aa2012-07-18 23:52:59 +0000813 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
814 i->DeductionFailure.Destroy();
815 }
Benjamin Kramer97e59492012-10-09 15:52:25 +0000816}
817
818void OverloadCandidateSet::clear() {
819 destroyCandidates();
Benjamin Kramer0b9c5092012-01-14 19:31:39 +0000820 NumInlineSequences = 0;
Benjamin Kramerfb761ff2012-01-14 16:31:55 +0000821 Candidates.clear();
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000822 Functions.clear();
823}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000824
John McCall4124c492011-10-17 18:40:02 +0000825namespace {
826 class UnbridgedCastsSet {
827 struct Entry {
828 Expr **Addr;
829 Expr *Saved;
830 };
831 SmallVector<Entry, 2> Entries;
832
833 public:
834 void save(Sema &S, Expr *&E) {
835 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
836 Entry entry = { &E, E };
837 Entries.push_back(entry);
838 E = S.stripARCUnbridgedCast(E);
839 }
840
841 void restore() {
842 for (SmallVectorImpl<Entry>::iterator
843 i = Entries.begin(), e = Entries.end(); i != e; ++i)
844 *i->Addr = i->Saved;
845 }
846 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000847}
John McCall4124c492011-10-17 18:40:02 +0000848
849/// checkPlaceholderForOverload - Do any interesting placeholder-like
850/// preprocessing on the given expression.
851///
852/// \param unbridgedCasts a collection to which to add unbridged casts;
853/// without this, they will be immediately diagnosed as errors
854///
855/// Return true on unrecoverable error.
Craig Topperc3ec1492014-05-26 06:22:03 +0000856static bool
857checkPlaceholderForOverload(Sema &S, Expr *&E,
858 UnbridgedCastsSet *unbridgedCasts = nullptr) {
John McCall4124c492011-10-17 18:40:02 +0000859 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
860 // We can't handle overloaded expressions here because overload
861 // resolution might reasonably tweak them.
862 if (placeholder->getKind() == BuiltinType::Overload) return false;
863
864 // If the context potentially accepts unbridged ARC casts, strip
865 // the unbridged cast and add it to the collection for later restoration.
866 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
867 unbridgedCasts) {
868 unbridgedCasts->save(S, E);
869 return false;
870 }
871
872 // Go ahead and check everything else.
873 ExprResult result = S.CheckPlaceholderExpr(E);
874 if (result.isInvalid())
875 return true;
876
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000877 E = result.get();
John McCall4124c492011-10-17 18:40:02 +0000878 return false;
879 }
880
881 // Nothing to do.
882 return false;
883}
884
885/// checkArgPlaceholdersForOverload - Check a set of call operands for
886/// placeholders.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000887static bool checkArgPlaceholdersForOverload(Sema &S,
888 MultiExprArg Args,
John McCall4124c492011-10-17 18:40:02 +0000889 UnbridgedCastsSet &unbridged) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000890 for (unsigned i = 0, e = Args.size(); i != e; ++i)
891 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
John McCall4124c492011-10-17 18:40:02 +0000892 return true;
893
894 return false;
895}
896
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000897// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000898// overload of the declarations in Old. This routine returns false if
899// New and Old cannot be overloaded, e.g., if New has the same
900// signature as some function in Old (C++ 1.3.10) or if the Old
901// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000902// it does return false, MatchedDecl will point to the decl that New
903// cannot be overloaded with. This decl may be a UsingShadowDecl on
904// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000905//
906// Example: Given the following input:
907//
908// void f(int, float); // #1
909// void f(int, int); // #2
910// int f(int, int); // #3
911//
912// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000913// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000914//
John McCall3d988d92009-12-02 08:47:38 +0000915// When we process #2, Old contains only the FunctionDecl for #1. By
916// comparing the parameter types, we see that #1 and #2 are overloaded
917// (since they have different signatures), so this routine returns
918// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000919//
John McCall3d988d92009-12-02 08:47:38 +0000920// When we process #3, Old is an overload set containing #1 and #2. We
921// compare the signatures of #3 to #1 (they're overloaded, so we do
922// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
923// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000924// signature), IsOverload returns false and MatchedDecl will be set to
925// point to the FunctionDecl for #2.
John McCalle9cccd82010-06-16 08:42:20 +0000926//
927// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
928// into a class by a using declaration. The rules for whether to hide
929// shadow declarations ignore some properties which otherwise figure
930// into a function template's signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000931Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000932Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
933 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000934 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000935 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000936 NamedDecl *OldD = *I;
937
938 bool OldIsUsingDecl = false;
939 if (isa<UsingShadowDecl>(OldD)) {
940 OldIsUsingDecl = true;
941
942 // We can always introduce two using declarations into the same
943 // context, even if they have identical signatures.
944 if (NewIsUsingDecl) continue;
945
946 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
947 }
948
Richard Smithf091e122015-09-15 01:28:55 +0000949 // A using-declaration does not conflict with another declaration
950 // if one of them is hidden.
951 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
952 continue;
953
John McCalle9cccd82010-06-16 08:42:20 +0000954 // If either declaration was introduced by a using declaration,
955 // we'll need to use slightly different rules for matching.
956 // Essentially, these rules are the normal rules, except that
957 // function templates hide function templates with different
958 // return types or template parameter lists.
959 bool UseMemberUsingDeclRules =
John McCallc70fca62013-04-03 21:19:47 +0000960 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
961 !New->getFriendObjectKind();
John McCalle9cccd82010-06-16 08:42:20 +0000962
Alp Tokera2794f92014-01-22 07:29:52 +0000963 if (FunctionDecl *OldF = OldD->getAsFunction()) {
John McCalle9cccd82010-06-16 08:42:20 +0000964 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
965 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
966 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
967 continue;
968 }
969
Alp Tokera2794f92014-01-22 07:29:52 +0000970 if (!isa<FunctionTemplateDecl>(OldD) &&
971 !shouldLinkPossiblyHiddenDecl(*I, New))
Rafael Espindola5bddd6a2013-04-15 12:49:13 +0000972 continue;
973
John McCalldaa3d6b2009-12-09 03:35:25 +0000974 Match = *I;
975 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000976 }
John McCalla8987a2942010-11-10 03:01:53 +0000977 } else if (isa<UsingDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +0000978 // We can overload with these, which can show up when doing
979 // redeclaration checks for UsingDecls.
980 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalla8987a2942010-11-10 03:01:53 +0000981 } else if (isa<TagDecl>(OldD)) {
982 // We can always overload with tags by hiding them.
John McCall84d87672009-12-10 09:41:52 +0000983 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
984 // Optimistically assume that an unresolved using decl will
985 // overload; if it doesn't, we'll have to diagnose during
986 // template instantiation.
987 } else {
John McCall1f82f242009-11-18 22:49:29 +0000988 // (C++ 13p1):
989 // Only function declarations can be overloaded; object and type
990 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000991 Match = *I;
992 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000993 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000994 }
John McCall1f82f242009-11-18 22:49:29 +0000995
John McCalldaa3d6b2009-12-09 03:35:25 +0000996 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000997}
998
Richard Smithac974a32013-06-30 09:48:50 +0000999bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
Justin Lebarba122ab2016-03-30 23:30:21 +00001000 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
Richard Smithac974a32013-06-30 09:48:50 +00001001 // C++ [basic.start.main]p2: This function shall not be overloaded.
1002 if (New->isMain())
Rafael Espindola576127d2012-12-28 14:21:58 +00001003 return false;
Rafael Espindola7cf35ef2013-01-12 01:47:40 +00001004
David Majnemerc729b0b2013-09-16 22:44:20 +00001005 // MSVCRT user defined entry points cannot be overloaded.
1006 if (New->isMSVCRTEntryPoint())
1007 return false;
1008
John McCall1f82f242009-11-18 22:49:29 +00001009 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1010 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1011
1012 // C++ [temp.fct]p2:
1013 // A function template can be overloaded with other function templates
1014 // and with normal (non-template) functions.
Craig Topperc3ec1492014-05-26 06:22:03 +00001015 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
John McCall1f82f242009-11-18 22:49:29 +00001016 return true;
1017
1018 // Is the function New an overload of the function Old?
Richard Smithac974a32013-06-30 09:48:50 +00001019 QualType OldQType = Context.getCanonicalType(Old->getType());
1020 QualType NewQType = Context.getCanonicalType(New->getType());
John McCall1f82f242009-11-18 22:49:29 +00001021
1022 // Compare the signatures (C++ 1.3.10) of the two functions to
1023 // determine whether they are overloads. If we find any mismatch
1024 // in the signature, they are overloads.
1025
1026 // If either of these functions is a K&R-style function (no
1027 // prototype), then we consider them to have matching signatures.
1028 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1029 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1030 return false;
1031
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001032 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1033 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
John McCall1f82f242009-11-18 22:49:29 +00001034
1035 // The signature of a function includes the types of its
1036 // parameters (C++ 1.3.10), which includes the presence or absence
1037 // of the ellipsis; see C++ DR 357).
1038 if (OldQType != NewQType &&
Alp Toker9cacbab2014-01-20 20:26:09 +00001039 (OldType->getNumParams() != NewType->getNumParams() ||
John McCall1f82f242009-11-18 22:49:29 +00001040 OldType->isVariadic() != NewType->isVariadic() ||
Alp Toker9cacbab2014-01-20 20:26:09 +00001041 !FunctionParamTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +00001042 return true;
1043
1044 // C++ [temp.over.link]p4:
1045 // The signature of a function template consists of its function
1046 // signature, its return type and its template parameter list. The names
1047 // of the template parameters are significant only for establishing the
1048 // relationship between the template parameters and the rest of the
1049 // signature.
1050 //
1051 // We check the return type and template parameter lists for function
1052 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +00001053 //
1054 // However, we don't consider either of these when deciding whether
1055 // a member introduced by a shadow declaration is hidden.
Justin Lebar39fd5292016-03-30 20:41:05 +00001056 if (!UseMemberUsingDeclRules && NewTemplate &&
Richard Smithac974a32013-06-30 09:48:50 +00001057 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1058 OldTemplate->getTemplateParameters(),
1059 false, TPL_TemplateMatch) ||
Alp Toker314cc812014-01-25 16:55:45 +00001060 OldType->getReturnType() != NewType->getReturnType()))
John McCall1f82f242009-11-18 22:49:29 +00001061 return true;
1062
1063 // If the function is a class member, its signature includes the
Douglas Gregorb2f8aa92011-01-26 17:47:49 +00001064 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall1f82f242009-11-18 22:49:29 +00001065 //
1066 // As part of this, also check whether one of the member functions
1067 // is static, in which case they are not overloads (C++
1068 // 13.1p2). While not part of the definition of the signature,
1069 // this check is important to determine whether these functions
1070 // can be overloaded.
Richard Smith574f4f62013-01-14 05:37:29 +00001071 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1072 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
John McCall1f82f242009-11-18 22:49:29 +00001073 if (OldMethod && NewMethod &&
Richard Smith574f4f62013-01-14 05:37:29 +00001074 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1075 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
Justin Lebar39fd5292016-03-30 20:41:05 +00001076 if (!UseMemberUsingDeclRules &&
Richard Smith574f4f62013-01-14 05:37:29 +00001077 (OldMethod->getRefQualifier() == RQ_None ||
1078 NewMethod->getRefQualifier() == RQ_None)) {
1079 // C++0x [over.load]p2:
1080 // - Member function declarations with the same name and the same
1081 // parameter-type-list as well as member function template
1082 // declarations with the same name, the same parameter-type-list, and
1083 // the same template parameter lists cannot be overloaded if any of
1084 // them, but not all, have a ref-qualifier (8.3.5).
Richard Smithac974a32013-06-30 09:48:50 +00001085 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
Richard Smith574f4f62013-01-14 05:37:29 +00001086 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
Richard Smithac974a32013-06-30 09:48:50 +00001087 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
Richard Smith574f4f62013-01-14 05:37:29 +00001088 }
1089 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001090 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001091
Richard Smith574f4f62013-01-14 05:37:29 +00001092 // We may not have applied the implicit const for a constexpr member
1093 // function yet (because we haven't yet resolved whether this is a static
1094 // or non-static member function). Add it now, on the assumption that this
1095 // is a redeclaration of OldMethod.
David Majnemer42350df2013-11-03 23:51:28 +00001096 unsigned OldQuals = OldMethod->getTypeQualifiers();
Richard Smith574f4f62013-01-14 05:37:29 +00001097 unsigned NewQuals = NewMethod->getTypeQualifiers();
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001098 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
Richard Smithe83b1d32013-06-25 18:46:26 +00001099 !isa<CXXConstructorDecl>(NewMethod))
Richard Smith574f4f62013-01-14 05:37:29 +00001100 NewQuals |= Qualifiers::Const;
David Majnemer42350df2013-11-03 23:51:28 +00001101
1102 // We do not allow overloading based off of '__restrict'.
1103 OldQuals &= ~Qualifiers::Restrict;
1104 NewQuals &= ~Qualifiers::Restrict;
1105 if (OldQuals != NewQuals)
Richard Smith574f4f62013-01-14 05:37:29 +00001106 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001107 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001108
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001109 // Though pass_object_size is placed on parameters and takes an argument, we
1110 // consider it to be a function-level modifier for the sake of function
1111 // identity. Either the function has one or more parameters with
1112 // pass_object_size or it doesn't.
1113 if (functionHasPassObjectSizeParams(New) !=
1114 functionHasPassObjectSizeParams(Old))
1115 return true;
1116
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001117 // enable_if attributes are an order-sensitive part of the signature.
1118 for (specific_attr_iterator<EnableIfAttr>
1119 NewI = New->specific_attr_begin<EnableIfAttr>(),
1120 NewE = New->specific_attr_end<EnableIfAttr>(),
1121 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1122 OldE = Old->specific_attr_end<EnableIfAttr>();
1123 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1124 if (NewI == NewE || OldI == OldE)
1125 return true;
1126 llvm::FoldingSetNodeID NewID, OldID;
1127 NewI->getCond()->Profile(NewID, Context, true);
1128 OldI->getCond()->Profile(OldID, Context, true);
Nick Lewyckyd950ae72014-01-21 01:30:30 +00001129 if (NewID != OldID)
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001130 return true;
1131 }
1132
Justin Lebarba122ab2016-03-30 23:30:21 +00001133 if (getLangOpts().CUDA && ConsiderCudaAttrs) {
Justin Lebare060feb2016-10-03 16:48:23 +00001134 // Don't allow overloading of destructors. (In theory we could, but it
1135 // would be a giant change to clang.)
1136 if (isa<CXXDestructorDecl>(New))
1137 return false;
1138
Artem Belevich94a55e82015-09-22 17:22:59 +00001139 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1140 OldTarget = IdentifyCUDATarget(Old);
1141 if (NewTarget == CFT_InvalidTarget || NewTarget == CFT_Global)
1142 return false;
1143
1144 assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target.");
1145
Justin Lebar53b000af2016-10-03 16:48:27 +00001146 // Don't allow HD and global functions to overload other functions with the
1147 // same signature. We allow overloading based on CUDA attributes so that
1148 // functions can have different implementations on the host and device, but
1149 // HD/global functions "exist" in some sense on both the host and device, so
1150 // should have the same implementation on both sides.
Artem Belevich1ef9b592016-02-24 21:54:45 +00001151 if ((NewTarget == CFT_HostDevice) || (OldTarget == CFT_HostDevice) ||
1152 (NewTarget == CFT_Global) || (OldTarget == CFT_Global))
Artem Belevich94a55e82015-09-22 17:22:59 +00001153 return false;
1154
Justin Lebar53b000af2016-10-03 16:48:27 +00001155 // Allow overloading of functions with same signature and different CUDA
1156 // target attributes.
Artem Belevich94a55e82015-09-22 17:22:59 +00001157 return NewTarget != OldTarget;
1158 }
1159
John McCall1f82f242009-11-18 22:49:29 +00001160 // The signatures match; this is not an overload.
1161 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001162}
1163
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00001164/// \brief Checks availability of the function depending on the current
1165/// function context. Inside an unavailable function, unavailability is ignored.
1166///
1167/// \returns true if \arg FD is unavailable and current context is inside
1168/// an available function, false otherwise.
1169bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
Duncan P. N. Exon Smith85363922016-03-08 10:28:52 +00001170 if (!FD->isUnavailable())
1171 return false;
1172
1173 // Walk up the context of the caller.
1174 Decl *C = cast<Decl>(CurContext);
1175 do {
1176 if (C->isUnavailable())
1177 return false;
1178 } while ((C = cast_or_null<Decl>(C->getDeclContext())));
1179 return true;
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00001180}
1181
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001182/// \brief Tries a user-defined conversion from From to ToType.
1183///
1184/// Produces an implicit conversion sequence for when a standard conversion
1185/// is not an option. See TryImplicitConversion for more information.
1186static ImplicitConversionSequence
1187TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1188 bool SuppressUserConversions,
1189 bool AllowExplicit,
1190 bool InOverloadResolution,
1191 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001192 bool AllowObjCWritebackConversion,
1193 bool AllowObjCConversionOnExplicit) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001194 ImplicitConversionSequence ICS;
1195
1196 if (SuppressUserConversions) {
1197 // We're not in the case above, so there is no conversion that
1198 // we can perform.
1199 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1200 return ICS;
1201 }
1202
1203 // Attempt user-defined conversion.
Richard Smith100b24a2014-04-17 01:52:14 +00001204 OverloadCandidateSet Conversions(From->getExprLoc(),
1205 OverloadCandidateSet::CSK_Normal);
Richard Smith48372b62015-01-27 03:30:40 +00001206 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1207 Conversions, AllowExplicit,
1208 AllowObjCConversionOnExplicit)) {
1209 case OR_Success:
1210 case OR_Deleted:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001211 ICS.setUserDefined();
1212 // C++ [over.ics.user]p4:
1213 // A conversion of an expression of class type to the same class
1214 // type is given Exact Match rank, and a conversion of an
1215 // expression of class type to a base class of that type is
1216 // given Conversion rank, in spite of the fact that a copy
1217 // constructor (i.e., a user-defined conversion function) is
1218 // called for those cases.
1219 if (CXXConstructorDecl *Constructor
1220 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1221 QualType FromCanon
1222 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1223 QualType ToCanon
1224 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1225 if (Constructor->isCopyConstructor() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00001226 (FromCanon == ToCanon ||
1227 S.IsDerivedFrom(From->getLocStart(), FromCanon, ToCanon))) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001228 // Turn this into a "standard" conversion sequence, so that it
1229 // gets ranked with standard conversion sequences.
Richard Smithc2bebe92016-05-11 20:37:46 +00001230 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001231 ICS.setStandard();
1232 ICS.Standard.setAsIdentityConversion();
1233 ICS.Standard.setFromType(From->getType());
1234 ICS.Standard.setAllToTypes(ToType);
1235 ICS.Standard.CopyConstructor = Constructor;
Richard Smithc2bebe92016-05-11 20:37:46 +00001236 ICS.Standard.FoundCopyConstructor = Found;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001237 if (ToCanon != FromCanon)
1238 ICS.Standard.Second = ICK_Derived_To_Base;
1239 }
1240 }
Richard Smith48372b62015-01-27 03:30:40 +00001241 break;
1242
1243 case OR_Ambiguous:
Richard Smith1bbaba82015-01-27 23:23:39 +00001244 ICS.setAmbiguous();
1245 ICS.Ambiguous.setFromType(From->getType());
1246 ICS.Ambiguous.setToType(ToType);
1247 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1248 Cand != Conversions.end(); ++Cand)
1249 if (Cand->Viable)
Richard Smithc2bebe92016-05-11 20:37:46 +00001250 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
Richard Smith1bbaba82015-01-27 23:23:39 +00001251 break;
Richard Smith48372b62015-01-27 03:30:40 +00001252
1253 // Fall through.
1254 case OR_No_Viable_Function:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001255 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Richard Smith48372b62015-01-27 03:30:40 +00001256 break;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001257 }
1258
1259 return ICS;
1260}
1261
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001262/// TryImplicitConversion - Attempt to perform an implicit conversion
1263/// from the given expression (Expr) to the given type (ToType). This
1264/// function returns an implicit conversion sequence that can be used
1265/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001266///
1267/// void f(float f);
1268/// void g(int i) { f(i); }
1269///
1270/// this routine would produce an implicit conversion sequence to
1271/// describe the initialization of f from i, which will be a standard
1272/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1273/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1274//
1275/// Note that this routine only determines how the conversion can be
1276/// performed; it does not actually perform the conversion. As such,
1277/// it will not produce any diagnostics if no conversion is available,
1278/// but will instead return an implicit conversion sequence of kind
1279/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +00001280///
1281/// If @p SuppressUserConversions, then user-defined conversions are
1282/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +00001283/// If @p AllowExplicit, then explicit user-defined conversions are
1284/// permitted.
John McCall31168b02011-06-15 23:02:42 +00001285///
1286/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1287/// writeback conversion, which allows __autoreleasing id* parameters to
1288/// be initialized with __strong id* or __weak id* arguments.
John McCall5c32be02010-08-24 20:38:10 +00001289static ImplicitConversionSequence
1290TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1291 bool SuppressUserConversions,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001292 bool AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001293 bool InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001294 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001295 bool AllowObjCWritebackConversion,
1296 bool AllowObjCConversionOnExplicit) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001297 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +00001298 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001299 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall0d1da222010-01-12 00:44:57 +00001300 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +00001301 return ICS;
1302 }
1303
David Blaikiebbafb8a2012-03-11 07:00:24 +00001304 if (!S.getLangOpts().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +00001305 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +00001306 return ICS;
1307 }
1308
Douglas Gregor836a7e82010-08-11 02:15:33 +00001309 // C++ [over.ics.user]p4:
1310 // A conversion of an expression of class type to the same class
1311 // type is given Exact Match rank, and a conversion of an
1312 // expression of class type to a base class of that type is
1313 // given Conversion rank, in spite of the fact that a copy/move
1314 // constructor (i.e., a user-defined conversion function) is
1315 // called for those cases.
1316 QualType FromType = From->getType();
1317 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00001318 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00001319 S.IsDerivedFrom(From->getLocStart(), FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001320 ICS.setStandard();
1321 ICS.Standard.setAsIdentityConversion();
1322 ICS.Standard.setFromType(FromType);
1323 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001324
Douglas Gregor5ab11652010-04-17 22:01:05 +00001325 // We don't actually check at this point whether there is a valid
1326 // copy/move constructor, since overloading just assumes that it
1327 // exists. When we actually perform initialization, we'll find the
1328 // appropriate constructor to copy the returned object, if needed.
Craig Topperc3ec1492014-05-26 06:22:03 +00001329 ICS.Standard.CopyConstructor = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001330
Douglas Gregor5ab11652010-04-17 22:01:05 +00001331 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +00001332 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +00001333 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001334
Douglas Gregor836a7e82010-08-11 02:15:33 +00001335 return ICS;
1336 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001337
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001338 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1339 AllowExplicit, InOverloadResolution, CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001340 AllowObjCWritebackConversion,
1341 AllowObjCConversionOnExplicit);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001342}
1343
John McCall31168b02011-06-15 23:02:42 +00001344ImplicitConversionSequence
1345Sema::TryImplicitConversion(Expr *From, QualType ToType,
1346 bool SuppressUserConversions,
1347 bool AllowExplicit,
1348 bool InOverloadResolution,
1349 bool CStyle,
1350 bool AllowObjCWritebackConversion) {
Richard Smith17c00b42014-11-12 01:24:00 +00001351 return ::TryImplicitConversion(*this, From, ToType,
1352 SuppressUserConversions, AllowExplicit,
1353 InOverloadResolution, CStyle,
1354 AllowObjCWritebackConversion,
1355 /*AllowObjCConversionOnExplicit=*/false);
John McCall5c32be02010-08-24 20:38:10 +00001356}
1357
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001358/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley01296292011-04-08 18:41:53 +00001359/// expression From to the type ToType. Returns the
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001360/// converted expression. Flavor is the kind of conversion we're
1361/// performing, used in the error message. If @p AllowExplicit,
1362/// explicit user-defined conversions are permitted.
John Wiegley01296292011-04-08 18:41:53 +00001363ExprResult
1364Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redlcc152642011-10-16 18:19:06 +00001365 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001366 ImplicitConversionSequence ICS;
Sebastian Redlcc152642011-10-16 18:19:06 +00001367 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001368}
1369
John Wiegley01296292011-04-08 18:41:53 +00001370ExprResult
1371Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001372 AssignmentAction Action, bool AllowExplicit,
Sebastian Redlcc152642011-10-16 18:19:06 +00001373 ImplicitConversionSequence& ICS) {
John McCall526ab472011-10-25 17:37:35 +00001374 if (checkPlaceholderForOverload(*this, From))
1375 return ExprError();
1376
John McCall31168b02011-06-15 23:02:42 +00001377 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1378 bool AllowObjCWritebackConversion
David Blaikiebbafb8a2012-03-11 07:00:24 +00001379 = getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001380 (Action == AA_Passing || Action == AA_Sending);
Fariborz Jahanian381edf52013-12-16 22:54:37 +00001381 if (getLangOpts().ObjC1)
1382 CheckObjCBridgeRelatedConversions(From->getLocStart(),
1383 ToType, From->getType(), From);
Richard Smith17c00b42014-11-12 01:24:00 +00001384 ICS = ::TryImplicitConversion(*this, From, ToType,
1385 /*SuppressUserConversions=*/false,
1386 AllowExplicit,
1387 /*InOverloadResolution=*/false,
1388 /*CStyle=*/false,
1389 AllowObjCWritebackConversion,
1390 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001391 return PerformImplicitConversion(From, ToType, ICS, Action);
1392}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001393
1394/// \brief Determine whether the conversion from FromType to ToType is a valid
Richard Smith3c4f8d22016-10-16 17:54:23 +00001395/// conversion that strips "noexcept" or "noreturn" off the nested function
1396/// type.
1397bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
Chandler Carruth53e61b02011-06-18 01:19:03 +00001398 QualType &ResultTy) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001399 if (Context.hasSameUnqualifiedType(FromType, ToType))
1400 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001401
John McCall991eb4b2010-12-21 00:44:39 +00001402 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
Richard Smith3c4f8d22016-10-16 17:54:23 +00001403 // or F(t noexcept) -> F(t)
John McCall991eb4b2010-12-21 00:44:39 +00001404 // where F adds one of the following at most once:
1405 // - a pointer
1406 // - a member pointer
1407 // - a block pointer
Richard Smitheb7ef2e2016-10-20 21:53:09 +00001408 // Changes here need matching changes in FindCompositePointerType.
John McCall991eb4b2010-12-21 00:44:39 +00001409 CanQualType CanTo = Context.getCanonicalType(ToType);
1410 CanQualType CanFrom = Context.getCanonicalType(FromType);
1411 Type::TypeClass TyClass = CanTo->getTypeClass();
1412 if (TyClass != CanFrom->getTypeClass()) return false;
1413 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1414 if (TyClass == Type::Pointer) {
1415 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1416 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1417 } else if (TyClass == Type::BlockPointer) {
1418 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1419 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1420 } else if (TyClass == Type::MemberPointer) {
Richard Smitheb7ef2e2016-10-20 21:53:09 +00001421 auto ToMPT = CanTo.getAs<MemberPointerType>();
1422 auto FromMPT = CanFrom.getAs<MemberPointerType>();
1423 // A function pointer conversion cannot change the class of the function.
1424 if (ToMPT->getClass() != FromMPT->getClass())
1425 return false;
1426 CanTo = ToMPT->getPointeeType();
1427 CanFrom = FromMPT->getPointeeType();
John McCall991eb4b2010-12-21 00:44:39 +00001428 } else {
1429 return false;
1430 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001431
John McCall991eb4b2010-12-21 00:44:39 +00001432 TyClass = CanTo->getTypeClass();
1433 if (TyClass != CanFrom->getTypeClass()) return false;
1434 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1435 return false;
1436 }
1437
Richard Smith3c4f8d22016-10-16 17:54:23 +00001438 const auto *FromFn = cast<FunctionType>(CanFrom);
1439 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
John McCall991eb4b2010-12-21 00:44:39 +00001440
Richard Smith6f427402016-10-20 00:01:36 +00001441 const auto *ToFn = cast<FunctionType>(CanTo);
Richard Smith3c4f8d22016-10-16 17:54:23 +00001442 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1443
1444 bool Changed = false;
1445
1446 // Drop 'noreturn' if not present in target type.
1447 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1448 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1449 Changed = true;
1450 }
1451
1452 // Drop 'noexcept' if not present in target type.
1453 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
Richard Smith6f427402016-10-20 00:01:36 +00001454 const auto *ToFPT = cast<FunctionProtoType>(ToFn);
Richard Smith3c4f8d22016-10-16 17:54:23 +00001455 if (FromFPT->isNothrow(Context) && !ToFPT->isNothrow(Context)) {
1456 FromFn = cast<FunctionType>(
1457 Context.getFunctionType(FromFPT->getReturnType(),
1458 FromFPT->getParamTypes(),
1459 FromFPT->getExtProtoInfo().withExceptionSpec(
1460 FunctionProtoType::ExceptionSpecInfo()))
1461 .getTypePtr());
1462 Changed = true;
1463 }
1464 }
1465
1466 if (!Changed)
1467 return false;
1468
John McCall991eb4b2010-12-21 00:44:39 +00001469 assert(QualType(FromFn, 0).isCanonical());
1470 if (QualType(FromFn, 0) != CanTo) return false;
1471
1472 ResultTy = ToType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001473 return true;
1474}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001475
Douglas Gregor46188682010-05-18 22:42:18 +00001476/// \brief Determine whether the conversion from FromType to ToType is a valid
1477/// vector conversion.
1478///
1479/// \param ICK Will be set to the vector conversion kind, if this is a vector
1480/// conversion.
John McCall9b595db2014-02-04 23:58:19 +00001481static bool IsVectorConversion(Sema &S, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001482 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregor46188682010-05-18 22:42:18 +00001483 // We need at least one of these types to be a vector type to have a vector
1484 // conversion.
1485 if (!ToType->isVectorType() && !FromType->isVectorType())
1486 return false;
1487
1488 // Identical types require no conversions.
John McCall9b595db2014-02-04 23:58:19 +00001489 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor46188682010-05-18 22:42:18 +00001490 return false;
1491
1492 // There are no conversions between extended vector types, only identity.
1493 if (ToType->isExtVectorType()) {
1494 // There are no conversions between extended vector types other than the
1495 // identity conversion.
1496 if (FromType->isExtVectorType())
1497 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001498
Douglas Gregor46188682010-05-18 22:42:18 +00001499 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +00001500 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +00001501 ICK = ICK_Vector_Splat;
1502 return true;
1503 }
1504 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001505
1506 // We can perform the conversion between vector types in the following cases:
1507 // 1)vector types are equivalent AltiVec and GCC vector types
1508 // 2)lax vector conversions are permitted and the vector types are of the
1509 // same size
1510 if (ToType->isVectorType() && FromType->isVectorType()) {
John McCall9b595db2014-02-04 23:58:19 +00001511 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1512 S.isLaxVectorConversion(FromType, ToType)) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001513 ICK = ICK_Vector_Conversion;
1514 return true;
1515 }
Douglas Gregor46188682010-05-18 22:42:18 +00001516 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001517
Douglas Gregor46188682010-05-18 22:42:18 +00001518 return false;
1519}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001520
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001521static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1522 bool InOverloadResolution,
1523 StandardConversionSequence &SCS,
1524 bool CStyle);
George Burgess IV45461812015-10-11 20:13:20 +00001525
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001526/// IsStandardConversion - Determines whether there is a standard
1527/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1528/// expression From to the type ToType. Standard conversion sequences
1529/// only consider non-class types; for conversions that involve class
1530/// types, use TryImplicitConversion. If a conversion exists, SCS will
1531/// contain the standard conversion sequence required to perform this
1532/// conversion and this routine will return true. Otherwise, this
1533/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +00001534static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1535 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +00001536 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +00001537 bool CStyle,
1538 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001539 QualType FromType = From->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001540
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001541 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +00001542 SCS.setAsIdentityConversion();
Douglas Gregor47d3f272008-12-19 17:40:08 +00001543 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +00001544 SCS.setFromType(FromType);
Craig Topperc3ec1492014-05-26 06:22:03 +00001545 SCS.CopyConstructor = nullptr;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001546
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001547 // There are no standard conversions for class types in C++, so
George Burgess IV45461812015-10-11 20:13:20 +00001548 // abort early. When overloading in C, however, we do permit them.
1549 if (S.getLangOpts().CPlusPlus &&
1550 (FromType->isRecordType() || ToType->isRecordType()))
1551 return false;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001552
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001553 // The first conversion can be an lvalue-to-rvalue conversion,
1554 // array-to-pointer conversion, or function-to-pointer conversion
1555 // (C++ 4p1).
1556
John McCall5c32be02010-08-24 20:38:10 +00001557 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001558 DeclAccessPair AccessPair;
1559 if (FunctionDecl *Fn
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001560 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall5c32be02010-08-24 20:38:10 +00001561 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001562 // We were able to resolve the address of the overloaded function,
1563 // so we can convert to the type of that function.
1564 FromType = Fn->getType();
Ehsan Akhgaric3ad3ba2014-07-22 20:20:14 +00001565 SCS.setFromType(FromType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00001566
1567 // we can sometimes resolve &foo<int> regardless of ToType, so check
1568 // if the type matches (identity) or we are converting to bool
1569 if (!S.Context.hasSameUnqualifiedType(
1570 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1571 QualType resultTy;
1572 // if the function type matches except for [[noreturn]], it's ok
Richard Smith3c4f8d22016-10-16 17:54:23 +00001573 if (!S.IsFunctionConversion(FromType,
Douglas Gregorb491ed32011-02-19 21:32:49 +00001574 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1575 // otherwise, only a boolean conversion is standard
1576 if (!ToType->isBooleanType())
1577 return false;
Douglas Gregor980fb162010-04-29 18:24:40 +00001578 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001579
Chandler Carruthffce2452011-03-29 08:08:18 +00001580 // Check if the "from" expression is taking the address of an overloaded
1581 // function and recompute the FromType accordingly. Take advantage of the
1582 // fact that non-static member functions *must* have such an address-of
1583 // expression.
1584 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1585 if (Method && !Method->isStatic()) {
1586 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1587 "Non-unary operator on non-static member address");
1588 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1589 == UO_AddrOf &&
1590 "Non-address-of operator on non-static member address");
1591 const Type *ClassType
1592 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1593 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruth7750f762011-03-29 18:38:10 +00001594 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1595 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1596 UO_AddrOf &&
Chandler Carruthffce2452011-03-29 08:08:18 +00001597 "Non-address-of operator for overloaded function expression");
1598 FromType = S.Context.getPointerType(FromType);
1599 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001600
Douglas Gregor980fb162010-04-29 18:24:40 +00001601 // Check that we've computed the proper type after overload resolution.
Richard Smith9095e5b2016-11-01 01:31:23 +00001602 // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't
1603 // be calling it from within an NDEBUG block.
Chandler Carruthffce2452011-03-29 08:08:18 +00001604 assert(S.Context.hasSameType(
1605 FromType,
1606 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001607 } else {
1608 return false;
1609 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001610 }
John McCall154a2fd2011-08-30 00:57:29 +00001611 // Lvalue-to-rvalue conversion (C++11 4.1):
1612 // A glvalue (3.10) of a non-function, non-array type T can
1613 // be converted to a prvalue.
1614 bool argIsLValue = From->isGLValue();
John McCall086a4642010-11-24 05:12:34 +00001615 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001616 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001617 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001618 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001619
Douglas Gregorc79862f2012-04-12 17:51:55 +00001620 // C11 6.3.2.1p2:
1621 // ... if the lvalue has atomic type, the value has the non-atomic version
1622 // of the type of the lvalue ...
1623 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1624 FromType = Atomic->getValueType();
1625
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001626 // If T is a non-class type, the type of the rvalue is the
1627 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001628 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1629 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001630 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001631 } else if (FromType->isArrayType()) {
1632 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001633 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001634
1635 // An lvalue or rvalue of type "array of N T" or "array of unknown
1636 // bound of T" can be converted to an rvalue of type "pointer to
1637 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001638 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001639
John McCall5c32be02010-08-24 20:38:10 +00001640 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00001641 // This conversion is deprecated in C++03 (D.4)
Douglas Gregore489a7d2010-02-28 18:30:25 +00001642 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001643
1644 // For the purpose of ranking in overload resolution
1645 // (13.3.3.1.1), this conversion is considered an
1646 // array-to-pointer conversion followed by a qualification
1647 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001648 SCS.Second = ICK_Identity;
1649 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001650 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001651 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001652 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001653 }
John McCall086a4642010-11-24 05:12:34 +00001654 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001655 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001656 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001657
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001658 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1659 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1660 if (!S.checkAddressOfFunctionIsAvailable(FD))
1661 return false;
1662
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001663 // An lvalue of function type T can be converted to an rvalue of
1664 // type "pointer to T." The result is a pointer to the
1665 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001666 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001667 } else {
1668 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001669 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001670 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001671 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001672
1673 // The second conversion can be an integral promotion, floating
1674 // point promotion, integral conversion, floating point conversion,
1675 // floating-integral conversion, pointer conversion,
1676 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001677 // For overloading in C, this can also be a "compatible-type"
1678 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001679 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001680 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001681 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001682 // The unqualified versions of the types are the same: there's no
1683 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001684 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001685 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001686 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001687 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001688 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001689 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001690 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001691 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001692 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001693 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001694 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001695 SCS.Second = ICK_Complex_Promotion;
1696 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001697 } else if (ToType->isBooleanType() &&
1698 (FromType->isArithmeticType() ||
1699 FromType->isAnyPointerType() ||
1700 FromType->isBlockPointerType() ||
1701 FromType->isMemberPointerType() ||
1702 FromType->isNullPtrType())) {
1703 // Boolean conversions (C++ 4.12).
1704 SCS.Second = ICK_Boolean_Conversion;
1705 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001706 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001707 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001708 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001709 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001710 FromType = ToType.getUnqualifiedType();
Richard Smithb8a98242013-05-10 20:29:50 +00001711 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001712 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001713 SCS.Second = ICK_Complex_Conversion;
1714 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001715 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1716 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001717 // Complex-real conversions (C99 6.3.1.7)
1718 SCS.Second = ICK_Complex_Real;
1719 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001720 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001721 // FIXME: disable conversions between long double and __float128 if
1722 // their representation is different until there is back end support
1723 // We of course allow this conversion if long double is really double.
1724 if (&S.Context.getFloatTypeSemantics(FromType) !=
1725 &S.Context.getFloatTypeSemantics(ToType)) {
1726 bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1727 ToType == S.Context.LongDoubleTy) ||
1728 (FromType == S.Context.LongDoubleTy &&
1729 ToType == S.Context.Float128Ty));
1730 if (Float128AndLongDouble &&
1731 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) !=
1732 &llvm::APFloat::IEEEdouble))
1733 return false;
1734 }
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001735 // Floating point conversions (C++ 4.8).
1736 SCS.Second = ICK_Floating_Conversion;
1737 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001738 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001739 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001740 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001741 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001742 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001743 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001744 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001745 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCall31168b02011-06-15 23:02:42 +00001746 SCS.Second = ICK_Block_Pointer_Conversion;
1747 } else if (AllowObjCWritebackConversion &&
1748 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1749 SCS.Second = ICK_Writeback_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001750 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1751 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001752 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001753 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001754 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregoraec25842011-04-26 23:16:46 +00001755 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001756 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall5c32be02010-08-24 20:38:10 +00001757 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001758 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001759 SCS.Second = ICK_Pointer_Member;
John McCall9b595db2014-02-04 23:58:19 +00001760 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001761 SCS.Second = SecondICK;
1762 FromType = ToType.getUnqualifiedType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001763 } else if (!S.getLangOpts().CPlusPlus &&
John McCall5c32be02010-08-24 20:38:10 +00001764 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001765 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001766 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001767 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001768 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1769 InOverloadResolution,
1770 SCS, CStyle)) {
1771 SCS.Second = ICK_TransparentUnionConversion;
1772 FromType = ToType;
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001773 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1774 CStyle)) {
1775 // tryAtomicConversion has updated the standard conversion sequence
Douglas Gregorc79862f2012-04-12 17:51:55 +00001776 // appropriately.
1777 return true;
George Burgess IV45461812015-10-11 20:13:20 +00001778 } else if (ToType->isEventT() &&
Guy Benyei259f9f42013-02-07 16:05:33 +00001779 From->isIntegerConstantExpr(S.getASTContext()) &&
George Burgess IV45461812015-10-11 20:13:20 +00001780 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
Guy Benyei259f9f42013-02-07 16:05:33 +00001781 SCS.Second = ICK_Zero_Event_Conversion;
1782 FromType = ToType;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001783 } else {
1784 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001785 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001786 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001787 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001788
Richard Smitheb7ef2e2016-10-20 21:53:09 +00001789 // The third conversion can be a function pointer conversion or a
1790 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
John McCall31168b02011-06-15 23:02:42 +00001791 bool ObjCLifetimeConversion;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00001792 if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1793 // Function pointer conversions (removing 'noexcept') including removal of
1794 // 'noreturn' (Clang extension).
1795 SCS.Third = ICK_Function_Conversion;
1796 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1797 ObjCLifetimeConversion)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001798 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001799 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001800 FromType = ToType;
1801 } else {
1802 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001803 SCS.Third = ICK_Identity;
Richard Smith9c37e662016-10-20 17:57:33 +00001804 }
Richard Smitheb7ef2e2016-10-20 21:53:09 +00001805
1806 // C++ [over.best.ics]p6:
1807 // [...] Any difference in top-level cv-qualification is
1808 // subsumed by the initialization itself and does not constitute
1809 // a conversion. [...]
1810 QualType CanonFrom = S.Context.getCanonicalType(FromType);
1811 QualType CanonTo = S.Context.getCanonicalType(ToType);
1812 if (CanonFrom.getLocalUnqualifiedType()
1813 == CanonTo.getLocalUnqualifiedType() &&
1814 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1815 FromType = ToType;
1816 CanonFrom = CanonTo;
1817 }
1818
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001819 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001820
George Burgess IV45461812015-10-11 20:13:20 +00001821 if (CanonFrom == CanonTo)
1822 return true;
1823
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001824 // If we have not converted the argument type to the parameter type,
George Burgess IV45461812015-10-11 20:13:20 +00001825 // this is a bad conversion sequence, unless we're resolving an overload in C.
1826 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001827 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001828
George Burgess IV45461812015-10-11 20:13:20 +00001829 ExprResult ER = ExprResult{From};
George Burgess IV2099b542016-09-02 22:59:57 +00001830 Sema::AssignConvertType Conv =
1831 S.CheckSingleAssignmentConstraints(ToType, ER,
1832 /*Diagnose=*/false,
1833 /*DiagnoseCFAudited=*/false,
1834 /*ConvertRHS=*/false);
George Burgess IV6098fd12016-09-03 00:28:25 +00001835 ImplicitConversionKind SecondConv;
George Burgess IV2099b542016-09-02 22:59:57 +00001836 switch (Conv) {
1837 case Sema::Compatible:
George Burgess IV6098fd12016-09-03 00:28:25 +00001838 SecondConv = ICK_C_Only_Conversion;
George Burgess IV2099b542016-09-02 22:59:57 +00001839 break;
1840 // For our purposes, discarding qualifiers is just as bad as using an
1841 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
1842 // qualifiers, as well.
1843 case Sema::CompatiblePointerDiscardsQualifiers:
1844 case Sema::IncompatiblePointer:
1845 case Sema::IncompatiblePointerSign:
George Burgess IV6098fd12016-09-03 00:28:25 +00001846 SecondConv = ICK_Incompatible_Pointer_Conversion;
George Burgess IV2099b542016-09-02 22:59:57 +00001847 break;
1848 default:
George Burgess IV45461812015-10-11 20:13:20 +00001849 return false;
George Burgess IV2099b542016-09-02 22:59:57 +00001850 }
George Burgess IV45461812015-10-11 20:13:20 +00001851
George Burgess IV6098fd12016-09-03 00:28:25 +00001852 // First can only be an lvalue conversion, so we pretend that this was the
1853 // second conversion. First should already be valid from earlier in the
1854 // function.
1855 SCS.Second = SecondConv;
1856 SCS.setToType(1, ToType);
1857
1858 // Third is Identity, because Second should rank us worse than any other
1859 // conversion. This could also be ICK_Qualification, but it's simpler to just
1860 // lump everything in with the second conversion, and we don't gain anything
1861 // from making this ICK_Qualification.
1862 SCS.Third = ICK_Identity;
1863 SCS.setToType(2, ToType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001864 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001865}
George Burgess IV2099b542016-09-02 22:59:57 +00001866
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001867static bool
1868IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1869 QualType &ToType,
1870 bool InOverloadResolution,
1871 StandardConversionSequence &SCS,
1872 bool CStyle) {
1873
1874 const RecordType *UT = ToType->getAsUnionType();
1875 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1876 return false;
1877 // The field to initialize within the transparent union.
1878 RecordDecl *UD = UT->getDecl();
1879 // It's compatible if the expression matches any of the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001880 for (const auto *it : UD->fields()) {
John McCall31168b02011-06-15 23:02:42 +00001881 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1882 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001883 ToType = it->getType();
1884 return true;
1885 }
1886 }
1887 return false;
1888}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001889
1890/// IsIntegralPromotion - Determines whether the conversion from the
1891/// expression From (whose potentially-adjusted type is FromType) to
1892/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1893/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001894bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001895 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001896 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001897 if (!To) {
1898 return false;
1899 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001900
1901 // An rvalue of type char, signed char, unsigned char, short int, or
1902 // unsigned short int can be converted to an rvalue of type int if
1903 // int can represent all the values of the source type; otherwise,
1904 // the source rvalue can be converted to an rvalue of type unsigned
1905 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001906 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1907 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001908 if (// We can promote any signed, promotable integer type to an int
1909 (FromType->isSignedIntegerType() ||
1910 // We can promote any unsigned integer type whose size is
1911 // less than int to an int.
Benjamin Kramer5ff67472016-04-11 08:26:13 +00001912 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001913 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001914 }
1915
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001916 return To->getKind() == BuiltinType::UInt;
1917 }
1918
Richard Smithb9c5a602012-09-13 21:18:54 +00001919 // C++11 [conv.prom]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001920 // A prvalue of an unscoped enumeration type whose underlying type is not
1921 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1922 // following types that can represent all the values of the enumeration
1923 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1924 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001925 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001926 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001927 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001928 // with lowest integer conversion rank (4.13) greater than the rank of long
1929 // long in which all the values of the enumeration can be represented. If
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001930 // there are two such extended types, the signed one is chosen.
Richard Smithb9c5a602012-09-13 21:18:54 +00001931 // C++11 [conv.prom]p4:
1932 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1933 // can be converted to a prvalue of its underlying type. Moreover, if
1934 // integral promotion can be applied to its underlying type, a prvalue of an
1935 // unscoped enumeration type whose underlying type is fixed can also be
1936 // converted to a prvalue of the promoted underlying type.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001937 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1938 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1939 // provided for a scoped enumeration.
1940 if (FromEnumType->getDecl()->isScoped())
1941 return false;
1942
Richard Smithb9c5a602012-09-13 21:18:54 +00001943 // We can perform an integral promotion to the underlying type of the enum,
Richard Smithac8c1752015-03-28 00:31:40 +00001944 // even if that's not the promoted type. Note that the check for promoting
1945 // the underlying type is based on the type alone, and does not consider
1946 // the bitfield-ness of the actual source expression.
Richard Smithb9c5a602012-09-13 21:18:54 +00001947 if (FromEnumType->getDecl()->isFixed()) {
1948 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1949 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
Richard Smithac8c1752015-03-28 00:31:40 +00001950 IsIntegralPromotion(nullptr, Underlying, ToType);
Richard Smithb9c5a602012-09-13 21:18:54 +00001951 }
1952
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001953 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001954 if (ToType->isIntegerType() &&
Richard Smithdb0ac552015-12-18 22:40:25 +00001955 isCompleteType(From->getLocStart(), FromType))
Richard Smith88f4bba2015-03-26 00:16:07 +00001956 return Context.hasSameUnqualifiedType(
1957 ToType, FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001958 }
John McCall56774992009-12-09 09:09:27 +00001959
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001960 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001961 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1962 // to an rvalue a prvalue of the first of the following types that can
1963 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001964 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001965 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001966 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001967 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001968 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001969 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001970 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001971 // Determine whether the type we're converting from is signed or
1972 // unsigned.
David Majnemerfa01a582011-07-22 21:09:04 +00001973 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001974 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001975
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001976 // The types we'll try to promote to, in the appropriate
1977 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001978 QualType PromoteTypes[6] = {
1979 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001980 Context.LongTy, Context.UnsignedLongTy ,
1981 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001982 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001983 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001984 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1985 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001986 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001987 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1988 // We found the type that we can promote to. If this is the
1989 // type we wanted, we have a promotion. Otherwise, no
1990 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001991 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001992 }
1993 }
1994 }
1995
1996 // An rvalue for an integral bit-field (9.6) can be converted to an
1997 // rvalue of type int if int can represent all the values of the
1998 // bit-field; otherwise, it can be converted to unsigned int if
1999 // unsigned int can represent all the values of the bit-field. If
2000 // the bit-field is larger yet, no integral promotion applies to
2001 // it. If the bit-field has an enumerated type, it is treated as any
2002 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00002003 // FIXME: We should delay checking of bit-fields until we actually perform the
2004 // conversion.
Richard Smith88f4bba2015-03-26 00:16:07 +00002005 if (From) {
John McCalld25db7e2013-05-06 21:39:12 +00002006 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
Richard Smith88f4bba2015-03-26 00:16:07 +00002007 llvm::APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00002008 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00002009 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
Richard Smith88f4bba2015-03-26 00:16:07 +00002010 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
Douglas Gregor71235ec2009-05-02 02:18:30 +00002011 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00002012
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00002013 // Are we promoting to an int from a bitfield that fits in an int?
2014 if (BitWidth < ToSize ||
2015 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
2016 return To->getKind() == BuiltinType::Int;
2017 }
Mike Stump11289f42009-09-09 15:08:12 +00002018
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00002019 // Are we promoting to an unsigned int from an unsigned bitfield
2020 // that fits into an unsigned int?
2021 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
2022 return To->getKind() == BuiltinType::UInt;
2023 }
Mike Stump11289f42009-09-09 15:08:12 +00002024
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00002025 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002026 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002027 }
Richard Smith88f4bba2015-03-26 00:16:07 +00002028 }
Mike Stump11289f42009-09-09 15:08:12 +00002029
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002030 // An rvalue of type bool can be converted to an rvalue of type int,
2031 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002032 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002033 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002034 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002035
2036 return false;
2037}
2038
2039/// IsFloatingPointPromotion - Determines whether the conversion from
2040/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2041/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00002042bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00002043 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2044 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002045 /// An rvalue of type float can be converted to an rvalue of type
2046 /// double. (C++ 4.6p1).
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002047 if (FromBuiltin->getKind() == BuiltinType::Float &&
2048 ToBuiltin->getKind() == BuiltinType::Double)
2049 return true;
2050
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002051 // C99 6.3.1.5p1:
2052 // When a float is promoted to double or long double, or a
2053 // double is promoted to long double [...].
David Blaikiebbafb8a2012-03-11 07:00:24 +00002054 if (!getLangOpts().CPlusPlus &&
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002055 (FromBuiltin->getKind() == BuiltinType::Float ||
2056 FromBuiltin->getKind() == BuiltinType::Double) &&
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002057 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2058 ToBuiltin->getKind() == BuiltinType::Float128))
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002059 return true;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002060
2061 // Half can be promoted to float.
Joey Goulydd7f4562013-01-23 11:56:20 +00002062 if (!getLangOpts().NativeHalfType &&
2063 FromBuiltin->getKind() == BuiltinType::Half &&
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002064 ToBuiltin->getKind() == BuiltinType::Float)
2065 return true;
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002066 }
2067
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002068 return false;
2069}
2070
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002071/// \brief Determine if a conversion is a complex promotion.
2072///
2073/// A complex promotion is defined as a complex -> complex conversion
2074/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00002075/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002076bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00002077 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002078 if (!FromComplex)
2079 return false;
2080
John McCall9dd450b2009-09-21 23:43:11 +00002081 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002082 if (!ToComplex)
2083 return false;
2084
2085 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00002086 ToComplex->getElementType()) ||
Craig Topperc3ec1492014-05-26 06:22:03 +00002087 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00002088 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002089}
2090
Douglas Gregor237f96c2008-11-26 23:31:11 +00002091/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2092/// the pointer type FromPtr to a pointer to type ToPointee, with the
2093/// same type qualifiers as FromPtr has on its pointee type. ToType,
2094/// if non-empty, will be a pointer to ToType that may or may not have
2095/// the right set of qualifiers on its pointee.
John McCall31168b02011-06-15 23:02:42 +00002096///
Mike Stump11289f42009-09-09 15:08:12 +00002097static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002098BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002099 QualType ToPointee, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002100 ASTContext &Context,
2101 bool StripObjCLifetime = false) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002102 assert((FromPtr->getTypeClass() == Type::Pointer ||
2103 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2104 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002105
John McCall31168b02011-06-15 23:02:42 +00002106 /// Conversions to 'id' subsume cv-qualifier conversions.
2107 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00002108 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002109
2110 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002111 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00002112 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00002113 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00002114
John McCall31168b02011-06-15 23:02:42 +00002115 if (StripObjCLifetime)
2116 Quals.removeObjCLifetime();
2117
Mike Stump11289f42009-09-09 15:08:12 +00002118 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002119 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00002120 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00002121 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00002122 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002123
2124 // Build a pointer to ToPointee. It has the right qualifiers
2125 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002126 if (isa<ObjCObjectPointerType>(ToType))
2127 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00002128 return Context.getPointerType(ToPointee);
2129 }
2130
2131 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002132 QualType QualifiedCanonToPointee
2133 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002134
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002135 if (isa<ObjCObjectPointerType>(ToType))
2136 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2137 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002138}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002139
Mike Stump11289f42009-09-09 15:08:12 +00002140static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00002141 bool InOverloadResolution,
2142 ASTContext &Context) {
2143 // Handle value-dependent integral null pointer constants correctly.
2144 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2145 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00002146 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00002147 return !InOverloadResolution;
2148
Douglas Gregor56751b52009-09-25 04:25:58 +00002149 return Expr->isNullPointerConstant(Context,
2150 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2151 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00002152}
Mike Stump11289f42009-09-09 15:08:12 +00002153
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002154/// IsPointerConversion - Determines whether the conversion of the
2155/// expression From, which has the (possibly adjusted) type FromType,
2156/// can be converted to the type ToType via a pointer conversion (C++
2157/// 4.10). If so, returns true and places the converted type (that
2158/// might differ from ToType in its cv-qualifiers at some level) into
2159/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00002160///
Douglas Gregora29dc052008-11-27 01:19:21 +00002161/// This routine also supports conversions to and from block pointers
2162/// and conversions with Objective-C's 'id', 'id<protocols...>', and
2163/// pointers to interfaces. FIXME: Once we've determined the
2164/// appropriate overloading rules for Objective-C, we may want to
2165/// split the Objective-C checks into a different routine; however,
2166/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00002167/// conversions, so for now they live here. IncompatibleObjC will be
2168/// set if the conversion is an allowed Objective-C conversion that
2169/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002170bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00002171 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00002172 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00002173 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00002174 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00002175 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2176 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00002177 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00002178
Mike Stump11289f42009-09-09 15:08:12 +00002179 // Conversion from a null pointer constant to any Objective-C pointer type.
2180 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002181 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00002182 ConvertedType = ToType;
2183 return true;
2184 }
2185
Douglas Gregor231d1c62008-11-27 00:15:41 +00002186 // Blocks: Block pointers can be converted to void*.
2187 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002188 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00002189 ConvertedType = ToType;
2190 return true;
2191 }
2192 // Blocks: A null pointer constant can be converted to a block
2193 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00002194 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002195 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00002196 ConvertedType = ToType;
2197 return true;
2198 }
2199
Sebastian Redl576fd422009-05-10 18:38:11 +00002200 // If the left-hand-side is nullptr_t, the right side can be a null
2201 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00002202 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002203 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00002204 ConvertedType = ToType;
2205 return true;
2206 }
2207
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002208 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002209 if (!ToTypePtr)
2210 return false;
2211
2212 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00002213 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002214 ConvertedType = ToType;
2215 return true;
2216 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002217
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002218 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002219 // , including objective-c pointers.
2220 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00002221 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002222 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002223 ConvertedType = BuildSimilarlyQualifiedPointerType(
2224 FromType->getAs<ObjCObjectPointerType>(),
2225 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002226 ToType, Context);
2227 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002228 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002229 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002230 if (!FromTypePtr)
2231 return false;
2232
2233 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002234
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002235 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-08-18 21:25:30 +00002236 // pointer conversion, so don't do all of the work below.
2237 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2238 return false;
2239
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002240 // An rvalue of type "pointer to cv T," where T is an object type,
2241 // can be converted to an rvalue of type "pointer to cv void" (C++
2242 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00002243 if (FromPointeeType->isIncompleteOrObjectType() &&
2244 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002245 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002246 ToPointeeType,
John McCall31168b02011-06-15 23:02:42 +00002247 ToType, Context,
2248 /*StripObjCLifetime=*/true);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002249 return true;
2250 }
2251
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002252 // MSVC allows implicit function to void* type conversion.
David Majnemer6bf02822015-10-31 08:42:14 +00002253 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002254 ToPointeeType->isVoidType()) {
2255 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2256 ToPointeeType,
2257 ToType, Context);
2258 return true;
2259 }
2260
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002261 // When we're overloading in C, we allow a special kind of pointer
2262 // conversion for compatible-but-not-identical pointee types.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002263 if (!getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002264 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002265 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002266 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00002267 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002268 return true;
2269 }
2270
Douglas Gregor5c407d92008-10-23 00:40:37 +00002271 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002272 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00002273 // An rvalue of type "pointer to cv D," where D is a class type,
2274 // can be converted to an rvalue of type "pointer to cv B," where
2275 // B is a base class (clause 10) of D. If B is an inaccessible
2276 // (clause 11) or ambiguous (10.2) base class of D, a program that
2277 // necessitates this conversion is ill-formed. The result of the
2278 // conversion is a pointer to the base class sub-object of the
2279 // derived class object. The null pointer value is converted to
2280 // the null pointer value of the destination type.
2281 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00002282 // Note that we do not check for ambiguity or inaccessibility
2283 // here. That is handled by CheckPointerConversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002284 if (getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002285 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00002286 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00002287 IsDerivedFrom(From->getLocStart(), FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002288 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002289 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002290 ToType, Context);
2291 return true;
2292 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002293
Fariborz Jahanianbc2ee932011-04-14 20:33:36 +00002294 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2295 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2296 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2297 ToPointeeType,
2298 ToType, Context);
2299 return true;
2300 }
2301
Douglas Gregora119f102008-12-19 19:13:09 +00002302 return false;
2303}
Douglas Gregoraec25842011-04-26 23:16:46 +00002304
2305/// \brief Adopt the given qualifiers for the given type.
2306static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2307 Qualifiers TQs = T.getQualifiers();
2308
2309 // Check whether qualifiers already match.
2310 if (TQs == Qs)
2311 return T;
2312
2313 if (Qs.compatiblyIncludes(TQs))
2314 return Context.getQualifiedType(T, Qs);
2315
2316 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2317}
Douglas Gregora119f102008-12-19 19:13:09 +00002318
2319/// isObjCPointerConversion - Determines whether this is an
2320/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2321/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00002322bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00002323 QualType& ConvertedType,
2324 bool &IncompatibleObjC) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002325 if (!getLangOpts().ObjC1)
Douglas Gregora119f102008-12-19 19:13:09 +00002326 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002327
Douglas Gregoraec25842011-04-26 23:16:46 +00002328 // The set of qualifiers on the type we're converting from.
2329 Qualifiers FromQualifiers = FromType.getQualifiers();
2330
Steve Naroff7cae42b2009-07-10 23:34:53 +00002331 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00002332 const ObjCObjectPointerType* ToObjCPtr =
2333 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00002334 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00002335 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002336
Steve Naroff7cae42b2009-07-10 23:34:53 +00002337 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002338 // If the pointee types are the same (ignoring qualifications),
2339 // then this is not a pointer conversion.
2340 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2341 FromObjCPtr->getPointeeType()))
2342 return false;
2343
Douglas Gregorab209d82015-07-07 03:58:42 +00002344 // Conversion between Objective-C pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00002345 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002346 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2347 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002348 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002349 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2350 FromObjCPtr->getPointeeType()))
2351 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002352 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002353 ToObjCPtr->getPointeeType(),
2354 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002355 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002356 return true;
2357 }
2358
2359 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2360 // Okay: this is some kind of implicit downcast of Objective-C
2361 // interfaces, which is permitted. However, we're going to
2362 // complain about it.
2363 IncompatibleObjC = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002364 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002365 ToObjCPtr->getPointeeType(),
2366 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002367 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002368 return true;
2369 }
Mike Stump11289f42009-09-09 15:08:12 +00002370 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00002371 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00002372 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002373 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002374 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002375 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002376 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002377 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002378 // to a block pointer type.
2379 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002380 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002381 return true;
2382 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002383 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002384 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002385 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002386 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002387 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002388 // pointer to any object.
Douglas Gregoraec25842011-04-26 23:16:46 +00002389 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002390 return true;
2391 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002392 else
Douglas Gregora119f102008-12-19 19:13:09 +00002393 return false;
2394
Douglas Gregor033f56d2008-12-23 00:53:59 +00002395 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002396 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002397 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00002398 else if (const BlockPointerType *FromBlockPtr =
2399 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00002400 FromPointeeType = FromBlockPtr->getPointeeType();
2401 else
Douglas Gregora119f102008-12-19 19:13:09 +00002402 return false;
2403
Douglas Gregora119f102008-12-19 19:13:09 +00002404 // If we have pointers to pointers, recursively check whether this
2405 // is an Objective-C conversion.
2406 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2407 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2408 IncompatibleObjC)) {
2409 // We always complain about this conversion.
2410 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002411 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002412 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002413 return true;
2414 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002415 // Allow conversion of pointee being objective-c pointer to another one;
2416 // as in I* to id.
2417 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2418 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2419 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2420 IncompatibleObjC)) {
John McCall31168b02011-06-15 23:02:42 +00002421
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002422 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002423 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002424 return true;
2425 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002426
Douglas Gregor033f56d2008-12-23 00:53:59 +00002427 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00002428 // differences in the argument and result types are in Objective-C
2429 // pointer conversions. If so, we permit the conversion (but
2430 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00002431 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002432 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002433 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002434 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002435 if (FromFunctionType && ToFunctionType) {
2436 // If the function types are exactly the same, this isn't an
2437 // Objective-C pointer conversion.
2438 if (Context.getCanonicalType(FromPointeeType)
2439 == Context.getCanonicalType(ToPointeeType))
2440 return false;
2441
2442 // Perform the quick checks that will tell us whether these
2443 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002444 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Douglas Gregora119f102008-12-19 19:13:09 +00002445 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2446 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2447 return false;
2448
2449 bool HasObjCConversion = false;
Alp Toker314cc812014-01-25 16:55:45 +00002450 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2451 Context.getCanonicalType(ToFunctionType->getReturnType())) {
Douglas Gregora119f102008-12-19 19:13:09 +00002452 // Okay, the types match exactly. Nothing to do.
Alp Toker314cc812014-01-25 16:55:45 +00002453 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2454 ToFunctionType->getReturnType(),
Douglas Gregora119f102008-12-19 19:13:09 +00002455 ConvertedType, IncompatibleObjC)) {
2456 // Okay, we have an Objective-C pointer conversion.
2457 HasObjCConversion = true;
2458 } else {
2459 // Function types are too different. Abort.
2460 return false;
2461 }
Mike Stump11289f42009-09-09 15:08:12 +00002462
Douglas Gregora119f102008-12-19 19:13:09 +00002463 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002464 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Douglas Gregora119f102008-12-19 19:13:09 +00002465 ArgIdx != NumArgs; ++ArgIdx) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002466 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2467 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Douglas Gregora119f102008-12-19 19:13:09 +00002468 if (Context.getCanonicalType(FromArgType)
2469 == Context.getCanonicalType(ToArgType)) {
2470 // Okay, the types match exactly. Nothing to do.
2471 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2472 ConvertedType, IncompatibleObjC)) {
2473 // Okay, we have an Objective-C pointer conversion.
2474 HasObjCConversion = true;
2475 } else {
2476 // Argument types are too different. Abort.
2477 return false;
2478 }
2479 }
2480
2481 if (HasObjCConversion) {
2482 // We had an Objective-C conversion. Allow this pointer
2483 // conversion, but complain about it.
Douglas Gregoraec25842011-04-26 23:16:46 +00002484 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002485 IncompatibleObjC = true;
2486 return true;
2487 }
2488 }
2489
Sebastian Redl72b597d2009-01-25 19:43:20 +00002490 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002491}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002492
John McCall31168b02011-06-15 23:02:42 +00002493/// \brief Determine whether this is an Objective-C writeback conversion,
2494/// used for parameter passing when performing automatic reference counting.
2495///
2496/// \param FromType The type we're converting form.
2497///
2498/// \param ToType The type we're converting to.
2499///
2500/// \param ConvertedType The type that will be produced after applying
2501/// this conversion.
2502bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2503 QualType &ConvertedType) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002504 if (!getLangOpts().ObjCAutoRefCount ||
John McCall31168b02011-06-15 23:02:42 +00002505 Context.hasSameUnqualifiedType(FromType, ToType))
2506 return false;
2507
2508 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2509 QualType ToPointee;
2510 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2511 ToPointee = ToPointer->getPointeeType();
2512 else
2513 return false;
2514
2515 Qualifiers ToQuals = ToPointee.getQualifiers();
2516 if (!ToPointee->isObjCLifetimeType() ||
2517 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall18ce25e2012-02-08 00:46:36 +00002518 !ToQuals.withoutObjCLifetime().empty())
John McCall31168b02011-06-15 23:02:42 +00002519 return false;
2520
2521 // Argument must be a pointer to __strong to __weak.
2522 QualType FromPointee;
2523 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2524 FromPointee = FromPointer->getPointeeType();
2525 else
2526 return false;
2527
2528 Qualifiers FromQuals = FromPointee.getQualifiers();
2529 if (!FromPointee->isObjCLifetimeType() ||
2530 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2531 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2532 return false;
2533
2534 // Make sure that we have compatible qualifiers.
2535 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2536 if (!ToQuals.compatiblyIncludes(FromQuals))
2537 return false;
2538
2539 // Remove qualifiers from the pointee type we're converting from; they
2540 // aren't used in the compatibility check belong, and we'll be adding back
2541 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2542 FromPointee = FromPointee.getUnqualifiedType();
2543
2544 // The unqualified form of the pointee types must be compatible.
2545 ToPointee = ToPointee.getUnqualifiedType();
2546 bool IncompatibleObjC;
2547 if (Context.typesAreCompatible(FromPointee, ToPointee))
2548 FromPointee = ToPointee;
2549 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2550 IncompatibleObjC))
2551 return false;
2552
2553 /// \brief Construct the type we're converting to, which is a pointer to
2554 /// __autoreleasing pointee.
2555 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2556 ConvertedType = Context.getPointerType(FromPointee);
2557 return true;
2558}
2559
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002560bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2561 QualType& ConvertedType) {
2562 QualType ToPointeeType;
2563 if (const BlockPointerType *ToBlockPtr =
2564 ToType->getAs<BlockPointerType>())
2565 ToPointeeType = ToBlockPtr->getPointeeType();
2566 else
2567 return false;
2568
2569 QualType FromPointeeType;
2570 if (const BlockPointerType *FromBlockPtr =
2571 FromType->getAs<BlockPointerType>())
2572 FromPointeeType = FromBlockPtr->getPointeeType();
2573 else
2574 return false;
2575 // We have pointer to blocks, check whether the only
2576 // differences in the argument and result types are in Objective-C
2577 // pointer conversions. If so, we permit the conversion.
2578
2579 const FunctionProtoType *FromFunctionType
2580 = FromPointeeType->getAs<FunctionProtoType>();
2581 const FunctionProtoType *ToFunctionType
2582 = ToPointeeType->getAs<FunctionProtoType>();
2583
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002584 if (!FromFunctionType || !ToFunctionType)
2585 return false;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002586
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002587 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002588 return true;
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002589
2590 // Perform the quick checks that will tell us whether these
2591 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002592 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002593 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2594 return false;
2595
2596 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2597 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2598 if (FromEInfo != ToEInfo)
2599 return false;
2600
2601 bool IncompatibleObjC = false;
Alp Toker314cc812014-01-25 16:55:45 +00002602 if (Context.hasSameType(FromFunctionType->getReturnType(),
2603 ToFunctionType->getReturnType())) {
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002604 // Okay, the types match exactly. Nothing to do.
2605 } else {
Alp Toker314cc812014-01-25 16:55:45 +00002606 QualType RHS = FromFunctionType->getReturnType();
2607 QualType LHS = ToFunctionType->getReturnType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002608 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002609 !RHS.hasQualifiers() && LHS.hasQualifiers())
2610 LHS = LHS.getUnqualifiedType();
2611
2612 if (Context.hasSameType(RHS,LHS)) {
2613 // OK exact match.
2614 } else if (isObjCPointerConversion(RHS, LHS,
2615 ConvertedType, IncompatibleObjC)) {
2616 if (IncompatibleObjC)
2617 return false;
2618 // Okay, we have an Objective-C pointer conversion.
2619 }
2620 else
2621 return false;
2622 }
2623
2624 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002625 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002626 ArgIdx != NumArgs; ++ArgIdx) {
2627 IncompatibleObjC = false;
Alp Toker9cacbab2014-01-20 20:26:09 +00002628 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2629 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002630 if (Context.hasSameType(FromArgType, ToArgType)) {
2631 // Okay, the types match exactly. Nothing to do.
2632 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2633 ConvertedType, IncompatibleObjC)) {
2634 if (IncompatibleObjC)
2635 return false;
2636 // Okay, we have an Objective-C pointer conversion.
2637 } else
2638 // Argument types are too different. Abort.
2639 return false;
2640 }
John McCall18afab72016-03-01 00:49:02 +00002641 if (!Context.doFunctionTypesMatchOnExtParameterInfos(FromFunctionType,
2642 ToFunctionType))
Fariborz Jahanian97676972011-09-28 21:52:05 +00002643 return false;
Fariborz Jahanian600ba202011-09-28 20:22:05 +00002644
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002645 ConvertedType = ToType;
2646 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002647}
2648
Richard Trieucaff2472011-11-23 22:32:32 +00002649enum {
2650 ft_default,
2651 ft_different_class,
2652 ft_parameter_arity,
2653 ft_parameter_mismatch,
2654 ft_return_type,
Richard Smith3c4f8d22016-10-16 17:54:23 +00002655 ft_qualifer_mismatch,
2656 ft_noexcept
Richard Trieucaff2472011-11-23 22:32:32 +00002657};
2658
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002659/// Attempts to get the FunctionProtoType from a Type. Handles
2660/// MemberFunctionPointers properly.
2661static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2662 if (auto *FPT = FromType->getAs<FunctionProtoType>())
2663 return FPT;
2664
2665 if (auto *MPT = FromType->getAs<MemberPointerType>())
2666 return MPT->getPointeeType()->getAs<FunctionProtoType>();
2667
2668 return nullptr;
2669}
2670
Richard Trieucaff2472011-11-23 22:32:32 +00002671/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2672/// function types. Catches different number of parameter, mismatch in
2673/// parameter types, and different return types.
2674void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2675 QualType FromType, QualType ToType) {
Richard Trieu96ed5b62011-12-13 23:19:45 +00002676 // If either type is not valid, include no extra info.
2677 if (FromType.isNull() || ToType.isNull()) {
2678 PDiag << ft_default;
2679 return;
2680 }
2681
Richard Trieucaff2472011-11-23 22:32:32 +00002682 // Get the function type from the pointers.
2683 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2684 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2685 *ToMember = ToType->getAs<MemberPointerType>();
Richard Trieu9098c9f2014-05-22 01:39:16 +00002686 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
Richard Trieucaff2472011-11-23 22:32:32 +00002687 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2688 << QualType(FromMember->getClass(), 0);
2689 return;
2690 }
2691 FromType = FromMember->getPointeeType();
2692 ToType = ToMember->getPointeeType();
Richard Trieucaff2472011-11-23 22:32:32 +00002693 }
2694
Richard Trieu96ed5b62011-12-13 23:19:45 +00002695 if (FromType->isPointerType())
2696 FromType = FromType->getPointeeType();
2697 if (ToType->isPointerType())
2698 ToType = ToType->getPointeeType();
2699
2700 // Remove references.
Richard Trieucaff2472011-11-23 22:32:32 +00002701 FromType = FromType.getNonReferenceType();
2702 ToType = ToType.getNonReferenceType();
2703
Richard Trieucaff2472011-11-23 22:32:32 +00002704 // Don't print extra info for non-specialized template functions.
2705 if (FromType->isInstantiationDependentType() &&
2706 !FromType->getAs<TemplateSpecializationType>()) {
2707 PDiag << ft_default;
2708 return;
2709 }
2710
Richard Trieu96ed5b62011-12-13 23:19:45 +00002711 // No extra info for same types.
2712 if (Context.hasSameType(FromType, ToType)) {
2713 PDiag << ft_default;
2714 return;
2715 }
2716
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002717 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2718 *ToFunction = tryGetFunctionProtoType(ToType);
Richard Trieucaff2472011-11-23 22:32:32 +00002719
2720 // Both types need to be function types.
2721 if (!FromFunction || !ToFunction) {
2722 PDiag << ft_default;
2723 return;
2724 }
2725
Alp Toker9cacbab2014-01-20 20:26:09 +00002726 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2727 PDiag << ft_parameter_arity << ToFunction->getNumParams()
2728 << FromFunction->getNumParams();
Richard Trieucaff2472011-11-23 22:32:32 +00002729 return;
2730 }
2731
2732 // Handle different parameter types.
2733 unsigned ArgPos;
Alp Toker9cacbab2014-01-20 20:26:09 +00002734 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
Richard Trieucaff2472011-11-23 22:32:32 +00002735 PDiag << ft_parameter_mismatch << ArgPos + 1
Alp Toker9cacbab2014-01-20 20:26:09 +00002736 << ToFunction->getParamType(ArgPos)
2737 << FromFunction->getParamType(ArgPos);
Richard Trieucaff2472011-11-23 22:32:32 +00002738 return;
2739 }
2740
2741 // Handle different return type.
Alp Toker314cc812014-01-25 16:55:45 +00002742 if (!Context.hasSameType(FromFunction->getReturnType(),
2743 ToFunction->getReturnType())) {
2744 PDiag << ft_return_type << ToFunction->getReturnType()
2745 << FromFunction->getReturnType();
Richard Trieucaff2472011-11-23 22:32:32 +00002746 return;
2747 }
2748
2749 unsigned FromQuals = FromFunction->getTypeQuals(),
2750 ToQuals = ToFunction->getTypeQuals();
2751 if (FromQuals != ToQuals) {
2752 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2753 return;
2754 }
2755
Richard Smith3c4f8d22016-10-16 17:54:23 +00002756 // Handle exception specification differences on canonical type (in C++17
2757 // onwards).
2758 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2759 ->isNothrow(Context) !=
2760 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2761 ->isNothrow(Context)) {
2762 PDiag << ft_noexcept;
2763 return;
2764 }
2765
Richard Trieucaff2472011-11-23 22:32:32 +00002766 // Unable to find a difference, so add no extra info.
2767 PDiag << ft_default;
2768}
2769
Alp Toker9cacbab2014-01-20 20:26:09 +00002770/// FunctionParamTypesAreEqual - This routine checks two function proto types
Douglas Gregor2039ca02011-12-15 17:15:07 +00002771/// for equality of their argument types. Caller has already checked that
Eli Friedman5f508952013-06-18 22:41:37 +00002772/// they have same number of arguments. If the parameters are different,
2773/// ArgPos will have the parameter index of the first different parameter.
Alp Toker9cacbab2014-01-20 20:26:09 +00002774bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2775 const FunctionProtoType *NewType,
2776 unsigned *ArgPos) {
2777 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2778 N = NewType->param_type_begin(),
2779 E = OldType->param_type_end();
2780 O && (O != E); ++O, ++N) {
Richard Trieu4b03d982013-08-09 21:42:32 +00002781 if (!Context.hasSameType(O->getUnqualifiedType(),
2782 N->getUnqualifiedType())) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002783 if (ArgPos)
2784 *ArgPos = O - OldType->param_type_begin();
Larisse Voufo4154f462013-08-06 03:57:41 +00002785 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002786 }
2787 }
2788 return true;
2789}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002790
Douglas Gregor39c16d42008-10-24 04:54:22 +00002791/// CheckPointerConversion - Check the pointer conversion from the
2792/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00002793/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00002794/// conversions for which IsPointerConversion has already returned
2795/// true. It returns true and produces a diagnostic if there was an
2796/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002797bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002798 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002799 CXXCastPath& BasePath,
George Burgess IV60bc9722016-01-13 23:36:34 +00002800 bool IgnoreBaseAccess,
2801 bool Diagnose) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002802 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00002803 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002804
John McCall8cb679e2010-11-15 09:13:47 +00002805 Kind = CK_BitCast;
2806
George Burgess IV60bc9722016-01-13 23:36:34 +00002807 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
Argyrios Kyrtzidis3e3305d2014-02-02 05:26:43 +00002808 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
George Burgess IV60bc9722016-01-13 23:36:34 +00002809 Expr::NPCK_ZeroExpression) {
David Blaikie1c7c8f72012-08-08 17:33:31 +00002810 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2811 DiagRuntimeBehavior(From->getExprLoc(), From,
2812 PDiag(diag::warn_impcast_bool_to_null_pointer)
2813 << ToType << From->getSourceRange());
2814 else if (!isUnevaluatedContext())
2815 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2816 << ToType << From->getSourceRange();
2817 }
John McCall9320b872011-09-09 05:25:32 +00002818 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2819 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002820 QualType FromPointeeType = FromPtrType->getPointeeType(),
2821 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00002822
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002823 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2824 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002825 // We must have a derived-to-base conversion. Check an
2826 // ambiguous or inaccessible conversion.
George Burgess IV60bc9722016-01-13 23:36:34 +00002827 unsigned InaccessibleID = 0;
2828 unsigned AmbigiousID = 0;
2829 if (Diagnose) {
2830 InaccessibleID = diag::err_upcast_to_inaccessible_base;
2831 AmbigiousID = diag::err_ambiguous_derived_to_base_conv;
2832 }
2833 if (CheckDerivedToBaseConversion(
2834 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID,
2835 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
2836 &BasePath, IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002837 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002838
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002839 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00002840 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002841 }
David Majnemer6bf02822015-10-31 08:42:14 +00002842
George Burgess IV60bc9722016-01-13 23:36:34 +00002843 if (Diagnose && !IsCStyleOrFunctionalCast &&
2844 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
David Majnemer6bf02822015-10-31 08:42:14 +00002845 assert(getLangOpts().MSVCCompat &&
2846 "this should only be possible with MSVCCompat!");
2847 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
2848 << From->getSourceRange();
2849 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00002850 }
John McCall9320b872011-09-09 05:25:32 +00002851 } else if (const ObjCObjectPointerType *ToPtrType =
2852 ToType->getAs<ObjCObjectPointerType>()) {
2853 if (const ObjCObjectPointerType *FromPtrType =
2854 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002855 // Objective-C++ conversions are always okay.
2856 // FIXME: We should have a different class of conversions for the
2857 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00002858 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002859 return false;
John McCall9320b872011-09-09 05:25:32 +00002860 } else if (FromType->isBlockPointerType()) {
2861 Kind = CK_BlockPointerToObjCPointerCast;
2862 } else {
2863 Kind = CK_CPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00002864 }
John McCall9320b872011-09-09 05:25:32 +00002865 } else if (ToType->isBlockPointerType()) {
2866 if (!FromType->isBlockPointerType())
2867 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002868 }
John McCall8cb679e2010-11-15 09:13:47 +00002869
2870 // We shouldn't fall into this case unless it's valid for other
2871 // reasons.
2872 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2873 Kind = CK_NullToPointer;
2874
Douglas Gregor39c16d42008-10-24 04:54:22 +00002875 return false;
2876}
2877
Sebastian Redl72b597d2009-01-25 19:43:20 +00002878/// IsMemberPointerConversion - Determines whether the conversion of the
2879/// expression From, which has the (possibly adjusted) type FromType, can be
2880/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2881/// If so, returns true and places the converted type (that might differ from
2882/// ToType in its cv-qualifiers at some level) into ConvertedType.
2883bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002884 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00002885 bool InOverloadResolution,
2886 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002887 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002888 if (!ToTypePtr)
2889 return false;
2890
2891 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00002892 if (From->isNullPointerConstant(Context,
2893 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2894 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002895 ConvertedType = ToType;
2896 return true;
2897 }
2898
2899 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002900 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002901 if (!FromTypePtr)
2902 return false;
2903
2904 // A pointer to member of B can be converted to a pointer to member of D,
2905 // where D is derived from B (C++ 4.11p2).
2906 QualType FromClass(FromTypePtr->getClass(), 0);
2907 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002908
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002909 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00002910 IsDerivedFrom(From->getLocStart(), ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002911 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2912 ToClass.getTypePtr());
2913 return true;
2914 }
2915
2916 return false;
2917}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002918
Sebastian Redl72b597d2009-01-25 19:43:20 +00002919/// CheckMemberPointerConversion - Check the member pointer conversion from the
2920/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002921/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002922/// for which IsMemberPointerConversion has already returned true. It returns
2923/// true and produces a diagnostic if there was an error, or returns false
2924/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002925bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002926 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002927 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002928 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002929 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002930 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00002931 if (!FromPtrType) {
2932 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002933 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00002934 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00002935 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00002936 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00002937 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00002938 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00002939
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002940 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00002941 assert(ToPtrType && "No member pointer cast has a target type "
2942 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002943
Sebastian Redled8f2002009-01-28 18:33:18 +00002944 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2945 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002946
Sebastian Redled8f2002009-01-28 18:33:18 +00002947 // FIXME: What about dependent types?
2948 assert(FromClass->isRecordType() && "Pointer into non-class.");
2949 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002950
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002951 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002952 /*DetectVirtual=*/true);
Richard Smith0f59cb32015-12-18 21:45:41 +00002953 bool DerivationOkay =
2954 IsDerivedFrom(From->getLocStart(), ToClass, FromClass, Paths);
Sebastian Redled8f2002009-01-28 18:33:18 +00002955 assert(DerivationOkay &&
2956 "Should not have been called if derivation isn't OK.");
2957 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002958
Sebastian Redled8f2002009-01-28 18:33:18 +00002959 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2960 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002961 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2962 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2963 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2964 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002965 }
Sebastian Redled8f2002009-01-28 18:33:18 +00002966
Douglas Gregor89ee6822009-02-28 01:32:25 +00002967 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002968 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2969 << FromClass << ToClass << QualType(VBase, 0)
2970 << From->getSourceRange();
2971 return true;
2972 }
2973
John McCall5b0829a2010-02-10 09:31:12 +00002974 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00002975 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2976 Paths.front(),
2977 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00002978
Anders Carlssond7923c62009-08-22 23:33:40 +00002979 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002980 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00002981 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002982 return false;
2983}
2984
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002985/// Determine whether the lifetime conversion between the two given
2986/// qualifiers sets is nontrivial.
2987static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
2988 Qualifiers ToQuals) {
2989 // Converting anything to const __unsafe_unretained is trivial.
2990 if (ToQuals.hasConst() &&
2991 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
2992 return false;
2993
2994 return true;
2995}
2996
Douglas Gregor9a657932008-10-21 23:43:52 +00002997/// IsQualificationConversion - Determines whether the conversion from
2998/// an rvalue of type FromType to ToType is a qualification conversion
2999/// (C++ 4.4).
John McCall31168b02011-06-15 23:02:42 +00003000///
3001/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3002/// when the qualification conversion involves a change in the Objective-C
3003/// object lifetime.
Mike Stump11289f42009-09-09 15:08:12 +00003004bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003005Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00003006 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor9a657932008-10-21 23:43:52 +00003007 FromType = Context.getCanonicalType(FromType);
3008 ToType = Context.getCanonicalType(ToType);
John McCall31168b02011-06-15 23:02:42 +00003009 ObjCLifetimeConversion = false;
3010
Douglas Gregor9a657932008-10-21 23:43:52 +00003011 // If FromType and ToType are the same type, this is not a
3012 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00003013 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00003014 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00003015
Douglas Gregor9a657932008-10-21 23:43:52 +00003016 // (C++ 4.4p4):
3017 // A conversion can add cv-qualifiers at levels other than the first
3018 // in multi-level pointers, subject to the following rules: [...]
3019 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00003020 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003021 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00003022 // Within each iteration of the loop, we check the qualifiers to
3023 // determine if this still looks like a qualification
3024 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003025 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00003026 // until there are no more pointers or pointers-to-members left to
3027 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003028 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00003029
Douglas Gregor90609aa2011-04-25 18:40:17 +00003030 Qualifiers FromQuals = FromType.getQualifiers();
3031 Qualifiers ToQuals = ToType.getQualifiers();
Andrey Bokhanko45d41322016-05-11 18:38:21 +00003032
3033 // Ignore __unaligned qualifier if this type is void.
3034 if (ToType.getUnqualifiedType()->isVoidType())
3035 FromQuals.removeUnaligned();
Douglas Gregor90609aa2011-04-25 18:40:17 +00003036
John McCall31168b02011-06-15 23:02:42 +00003037 // Objective-C ARC:
3038 // Check Objective-C lifetime conversions.
3039 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
3040 UnwrappedAnyPointer) {
3041 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00003042 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3043 ObjCLifetimeConversion = true;
John McCall31168b02011-06-15 23:02:42 +00003044 FromQuals.removeObjCLifetime();
3045 ToQuals.removeObjCLifetime();
3046 } else {
3047 // Qualification conversions cannot cast between different
3048 // Objective-C lifetime qualifiers.
3049 return false;
3050 }
3051 }
3052
Douglas Gregorf30053d2011-05-08 06:09:53 +00003053 // Allow addition/removal of GC attributes but not changing GC attributes.
3054 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3055 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3056 FromQuals.removeObjCGCAttr();
3057 ToQuals.removeObjCGCAttr();
3058 }
3059
Douglas Gregor9a657932008-10-21 23:43:52 +00003060 // -- for every j > 0, if const is in cv 1,j then const is in cv
3061 // 2,j, and similarly for volatile.
Douglas Gregor90609aa2011-04-25 18:40:17 +00003062 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor9a657932008-10-21 23:43:52 +00003063 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003064
Douglas Gregor9a657932008-10-21 23:43:52 +00003065 // -- if the cv 1,j and cv 2,j are different, then const is in
3066 // every cv for 0 < k < j.
Douglas Gregor90609aa2011-04-25 18:40:17 +00003067 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003068 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00003069 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003070
Douglas Gregor9a657932008-10-21 23:43:52 +00003071 // Keep track of whether all prior cv-qualifiers in the "to" type
3072 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00003073 PreviousToQualsIncludeConst
Douglas Gregor90609aa2011-04-25 18:40:17 +00003074 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003075 }
Douglas Gregor9a657932008-10-21 23:43:52 +00003076
3077 // We are left with FromType and ToType being the pointee types
3078 // after unwrapping the original FromType and ToType the same number
3079 // of types. If we unwrapped any pointers, and if FromType and
3080 // ToType have the same unqualified type (since we checked
3081 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003082 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00003083}
3084
Douglas Gregorc79862f2012-04-12 17:51:55 +00003085/// \brief - Determine whether this is a conversion from a scalar type to an
3086/// atomic type.
3087///
3088/// If successful, updates \c SCS's second and third steps in the conversion
3089/// sequence to finish the conversion.
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00003090static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3091 bool InOverloadResolution,
3092 StandardConversionSequence &SCS,
3093 bool CStyle) {
Douglas Gregorc79862f2012-04-12 17:51:55 +00003094 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3095 if (!ToAtomic)
3096 return false;
3097
3098 StandardConversionSequence InnerSCS;
3099 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3100 InOverloadResolution, InnerSCS,
3101 CStyle, /*AllowObjCWritebackConversion=*/false))
3102 return false;
3103
3104 SCS.Second = InnerSCS.Second;
3105 SCS.setToType(1, InnerSCS.getToType(1));
3106 SCS.Third = InnerSCS.Third;
3107 SCS.QualificationIncludesObjCLifetime
3108 = InnerSCS.QualificationIncludesObjCLifetime;
3109 SCS.setToType(2, InnerSCS.getToType(2));
3110 return true;
3111}
3112
Sebastian Redle5417162012-03-27 18:33:03 +00003113static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3114 CXXConstructorDecl *Constructor,
3115 QualType Type) {
3116 const FunctionProtoType *CtorType =
3117 Constructor->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00003118 if (CtorType->getNumParams() > 0) {
3119 QualType FirstArg = CtorType->getParamType(0);
Sebastian Redle5417162012-03-27 18:33:03 +00003120 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3121 return true;
3122 }
3123 return false;
3124}
3125
Sebastian Redl82ace982012-02-11 23:51:08 +00003126static OverloadingResult
3127IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3128 CXXRecordDecl *To,
3129 UserDefinedConversionSequence &User,
3130 OverloadCandidateSet &CandidateSet,
3131 bool AllowExplicit) {
Richard Smithc2bebe92016-05-11 20:37:46 +00003132 for (auto *D : S.LookupConstructors(To)) {
3133 auto Info = getConstructorInfo(D);
Richard Smith5179eb72016-06-28 19:03:57 +00003134 if (!Info)
Richard Smithc2bebe92016-05-11 20:37:46 +00003135 continue;
Sebastian Redl82ace982012-02-11 23:51:08 +00003136
Richard Smithc2bebe92016-05-11 20:37:46 +00003137 bool Usable = !Info.Constructor->isInvalidDecl() &&
3138 S.isInitListConstructor(Info.Constructor) &&
3139 (AllowExplicit || !Info.Constructor->isExplicit());
Sebastian Redl82ace982012-02-11 23:51:08 +00003140 if (Usable) {
Sebastian Redle5417162012-03-27 18:33:03 +00003141 // If the first argument is (a reference to) the target type,
3142 // suppress conversions.
Richard Smithc2bebe92016-05-11 20:37:46 +00003143 bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3144 S.Context, Info.Constructor, ToType);
3145 if (Info.ConstructorTmpl)
3146 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3147 /*ExplicitArgs*/ nullptr, From,
3148 CandidateSet, SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00003149 else
Richard Smithc2bebe92016-05-11 20:37:46 +00003150 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3151 CandidateSet, SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00003152 }
3153 }
3154
3155 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3156
3157 OverloadCandidateSet::iterator Best;
Fariborz Jahaniandcf06f42015-04-14 17:21:58 +00003158 switch (auto Result =
3159 CandidateSet.BestViableFunction(S, From->getLocStart(),
3160 Best, true)) {
3161 case OR_Deleted:
Sebastian Redl82ace982012-02-11 23:51:08 +00003162 case OR_Success: {
3163 // Record the standard conversion we used and the conversion function.
3164 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Sebastian Redl82ace982012-02-11 23:51:08 +00003165 QualType ThisType = Constructor->getThisType(S.Context);
3166 // Initializer lists don't have conversions as such.
3167 User.Before.setAsIdentityConversion();
3168 User.HadMultipleCandidates = HadMultipleCandidates;
3169 User.ConversionFunction = Constructor;
3170 User.FoundConversionFunction = Best->FoundDecl;
3171 User.After.setAsIdentityConversion();
3172 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3173 User.After.setAllToTypes(ToType);
Fariborz Jahaniandcf06f42015-04-14 17:21:58 +00003174 return Result;
Sebastian Redl82ace982012-02-11 23:51:08 +00003175 }
3176
3177 case OR_No_Viable_Function:
3178 return OR_No_Viable_Function;
Sebastian Redl82ace982012-02-11 23:51:08 +00003179 case OR_Ambiguous:
3180 return OR_Ambiguous;
3181 }
3182
3183 llvm_unreachable("Invalid OverloadResult!");
3184}
3185
Douglas Gregor576e98c2009-01-30 23:27:23 +00003186/// Determines whether there is a user-defined conversion sequence
3187/// (C++ [over.ics.user]) that converts expression From to the type
3188/// ToType. If such a conversion exists, User will contain the
3189/// user-defined conversion sequence that performs such a conversion
3190/// and this routine will return true. Otherwise, this routine returns
3191/// false and User is unspecified.
3192///
Douglas Gregor576e98c2009-01-30 23:27:23 +00003193/// \param AllowExplicit true if the conversion should consider C++0x
3194/// "explicit" conversion functions as well as non-explicit conversion
3195/// functions (C++0x [class.conv.fct]p2).
Douglas Gregor4b60a152013-11-07 22:34:54 +00003196///
3197/// \param AllowObjCConversionOnExplicit true if the conversion should
3198/// allow an extra Objective-C pointer conversion on uses of explicit
3199/// constructors. Requires \c AllowExplicit to also be set.
John McCall5c32be02010-08-24 20:38:10 +00003200static OverloadingResult
3201IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl82ace982012-02-11 23:51:08 +00003202 UserDefinedConversionSequence &User,
3203 OverloadCandidateSet &CandidateSet,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003204 bool AllowExplicit,
3205 bool AllowObjCConversionOnExplicit) {
Douglas Gregor2ee1d992013-11-08 01:20:25 +00003206 assert(AllowExplicit || !AllowObjCConversionOnExplicit);
Douglas Gregor4b60a152013-11-07 22:34:54 +00003207
Douglas Gregor5ab11652010-04-17 22:01:05 +00003208 // Whether we will only visit constructors.
3209 bool ConstructorsOnly = false;
3210
3211 // If the type we are conversion to is a class type, enumerate its
3212 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003213 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00003214 // C++ [over.match.ctor]p1:
3215 // When objects of class type are direct-initialized (8.5), or
3216 // copy-initialized from an expression of the same or a
3217 // derived class type (8.5), overload resolution selects the
3218 // constructor. [...] For copy-initialization, the candidate
3219 // functions are all the converting constructors (12.3.1) of
3220 // that class. The argument list is the expression-list within
3221 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00003222 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00003223 (From->getType()->getAs<RecordType>() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00003224 S.IsDerivedFrom(From->getLocStart(), From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00003225 ConstructorsOnly = true;
3226
Richard Smithdb0ac552015-12-18 22:40:25 +00003227 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003228 // We're not going to find any constructors.
3229 } else if (CXXRecordDecl *ToRecordDecl
3230 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003231
3232 Expr **Args = &From;
3233 unsigned NumArgs = 1;
3234 bool ListInitializing = false;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003235 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003236 // But first, see if there is an init-list-constructor that will work.
Sebastian Redl82ace982012-02-11 23:51:08 +00003237 OverloadingResult Result = IsInitializerListConstructorConversion(
3238 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3239 if (Result != OR_No_Viable_Function)
3240 return Result;
3241 // Never mind.
3242 CandidateSet.clear();
3243
3244 // If we're list-initializing, we pass the individual elements as
3245 // arguments, not the entire list.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003246 Args = InitList->getInits();
3247 NumArgs = InitList->getNumInits();
3248 ListInitializing = true;
3249 }
3250
Richard Smithc2bebe92016-05-11 20:37:46 +00003251 for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3252 auto Info = getConstructorInfo(D);
Richard Smith5179eb72016-06-28 19:03:57 +00003253 if (!Info)
Richard Smithc2bebe92016-05-11 20:37:46 +00003254 continue;
John McCalla0296f72010-03-19 07:35:19 +00003255
Richard Smithc2bebe92016-05-11 20:37:46 +00003256 bool Usable = !Info.Constructor->isInvalidDecl();
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003257 if (ListInitializing)
Richard Smithc2bebe92016-05-11 20:37:46 +00003258 Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit());
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003259 else
Richard Smithc2bebe92016-05-11 20:37:46 +00003260 Usable = Usable &&
3261 Info.Constructor->isConvertingConstructor(AllowExplicit);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003262 if (Usable) {
Sebastian Redld9170b02012-03-20 21:24:14 +00003263 bool SuppressUserConversions = !ConstructorsOnly;
3264 if (SuppressUserConversions && ListInitializing) {
3265 SuppressUserConversions = false;
3266 if (NumArgs == 1) {
3267 // If the first argument is (a reference to) the target type,
3268 // suppress conversions.
Sebastian Redle5417162012-03-27 18:33:03 +00003269 SuppressUserConversions = isFirstArgumentCompatibleWithType(
Richard Smithc2bebe92016-05-11 20:37:46 +00003270 S.Context, Info.Constructor, ToType);
Sebastian Redld9170b02012-03-20 21:24:14 +00003271 }
3272 }
Richard Smithc2bebe92016-05-11 20:37:46 +00003273 if (Info.ConstructorTmpl)
3274 S.AddTemplateOverloadCandidate(
3275 Info.ConstructorTmpl, Info.FoundDecl,
3276 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3277 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003278 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00003279 // Allow one user-defined conversion when user specifies a
3280 // From->ToType conversion via an static cast (c-style, etc).
Richard Smithc2bebe92016-05-11 20:37:46 +00003281 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003282 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003283 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003284 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00003285 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003286 }
3287 }
3288
Douglas Gregor5ab11652010-04-17 22:01:05 +00003289 // Enumerate conversion functions, if we're allowed to.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003290 if (ConstructorsOnly || isa<InitListExpr>(From)) {
Richard Smithdb0ac552015-12-18 22:40:25 +00003291 } else if (!S.isCompleteType(From->getLocStart(), From->getType())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003292 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00003293 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00003294 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00003295 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003296 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3297 // Add all of the conversion functions as candidates.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00003298 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3299 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00003300 DeclAccessPair FoundDecl = I.getPair();
3301 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003302 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3303 if (isa<UsingShadowDecl>(D))
3304 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3305
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003306 CXXConversionDecl *Conv;
3307 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00003308 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3309 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003310 else
John McCallda4458e2010-03-31 01:36:47 +00003311 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003312
3313 if (AllowExplicit || !Conv->isExplicit()) {
3314 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00003315 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3316 ActingContext, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003317 CandidateSet,
3318 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003319 else
John McCall5c32be02010-08-24 20:38:10 +00003320 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003321 From, ToType, CandidateSet,
3322 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003323 }
3324 }
3325 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00003326 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003327
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003328 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3329
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003330 OverloadCandidateSet::iterator Best;
Richard Smith48372b62015-01-27 03:30:40 +00003331 switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(),
3332 Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00003333 case OR_Success:
Richard Smith48372b62015-01-27 03:30:40 +00003334 case OR_Deleted:
John McCall5c32be02010-08-24 20:38:10 +00003335 // Record the standard conversion we used and the conversion function.
3336 if (CXXConstructorDecl *Constructor
3337 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3338 // C++ [over.ics.user]p1:
3339 // If the user-defined conversion is specified by a
3340 // constructor (12.3.1), the initial standard conversion
3341 // sequence converts the source type to the type required by
3342 // the argument of the constructor.
3343 //
3344 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003345 if (isa<InitListExpr>(From)) {
3346 // Initializer lists don't have conversions as such.
3347 User.Before.setAsIdentityConversion();
3348 } else {
3349 if (Best->Conversions[0].isEllipsis())
3350 User.EllipsisConversion = true;
3351 else {
3352 User.Before = Best->Conversions[0].Standard;
3353 User.EllipsisConversion = false;
3354 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003355 }
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003356 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003357 User.ConversionFunction = Constructor;
John McCall30909032011-09-21 08:36:56 +00003358 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003359 User.After.setAsIdentityConversion();
3360 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3361 User.After.setAllToTypes(ToType);
Richard Smith48372b62015-01-27 03:30:40 +00003362 return Result;
David Blaikie8a40f702012-01-17 06:56:22 +00003363 }
3364 if (CXXConversionDecl *Conversion
John McCall5c32be02010-08-24 20:38:10 +00003365 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3366 // C++ [over.ics.user]p1:
3367 //
3368 // [...] If the user-defined conversion is specified by a
3369 // conversion function (12.3.2), the initial standard
3370 // conversion sequence converts the source type to the
3371 // implicit object parameter of the conversion function.
3372 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003373 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003374 User.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00003375 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003376 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00003377
John McCall5c32be02010-08-24 20:38:10 +00003378 // C++ [over.ics.user]p2:
3379 // The second standard conversion sequence converts the
3380 // result of the user-defined conversion to the target type
3381 // for the sequence. Since an implicit conversion sequence
3382 // is an initialization, the special rules for
3383 // initialization by user-defined conversion apply when
3384 // selecting the best user-defined conversion for a
3385 // user-defined conversion sequence (see 13.3.3 and
3386 // 13.3.3.1).
3387 User.After = Best->FinalConversion;
Richard Smith48372b62015-01-27 03:30:40 +00003388 return Result;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003389 }
David Blaikie8a40f702012-01-17 06:56:22 +00003390 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003391
John McCall5c32be02010-08-24 20:38:10 +00003392 case OR_No_Viable_Function:
3393 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003394
John McCall5c32be02010-08-24 20:38:10 +00003395 case OR_Ambiguous:
3396 return OR_Ambiguous;
3397 }
3398
David Blaikie8a40f702012-01-17 06:56:22 +00003399 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003400}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003401
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003402bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00003403Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003404 ImplicitConversionSequence ICS;
Richard Smith100b24a2014-04-17 01:52:14 +00003405 OverloadCandidateSet CandidateSet(From->getExprLoc(),
3406 OverloadCandidateSet::CSK_Normal);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003407 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00003408 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003409 CandidateSet, false, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00003410 if (OvResult == OR_Ambiguous)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003411 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3412 << From->getType() << ToType << From->getSourceRange();
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003413 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
Larisse Voufo70bb43a2013-06-27 03:36:30 +00003414 if (!RequireCompleteType(From->getLocStart(), ToType,
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003415 diag::err_typecheck_nonviable_condition_incomplete,
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003416 From->getType(), From->getSourceRange()))
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003417 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
Nick Lewycky08426e22015-08-25 22:18:46 +00003418 << false << From->getType() << From->getSourceRange() << ToType;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003419 } else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003420 return false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003421 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003422 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003423}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003424
Douglas Gregor2837aa22012-02-22 17:32:19 +00003425/// \brief Compare the user-defined conversion functions or constructors
3426/// of two user-defined conversion sequences to determine whether any ordering
3427/// is possible.
3428static ImplicitConversionSequence::CompareKind
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003429compareConversionFunctions(Sema &S, FunctionDecl *Function1,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003430 FunctionDecl *Function2) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003431 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
Douglas Gregor2837aa22012-02-22 17:32:19 +00003432 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003433
Douglas Gregor2837aa22012-02-22 17:32:19 +00003434 // Objective-C++:
3435 // If both conversion functions are implicitly-declared conversions from
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003436 // a lambda closure type to a function pointer and a block pointer,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003437 // respectively, always prefer the conversion to a function pointer,
3438 // because the function pointer is more lightweight and is more likely
3439 // to keep code working.
Ted Kremenek8d265c22014-04-01 07:23:18 +00003440 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003441 if (!Conv1)
3442 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003443
Douglas Gregor2837aa22012-02-22 17:32:19 +00003444 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3445 if (!Conv2)
3446 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003447
Douglas Gregor2837aa22012-02-22 17:32:19 +00003448 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3449 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3450 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3451 if (Block1 != Block2)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003452 return Block1 ? ImplicitConversionSequence::Worse
3453 : ImplicitConversionSequence::Better;
Douglas Gregor2837aa22012-02-22 17:32:19 +00003454 }
3455
3456 return ImplicitConversionSequence::Indistinguishable;
3457}
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003458
3459static bool hasDeprecatedStringLiteralToCharPtrConversion(
3460 const ImplicitConversionSequence &ICS) {
3461 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3462 (ICS.isUserDefined() &&
3463 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3464}
3465
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003466/// CompareImplicitConversionSequences - Compare two implicit
3467/// conversion sequences to determine whether one is better than the
3468/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00003469static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +00003470CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +00003471 const ImplicitConversionSequence& ICS1,
3472 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003473{
3474 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3475 // conversion sequences (as defined in 13.3.3.1)
3476 // -- a standard conversion sequence (13.3.3.1.1) is a better
3477 // conversion sequence than a user-defined conversion sequence or
3478 // an ellipsis conversion sequence, and
3479 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3480 // conversion sequence than an ellipsis conversion sequence
3481 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00003482 //
John McCall0d1da222010-01-12 00:44:57 +00003483 // C++0x [over.best.ics]p10:
3484 // For the purpose of ranking implicit conversion sequences as
3485 // described in 13.3.3.2, the ambiguous conversion sequence is
3486 // treated as a user-defined sequence that is indistinguishable
3487 // from any other user-defined conversion sequence.
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003488
3489 // String literal to 'char *' conversion has been deprecated in C++03. It has
3490 // been removed from C++11. We still accept this conversion, if it happens at
3491 // the best viable function. Otherwise, this conversion is considered worse
3492 // than ellipsis conversion. Consider this as an extension; this is not in the
3493 // standard. For example:
3494 //
3495 // int &f(...); // #1
3496 // void f(char*); // #2
3497 // void g() { int &r = f("foo"); }
3498 //
3499 // In C++03, we pick #2 as the best viable function.
3500 // In C++11, we pick #1 as the best viable function, because ellipsis
3501 // conversion is better than string-literal to char* conversion (since there
3502 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3503 // convert arguments, #2 would be the best viable function in C++11.
3504 // If the best viable function has this conversion, a warning will be issued
3505 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3506
3507 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3508 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3509 hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3510 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3511 ? ImplicitConversionSequence::Worse
3512 : ImplicitConversionSequence::Better;
3513
Douglas Gregor5ab11652010-04-17 22:01:05 +00003514 if (ICS1.getKindRank() < ICS2.getKindRank())
3515 return ImplicitConversionSequence::Better;
David Blaikie8a40f702012-01-17 06:56:22 +00003516 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor5ab11652010-04-17 22:01:05 +00003517 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003518
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00003519 // The following checks require both conversion sequences to be of
3520 // the same kind.
3521 if (ICS1.getKind() != ICS2.getKind())
3522 return ImplicitConversionSequence::Indistinguishable;
3523
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003524 ImplicitConversionSequence::CompareKind Result =
3525 ImplicitConversionSequence::Indistinguishable;
3526
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003527 // Two implicit conversion sequences of the same form are
3528 // indistinguishable conversion sequences unless one of the
3529 // following rules apply: (C++ 13.3.3.2p3):
Larisse Voufo19d08672015-01-27 18:47:05 +00003530
3531 // List-initialization sequence L1 is a better conversion sequence than
3532 // list-initialization sequence L2 if:
3533 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3534 // if not that,
NAKAMURA Takumib01d86b2015-02-25 11:02:00 +00003535 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
Larisse Voufo19d08672015-01-27 18:47:05 +00003536 // and N1 is smaller than N2.,
3537 // even if one of the other rules in this paragraph would otherwise apply.
3538 if (!ICS1.isBad()) {
3539 if (ICS1.isStdInitializerListElement() &&
3540 !ICS2.isStdInitializerListElement())
3541 return ImplicitConversionSequence::Better;
3542 if (!ICS1.isStdInitializerListElement() &&
3543 ICS2.isStdInitializerListElement())
3544 return ImplicitConversionSequence::Worse;
3545 }
3546
John McCall0d1da222010-01-12 00:44:57 +00003547 if (ICS1.isStandard())
Larisse Voufo19d08672015-01-27 18:47:05 +00003548 // Standard conversion sequence S1 is a better conversion sequence than
3549 // standard conversion sequence S2 if [...]
Richard Smith0f59cb32015-12-18 21:45:41 +00003550 Result = CompareStandardConversionSequences(S, Loc,
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003551 ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00003552 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003553 // User-defined conversion sequence U1 is a better conversion
3554 // sequence than another user-defined conversion sequence U2 if
3555 // they contain the same user-defined conversion function or
3556 // constructor and if the second standard conversion sequence of
3557 // U1 is better than the second standard conversion sequence of
3558 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00003559 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003560 ICS2.UserDefined.ConversionFunction)
Richard Smith0f59cb32015-12-18 21:45:41 +00003561 Result = CompareStandardConversionSequences(S, Loc,
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003562 ICS1.UserDefined.After,
3563 ICS2.UserDefined.After);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003564 else
3565 Result = compareConversionFunctions(S,
3566 ICS1.UserDefined.ConversionFunction,
3567 ICS2.UserDefined.ConversionFunction);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003568 }
3569
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003570 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003571}
3572
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003573static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3574 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3575 Qualifiers Quals;
3576 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003577 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003578 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003579
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003580 return Context.hasSameUnqualifiedType(T1, T2);
3581}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003582
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003583// Per 13.3.3.2p3, compare the given standard conversion sequences to
3584// determine if one is a proper subset of the other.
3585static ImplicitConversionSequence::CompareKind
3586compareStandardConversionSubsets(ASTContext &Context,
3587 const StandardConversionSequence& SCS1,
3588 const StandardConversionSequence& SCS2) {
3589 ImplicitConversionSequence::CompareKind Result
3590 = ImplicitConversionSequence::Indistinguishable;
3591
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003592 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00003593 // any non-identity conversion sequence
Douglas Gregor377c1092011-06-05 06:15:20 +00003594 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3595 return ImplicitConversionSequence::Better;
3596 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3597 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003598
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003599 if (SCS1.Second != SCS2.Second) {
3600 if (SCS1.Second == ICK_Identity)
3601 Result = ImplicitConversionSequence::Better;
3602 else if (SCS2.Second == ICK_Identity)
3603 Result = ImplicitConversionSequence::Worse;
3604 else
3605 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003606 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003607 return ImplicitConversionSequence::Indistinguishable;
3608
3609 if (SCS1.Third == SCS2.Third) {
3610 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3611 : ImplicitConversionSequence::Indistinguishable;
3612 }
3613
3614 if (SCS1.Third == ICK_Identity)
3615 return Result == ImplicitConversionSequence::Worse
3616 ? ImplicitConversionSequence::Indistinguishable
3617 : ImplicitConversionSequence::Better;
3618
3619 if (SCS2.Third == ICK_Identity)
3620 return Result == ImplicitConversionSequence::Better
3621 ? ImplicitConversionSequence::Indistinguishable
3622 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003623
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003624 return ImplicitConversionSequence::Indistinguishable;
3625}
3626
Douglas Gregore696ebb2011-01-26 14:52:12 +00003627/// \brief Determine whether one of the given reference bindings is better
3628/// than the other based on what kind of bindings they are.
Richard Smith19172c42014-07-14 02:28:44 +00003629static bool
3630isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3631 const StandardConversionSequence &SCS2) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003632 // C++0x [over.ics.rank]p3b4:
3633 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3634 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003635 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00003636 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003637 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00003638 // reference*.
3639 //
3640 // FIXME: Rvalue references. We're going rogue with the above edits,
3641 // because the semantics in the current C++0x working paper (N3225 at the
3642 // time of this writing) break the standard definition of std::forward
3643 // and std::reference_wrapper when dealing with references to functions.
3644 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00003645 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3646 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3647 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003648
Douglas Gregore696ebb2011-01-26 14:52:12 +00003649 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3650 SCS2.IsLvalueReference) ||
3651 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
Richard Smith19172c42014-07-14 02:28:44 +00003652 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
Douglas Gregore696ebb2011-01-26 14:52:12 +00003653}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003654
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003655/// CompareStandardConversionSequences - Compare two standard
3656/// conversion sequences to determine whether one is better than the
3657/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00003658static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +00003659CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +00003660 const StandardConversionSequence& SCS1,
3661 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003662{
3663 // Standard conversion sequence S1 is a better conversion sequence
3664 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3665
3666 // -- S1 is a proper subsequence of S2 (comparing the conversion
3667 // sequences in the canonical form defined by 13.3.3.1.1,
3668 // excluding any Lvalue Transformation; the identity conversion
3669 // sequence is considered to be a subsequence of any
3670 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003671 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00003672 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003673 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003674
3675 // -- the rank of S1 is better than the rank of S2 (by the rules
3676 // defined below), or, if not that,
3677 ImplicitConversionRank Rank1 = SCS1.getRank();
3678 ImplicitConversionRank Rank2 = SCS2.getRank();
3679 if (Rank1 < Rank2)
3680 return ImplicitConversionSequence::Better;
3681 else if (Rank2 < Rank1)
3682 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003683
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003684 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3685 // are indistinguishable unless one of the following rules
3686 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00003687
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003688 // A conversion that is not a conversion of a pointer, or
3689 // pointer to member, to bool is better than another conversion
3690 // that is such a conversion.
3691 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3692 return SCS2.isPointerConversionToBool()
3693 ? ImplicitConversionSequence::Better
3694 : ImplicitConversionSequence::Worse;
3695
Douglas Gregor5c407d92008-10-23 00:40:37 +00003696 // C++ [over.ics.rank]p4b2:
3697 //
3698 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003699 // conversion of B* to A* is better than conversion of B* to
3700 // void*, and conversion of A* to void* is better than conversion
3701 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00003702 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003703 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00003704 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003705 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003706 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3707 // Exactly one of the conversion sequences is a conversion to
3708 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003709 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3710 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003711 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3712 // Neither conversion sequence converts to a void pointer; compare
3713 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003714 if (ImplicitConversionSequence::CompareKind DerivedCK
Richard Smith0f59cb32015-12-18 21:45:41 +00003715 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003716 return DerivedCK;
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003717 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3718 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003719 // Both conversion sequences are conversions to void
3720 // pointers. Compare the source types to determine if there's an
3721 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00003722 QualType FromType1 = SCS1.getFromType();
3723 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003724
3725 // Adjust the types we're converting from via the array-to-pointer
3726 // conversion, if we need to.
3727 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003728 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003729 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003730 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003731
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003732 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3733 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003734
Richard Smith0f59cb32015-12-18 21:45:41 +00003735 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003736 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00003737 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003738 return ImplicitConversionSequence::Worse;
3739
3740 // Objective-C++: If one interface is more specific than the
3741 // other, it is the better one.
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003742 const ObjCObjectPointerType* FromObjCPtr1
3743 = FromType1->getAs<ObjCObjectPointerType>();
3744 const ObjCObjectPointerType* FromObjCPtr2
3745 = FromType2->getAs<ObjCObjectPointerType>();
3746 if (FromObjCPtr1 && FromObjCPtr2) {
3747 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3748 FromObjCPtr2);
3749 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3750 FromObjCPtr1);
3751 if (AssignLeft != AssignRight) {
3752 return AssignLeft? ImplicitConversionSequence::Better
3753 : ImplicitConversionSequence::Worse;
3754 }
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003755 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003756 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003757
3758 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3759 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00003760 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00003761 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003762 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003763
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003764 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003765 // Check for a better reference binding based on the kind of bindings.
3766 if (isBetterReferenceBindingKind(SCS1, SCS2))
3767 return ImplicitConversionSequence::Better;
3768 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3769 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003770
Sebastian Redlb28b4072009-03-22 23:49:27 +00003771 // C++ [over.ics.rank]p3b4:
3772 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3773 // which the references refer are the same type except for
3774 // top-level cv-qualifiers, and the type to which the reference
3775 // initialized by S2 refers is more cv-qualified than the type
3776 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003777 QualType T1 = SCS1.getToType(2);
3778 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003779 T1 = S.Context.getCanonicalType(T1);
3780 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003781 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003782 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3783 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003784 if (UnqualT1 == UnqualT2) {
John McCall31168b02011-06-15 23:02:42 +00003785 // Objective-C++ ARC: If the references refer to objects with different
3786 // lifetimes, prefer bindings that don't change lifetime.
3787 if (SCS1.ObjCLifetimeConversionBinding !=
3788 SCS2.ObjCLifetimeConversionBinding) {
3789 return SCS1.ObjCLifetimeConversionBinding
3790 ? ImplicitConversionSequence::Worse
3791 : ImplicitConversionSequence::Better;
3792 }
3793
Chandler Carruth8e543b32010-12-12 08:17:55 +00003794 // If the type is an array type, promote the element qualifiers to the
3795 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003796 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003797 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003798 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003799 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003800 if (T2.isMoreQualifiedThan(T1))
3801 return ImplicitConversionSequence::Better;
3802 else if (T1.isMoreQualifiedThan(T2))
John McCall31168b02011-06-15 23:02:42 +00003803 return ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003804 }
3805 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003806
Francois Pichet08d2fa02011-09-18 21:37:37 +00003807 // In Microsoft mode, prefer an integral conversion to a
3808 // floating-to-integral conversion if the integral conversion
3809 // is between types of the same size.
3810 // For example:
3811 // void f(float);
3812 // void f(int);
3813 // int main {
3814 // long a;
3815 // f(a);
3816 // }
3817 // Here, MSVC will call f(int) instead of generating a compile error
3818 // as clang will do in standard mode.
Alp Tokerbfa39342014-01-14 12:51:41 +00003819 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3820 SCS2.Second == ICK_Floating_Integral &&
Francois Pichet08d2fa02011-09-18 21:37:37 +00003821 S.Context.getTypeSize(SCS1.getFromType()) ==
Alp Tokerbfa39342014-01-14 12:51:41 +00003822 S.Context.getTypeSize(SCS1.getToType(2)))
Francois Pichet08d2fa02011-09-18 21:37:37 +00003823 return ImplicitConversionSequence::Better;
3824
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003825 return ImplicitConversionSequence::Indistinguishable;
3826}
3827
3828/// CompareQualificationConversions - Compares two standard conversion
3829/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00003830/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
Richard Smith17c00b42014-11-12 01:24:00 +00003831static ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003832CompareQualificationConversions(Sema &S,
3833 const StandardConversionSequence& SCS1,
3834 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00003835 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003836 // -- S1 and S2 differ only in their qualification conversion and
3837 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3838 // cv-qualification signature of type T1 is a proper subset of
3839 // the cv-qualification signature of type T2, and S1 is not the
3840 // deprecated string literal array-to-pointer conversion (4.2).
3841 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3842 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3843 return ImplicitConversionSequence::Indistinguishable;
3844
3845 // FIXME: the example in the standard doesn't use a qualification
3846 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003847 QualType T1 = SCS1.getToType(2);
3848 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003849 T1 = S.Context.getCanonicalType(T1);
3850 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003851 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003852 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3853 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003854
3855 // If the types are the same, we won't learn anything by unwrapped
3856 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003857 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003858 return ImplicitConversionSequence::Indistinguishable;
3859
Chandler Carruth607f38e2009-12-29 07:16:59 +00003860 // If the type is an array type, promote the element qualifiers to the type
3861 // for comparison.
3862 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003863 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003864 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003865 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003866
Mike Stump11289f42009-09-09 15:08:12 +00003867 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003868 = ImplicitConversionSequence::Indistinguishable;
John McCall31168b02011-06-15 23:02:42 +00003869
3870 // Objective-C++ ARC:
3871 // Prefer qualification conversions not involving a change in lifetime
3872 // to qualification conversions that do not change lifetime.
3873 if (SCS1.QualificationIncludesObjCLifetime !=
3874 SCS2.QualificationIncludesObjCLifetime) {
3875 Result = SCS1.QualificationIncludesObjCLifetime
3876 ? ImplicitConversionSequence::Worse
3877 : ImplicitConversionSequence::Better;
3878 }
3879
John McCall5c32be02010-08-24 20:38:10 +00003880 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003881 // Within each iteration of the loop, we check the qualifiers to
3882 // determine if this still looks like a qualification
3883 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003884 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003885 // until there are no more pointers or pointers-to-members left
3886 // to unwrap. This essentially mimics what
3887 // IsQualificationConversion does, but here we're checking for a
3888 // strict subset of qualifiers.
3889 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3890 // The qualifiers are the same, so this doesn't tell us anything
3891 // about how the sequences rank.
3892 ;
3893 else if (T2.isMoreQualifiedThan(T1)) {
3894 // T1 has fewer qualifiers, so it could be the better sequence.
3895 if (Result == ImplicitConversionSequence::Worse)
3896 // Neither has qualifiers that are a subset of the other's
3897 // qualifiers.
3898 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003899
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003900 Result = ImplicitConversionSequence::Better;
3901 } else if (T1.isMoreQualifiedThan(T2)) {
3902 // T2 has fewer qualifiers, so it could be the better sequence.
3903 if (Result == ImplicitConversionSequence::Better)
3904 // Neither has qualifiers that are a subset of the other's
3905 // qualifiers.
3906 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003907
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003908 Result = ImplicitConversionSequence::Worse;
3909 } else {
3910 // Qualifiers are disjoint.
3911 return ImplicitConversionSequence::Indistinguishable;
3912 }
3913
3914 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00003915 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003916 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003917 }
3918
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003919 // Check that the winning standard conversion sequence isn't using
3920 // the deprecated string literal array to pointer conversion.
3921 switch (Result) {
3922 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003923 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003924 Result = ImplicitConversionSequence::Indistinguishable;
3925 break;
3926
3927 case ImplicitConversionSequence::Indistinguishable:
3928 break;
3929
3930 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003931 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003932 Result = ImplicitConversionSequence::Indistinguishable;
3933 break;
3934 }
3935
3936 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003937}
3938
Douglas Gregor5c407d92008-10-23 00:40:37 +00003939/// CompareDerivedToBaseConversions - Compares two standard conversion
3940/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00003941/// various kinds of derived-to-base conversions (C++
3942/// [over.ics.rank]p4b3). As part of these checks, we also look at
3943/// conversions between Objective-C interface types.
Richard Smith17c00b42014-11-12 01:24:00 +00003944static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +00003945CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +00003946 const StandardConversionSequence& SCS1,
3947 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00003948 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003949 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00003950 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003951 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003952
3953 // Adjust the types we're converting from via the array-to-pointer
3954 // conversion, if we need to.
3955 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003956 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003957 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003958 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003959
3960 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00003961 FromType1 = S.Context.getCanonicalType(FromType1);
3962 ToType1 = S.Context.getCanonicalType(ToType1);
3963 FromType2 = S.Context.getCanonicalType(FromType2);
3964 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003965
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003966 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00003967 //
3968 // If class B is derived directly or indirectly from class A and
3969 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00003970 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003971 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00003972 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00003973 SCS2.Second == ICK_Pointer_Conversion &&
3974 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3975 FromType1->isPointerType() && FromType2->isPointerType() &&
3976 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003977 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003978 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00003979 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003980 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003981 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003982 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003983 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003984 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00003985
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003986 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00003987 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00003988 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003989 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00003990 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003991 return ImplicitConversionSequence::Worse;
3992 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003993
3994 // -- conversion of B* to A* is better than conversion of C* to A*,
3995 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00003996 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003997 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00003998 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003999 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00004000 }
4001 } else if (SCS1.Second == ICK_Pointer_Conversion &&
4002 SCS2.Second == ICK_Pointer_Conversion) {
4003 const ObjCObjectPointerType *FromPtr1
4004 = FromType1->getAs<ObjCObjectPointerType>();
4005 const ObjCObjectPointerType *FromPtr2
4006 = FromType2->getAs<ObjCObjectPointerType>();
4007 const ObjCObjectPointerType *ToPtr1
4008 = ToType1->getAs<ObjCObjectPointerType>();
4009 const ObjCObjectPointerType *ToPtr2
4010 = ToType2->getAs<ObjCObjectPointerType>();
4011
4012 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4013 // Apply the same conversion ranking rules for Objective-C pointer types
4014 // that we do for C++ pointers to class types. However, we employ the
4015 // Objective-C pseudo-subtyping relationship used for assignment of
4016 // Objective-C pointer types.
4017 bool FromAssignLeft
4018 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4019 bool FromAssignRight
4020 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4021 bool ToAssignLeft
4022 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4023 bool ToAssignRight
4024 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4025
4026 // A conversion to an a non-id object pointer type or qualified 'id'
4027 // type is better than a conversion to 'id'.
4028 if (ToPtr1->isObjCIdType() &&
4029 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4030 return ImplicitConversionSequence::Worse;
4031 if (ToPtr2->isObjCIdType() &&
4032 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4033 return ImplicitConversionSequence::Better;
4034
4035 // A conversion to a non-id object pointer type is better than a
4036 // conversion to a qualified 'id' type
4037 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4038 return ImplicitConversionSequence::Worse;
4039 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4040 return ImplicitConversionSequence::Better;
4041
4042 // A conversion to an a non-Class object pointer type or qualified 'Class'
4043 // type is better than a conversion to 'Class'.
4044 if (ToPtr1->isObjCClassType() &&
4045 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4046 return ImplicitConversionSequence::Worse;
4047 if (ToPtr2->isObjCClassType() &&
4048 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4049 return ImplicitConversionSequence::Better;
4050
4051 // A conversion to a non-Class object pointer type is better than a
4052 // conversion to a qualified 'Class' type.
4053 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4054 return ImplicitConversionSequence::Worse;
4055 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4056 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00004057
Douglas Gregor058d3de2011-01-31 18:51:41 +00004058 // -- "conversion of C* to B* is better than conversion of C* to A*,"
4059 if (S.Context.hasSameType(FromType1, FromType2) &&
4060 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4061 (ToAssignLeft != ToAssignRight))
4062 return ToAssignLeft? ImplicitConversionSequence::Worse
4063 : ImplicitConversionSequence::Better;
4064
4065 // -- "conversion of B* to A* is better than conversion of C* to A*,"
4066 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4067 (FromAssignLeft != FromAssignRight))
4068 return FromAssignLeft? ImplicitConversionSequence::Better
4069 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004070 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00004071 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00004072
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00004073 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004074 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4075 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4076 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004077 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004078 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004079 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004080 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004081 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004082 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004083 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004084 ToType2->getAs<MemberPointerType>();
4085 const Type *FromPointeeType1 = FromMemPointer1->getClass();
4086 const Type *ToPointeeType1 = ToMemPointer1->getClass();
4087 const Type *FromPointeeType2 = FromMemPointer2->getClass();
4088 const Type *ToPointeeType2 = ToMemPointer2->getClass();
4089 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4090 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4091 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4092 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00004093 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004094 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004095 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004096 return ImplicitConversionSequence::Worse;
Richard Smith0f59cb32015-12-18 21:45:41 +00004097 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004098 return ImplicitConversionSequence::Better;
4099 }
4100 // conversion of B::* to C::* is better than conversion of A::* to C::*
4101 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004102 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004103 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004104 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004105 return ImplicitConversionSequence::Worse;
4106 }
4107 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004108
Douglas Gregor5ab11652010-04-17 22:01:05 +00004109 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00004110 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00004111 // -- binding of an expression of type C to a reference of type
4112 // B& is better than binding an expression of type C to a
4113 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00004114 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4115 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004116 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004117 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004118 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004119 return ImplicitConversionSequence::Worse;
4120 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004121
Douglas Gregor2fe98832008-11-03 19:09:14 +00004122 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00004123 // -- binding of an expression of type B to a reference of type
4124 // A& is better than binding an expression of type C to a
4125 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00004126 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4127 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004128 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004129 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004130 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004131 return ImplicitConversionSequence::Worse;
4132 }
4133 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004134
Douglas Gregor5c407d92008-10-23 00:40:37 +00004135 return ImplicitConversionSequence::Indistinguishable;
4136}
4137
Douglas Gregor45bb4832013-03-26 23:36:30 +00004138/// \brief Determine whether the given type is valid, e.g., it is not an invalid
4139/// C++ class.
4140static bool isTypeValid(QualType T) {
4141 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4142 return !Record->isInvalidDecl();
4143
4144 return true;
4145}
4146
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004147/// CompareReferenceRelationship - Compare the two types T1 and T2 to
4148/// determine whether they are reference-related,
4149/// reference-compatible, reference-compatible with added
4150/// qualification, or incompatible, for use in C++ initialization by
4151/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4152/// type, and the first type (T1) is the pointee type of the reference
4153/// type being initialized.
4154Sema::ReferenceCompareResult
4155Sema::CompareReferenceRelationship(SourceLocation Loc,
4156 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004157 bool &DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004158 bool &ObjCConversion,
4159 bool &ObjCLifetimeConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004160 assert(!OrigT1->isReferenceType() &&
4161 "T1 must be the pointee type of the reference type");
4162 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4163
4164 QualType T1 = Context.getCanonicalType(OrigT1);
4165 QualType T2 = Context.getCanonicalType(OrigT2);
4166 Qualifiers T1Quals, T2Quals;
4167 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4168 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4169
4170 // C++ [dcl.init.ref]p4:
4171 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4172 // reference-related to "cv2 T2" if T1 is the same type as T2, or
4173 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004174 DerivedToBase = false;
4175 ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004176 ObjCLifetimeConversion = false;
Richard Smith1be59c52016-10-22 01:32:19 +00004177 QualType ConvertedT2;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004178 if (UnqualT1 == UnqualT2) {
4179 // Nothing to do.
Richard Smithdb0ac552015-12-18 22:40:25 +00004180 } else if (isCompleteType(Loc, OrigT2) &&
Douglas Gregor45bb4832013-03-26 23:36:30 +00004181 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00004182 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004183 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004184 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4185 UnqualT2->isObjCObjectOrInterfaceType() &&
4186 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4187 ObjCConversion = true;
Richard Smith1be59c52016-10-22 01:32:19 +00004188 else if (UnqualT2->isFunctionType() &&
4189 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2))
4190 // C++1z [dcl.init.ref]p4:
4191 // cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept
4192 // function" and T1 is "function"
4193 //
4194 // We extend this to also apply to 'noreturn', so allow any function
4195 // conversion between function types.
4196 return Ref_Compatible;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004197 else
4198 return Ref_Incompatible;
4199
4200 // At this point, we know that T1 and T2 are reference-related (at
4201 // least).
4202
4203 // If the type is an array type, promote the element qualifiers to the type
4204 // for comparison.
4205 if (isa<ArrayType>(T1) && T1Quals)
4206 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4207 if (isa<ArrayType>(T2) && T2Quals)
4208 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4209
4210 // C++ [dcl.init.ref]p4:
4211 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4212 // reference-related to T2 and cv1 is the same cv-qualification
4213 // as, or greater cv-qualification than, cv2. For purposes of
4214 // overload resolution, cases for which cv1 is greater
4215 // cv-qualification than cv2 are identified as
4216 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregord517d552011-04-28 17:56:11 +00004217 //
4218 // Note that we also require equivalence of Objective-C GC and address-space
4219 // qualifiers when performing these computations, so that e.g., an int in
4220 // address space 1 is not reference-compatible with an int in address
4221 // space 2.
John McCall31168b02011-06-15 23:02:42 +00004222 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4223 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00004224 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4225 ObjCLifetimeConversion = true;
4226
John McCall31168b02011-06-15 23:02:42 +00004227 T1Quals.removeObjCLifetime();
4228 T2Quals.removeObjCLifetime();
John McCall31168b02011-06-15 23:02:42 +00004229 }
4230
Andrey Bokhanko45d41322016-05-11 18:38:21 +00004231 // MS compiler ignores __unaligned qualifier for references; do the same.
4232 T1Quals.removeUnaligned();
4233 T2Quals.removeUnaligned();
4234
Richard Smithce766292016-10-21 23:01:55 +00004235 if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004236 return Ref_Compatible;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004237 else
4238 return Ref_Related;
4239}
4240
Douglas Gregor836a7e82010-08-11 02:15:33 +00004241/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00004242/// with DeclType. Return true if something definite is found.
4243static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00004244FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4245 QualType DeclType, SourceLocation DeclLoc,
4246 Expr *Init, QualType T2, bool AllowRvalues,
4247 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004248 assert(T2->isRecordType() && "Can only find conversions of record types.");
4249 CXXRecordDecl *T2RecordDecl
4250 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4251
Richard Smith100b24a2014-04-17 01:52:14 +00004252 OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal);
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004253 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4254 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004255 NamedDecl *D = *I;
4256 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4257 if (isa<UsingShadowDecl>(D))
4258 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4259
4260 FunctionTemplateDecl *ConvTemplate
4261 = dyn_cast<FunctionTemplateDecl>(D);
4262 CXXConversionDecl *Conv;
4263 if (ConvTemplate)
4264 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4265 else
4266 Conv = cast<CXXConversionDecl>(D);
4267
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004268 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00004269 // explicit conversions, skip it.
4270 if (!AllowExplicit && Conv->isExplicit())
4271 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004272
Douglas Gregor836a7e82010-08-11 02:15:33 +00004273 if (AllowRvalues) {
4274 bool DerivedToBase = false;
4275 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004276 bool ObjCLifetimeConversion = false;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004277
4278 // If we are initializing an rvalue reference, don't permit conversion
4279 // functions that return lvalues.
4280 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4281 const ReferenceType *RefType
4282 = Conv->getConversionType()->getAs<LValueReferenceType>();
4283 if (RefType && !RefType->getPointeeType()->isFunctionType())
4284 continue;
4285 }
4286
Douglas Gregor836a7e82010-08-11 02:15:33 +00004287 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00004288 S.CompareReferenceRelationship(
4289 DeclLoc,
4290 Conv->getConversionType().getNonReferenceType()
4291 .getUnqualifiedType(),
4292 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCall31168b02011-06-15 23:02:42 +00004293 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth8e543b32010-12-12 08:17:55 +00004294 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00004295 continue;
4296 } else {
4297 // If the conversion function doesn't return a reference type,
4298 // it can't be considered for this conversion. An rvalue reference
4299 // is only acceptable if its referencee is a function type.
4300
4301 const ReferenceType *RefType =
4302 Conv->getConversionType()->getAs<ReferenceType>();
4303 if (!RefType ||
4304 (!RefType->isLValueReferenceType() &&
4305 !RefType->getPointeeType()->isFunctionType()))
4306 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00004307 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004308
Douglas Gregor836a7e82010-08-11 02:15:33 +00004309 if (ConvTemplate)
4310 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004311 Init, DeclType, CandidateSet,
4312 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor836a7e82010-08-11 02:15:33 +00004313 else
4314 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004315 DeclType, CandidateSet,
4316 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redld92badf2010-06-30 18:13:39 +00004317 }
4318
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004319 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4320
Sebastian Redld92badf2010-06-30 18:13:39 +00004321 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00004322 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004323 case OR_Success:
4324 // C++ [over.ics.ref]p1:
4325 //
4326 // [...] If the parameter binds directly to the result of
4327 // applying a conversion function to the argument
4328 // expression, the implicit conversion sequence is a
4329 // user-defined conversion sequence (13.3.3.1.2), with the
4330 // second standard conversion sequence either an identity
4331 // conversion or, if the conversion function returns an
4332 // entity of a type that is a derived class of the parameter
4333 // type, a derived-to-base Conversion.
4334 if (!Best->FinalConversion.DirectBinding)
4335 return false;
4336
4337 ICS.setUserDefined();
4338 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4339 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004340 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redld92badf2010-06-30 18:13:39 +00004341 ICS.UserDefined.ConversionFunction = Best->Function;
John McCall30909032011-09-21 08:36:56 +00004342 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redld92badf2010-06-30 18:13:39 +00004343 ICS.UserDefined.EllipsisConversion = false;
4344 assert(ICS.UserDefined.After.ReferenceBinding &&
4345 ICS.UserDefined.After.DirectBinding &&
4346 "Expected a direct reference binding!");
4347 return true;
4348
4349 case OR_Ambiguous:
4350 ICS.setAmbiguous();
4351 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4352 Cand != CandidateSet.end(); ++Cand)
4353 if (Cand->Viable)
Richard Smithc2bebe92016-05-11 20:37:46 +00004354 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
Sebastian Redld92badf2010-06-30 18:13:39 +00004355 return true;
4356
4357 case OR_No_Viable_Function:
4358 case OR_Deleted:
4359 // There was no suitable conversion, or we found a deleted
4360 // conversion; continue with other checks.
4361 return false;
4362 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004363
David Blaikie8a40f702012-01-17 06:56:22 +00004364 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redld92badf2010-06-30 18:13:39 +00004365}
4366
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004367/// \brief Compute an implicit conversion sequence for reference
4368/// initialization.
4369static ImplicitConversionSequence
Sebastian Redldf888642011-12-03 14:54:30 +00004370TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004371 SourceLocation DeclLoc,
4372 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00004373 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004374 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4375
4376 // Most paths end in a failed conversion.
4377 ImplicitConversionSequence ICS;
4378 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4379
4380 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4381 QualType T2 = Init->getType();
4382
4383 // If the initializer is the address of an overloaded function, try
4384 // to resolve the overloaded function. If all goes well, T2 is the
4385 // type of the resulting function.
4386 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4387 DeclAccessPair Found;
4388 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4389 false, Found))
4390 T2 = Fn->getType();
4391 }
4392
4393 // Compute some basic properties of the types and the initializer.
4394 bool isRValRef = DeclType->isRValueReferenceType();
4395 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004396 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004397 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00004398 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004399 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004400 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004401 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004402
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004403
Sebastian Redld92badf2010-06-30 18:13:39 +00004404 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00004405 // A reference to type "cv1 T1" is initialized by an expression
4406 // of type "cv2 T2" as follows:
4407
Sebastian Redld92badf2010-06-30 18:13:39 +00004408 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00004409 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004410 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4411 // reference-compatible with "cv2 T2," or
4412 //
4413 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
Richard Smithce766292016-10-21 23:01:55 +00004414 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004415 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00004416 // When a parameter of reference type binds directly (8.5.3)
4417 // to an argument expression, the implicit conversion sequence
4418 // is the identity conversion, unless the argument expression
4419 // has a type that is a derived class of the parameter type,
4420 // in which case the implicit conversion sequence is a
4421 // derived-to-base Conversion (13.3.3.1).
4422 ICS.setStandard();
4423 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004424 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4425 : ObjCConversion? ICK_Compatible_Conversion
4426 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00004427 ICS.Standard.Third = ICK_Identity;
4428 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4429 ICS.Standard.setToType(0, T2);
4430 ICS.Standard.setToType(1, T1);
4431 ICS.Standard.setToType(2, T1);
4432 ICS.Standard.ReferenceBinding = true;
4433 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004434 ICS.Standard.IsLvalueReference = !isRValRef;
4435 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4436 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004437 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004438 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Craig Topperc3ec1492014-05-26 06:22:03 +00004439 ICS.Standard.CopyConstructor = nullptr;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004440 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004441
Sebastian Redld92badf2010-06-30 18:13:39 +00004442 // Nothing more to do: the inaccessibility/ambiguity check for
4443 // derived-to-base conversions is suppressed when we're
4444 // computing the implicit conversion sequence (C++
4445 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004446 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00004447 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004448
Sebastian Redld92badf2010-06-30 18:13:39 +00004449 // -- has a class type (i.e., T2 is a class type), where T1 is
4450 // not reference-related to T2, and can be implicitly
4451 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4452 // is reference-compatible with "cv3 T3" 92) (this
4453 // conversion is selected by enumerating the applicable
4454 // conversion functions (13.3.1.6) and choosing the best
4455 // one through overload resolution (13.3)),
4456 if (!SuppressUserConversions && T2->isRecordType() &&
Richard Smithdb0ac552015-12-18 22:40:25 +00004457 S.isCompleteType(DeclLoc, T2) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00004458 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00004459 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4460 Init, T2, /*AllowRvalues=*/false,
4461 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00004462 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004463 }
4464 }
4465
Sebastian Redld92badf2010-06-30 18:13:39 +00004466 // -- Otherwise, the reference shall be an lvalue reference to a
4467 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00004468 // shall be an rvalue reference.
Richard Smithce4f6082012-05-24 04:29:20 +00004469 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004470 return ICS;
4471
Douglas Gregorf143cd52011-01-24 16:14:37 +00004472 // -- If the initializer expression
4473 //
4474 // -- is an xvalue, class prvalue, array prvalue or function
John McCall31168b02011-06-15 23:02:42 +00004475 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Richard Smithce766292016-10-21 23:01:55 +00004476 if (RefRelationship == Sema::Ref_Compatible &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004477 (InitCategory.isXValue() ||
Richard Smithce766292016-10-21 23:01:55 +00004478 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4479 (InitCategory.isLValue() && T2->isFunctionType()))) {
Douglas Gregorf143cd52011-01-24 16:14:37 +00004480 ICS.setStandard();
4481 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004482 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004483 : ObjCConversion? ICK_Compatible_Conversion
4484 : ICK_Identity;
4485 ICS.Standard.Third = ICK_Identity;
4486 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4487 ICS.Standard.setToType(0, T2);
4488 ICS.Standard.setToType(1, T1);
4489 ICS.Standard.setToType(2, T1);
4490 ICS.Standard.ReferenceBinding = true;
4491 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4492 // binding unless we're binding to a class prvalue.
4493 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4494 // allow the use of rvalue references in C++98/03 for the benefit of
4495 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004496 ICS.Standard.DirectBinding =
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004497 S.getLangOpts().CPlusPlus11 ||
Richard Smithb94afe12014-07-14 19:54:05 +00004498 !(InitCategory.isPRValue() || T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00004499 ICS.Standard.IsLvalueReference = !isRValRef;
4500 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004501 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00004502 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004503 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Craig Topperc3ec1492014-05-26 06:22:03 +00004504 ICS.Standard.CopyConstructor = nullptr;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004505 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004506 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00004507 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004508
Douglas Gregorf143cd52011-01-24 16:14:37 +00004509 // -- has a class type (i.e., T2 is a class type), where T1 is not
4510 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004511 // an xvalue, class prvalue, or function lvalue of type
4512 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00004513 // "cv3 T3",
4514 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004515 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00004516 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004517 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004518 // class subobject).
4519 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
Richard Smithdb0ac552015-12-18 22:40:25 +00004520 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004521 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4522 Init, T2, /*AllowRvalues=*/true,
4523 AllowExplicit)) {
4524 // In the second case, if the reference is an rvalue reference
4525 // and the second standard conversion sequence of the
4526 // user-defined conversion sequence includes an lvalue-to-rvalue
4527 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004528 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004529 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4530 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4531
Douglas Gregor95273c32011-01-21 16:36:05 +00004532 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00004533 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004534
Richard Smith19172c42014-07-14 02:28:44 +00004535 // A temporary of function type cannot be created; don't even try.
4536 if (T1->isFunctionType())
4537 return ICS;
4538
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004539 // -- Otherwise, a temporary of type "cv1 T1" is created and
4540 // initialized from the initializer expression using the
4541 // rules for a non-reference copy initialization (8.5). The
4542 // reference is then bound to the temporary. If T1 is
4543 // reference-related to T2, cv1 must be the same
4544 // cv-qualification as, or greater cv-qualification than,
4545 // cv2; otherwise, the program is ill-formed.
4546 if (RefRelationship == Sema::Ref_Related) {
4547 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4548 // we would be reference-compatible or reference-compatible with
4549 // added qualification. But that wasn't the case, so the reference
4550 // initialization fails.
John McCall31168b02011-06-15 23:02:42 +00004551 //
4552 // Note that we only want to check address spaces and cvr-qualifiers here.
Andrey Bokhanko45d41322016-05-11 18:38:21 +00004553 // ObjC GC, lifetime and unaligned qualifiers aren't important.
John McCall31168b02011-06-15 23:02:42 +00004554 Qualifiers T1Quals = T1.getQualifiers();
4555 Qualifiers T2Quals = T2.getQualifiers();
4556 T1Quals.removeObjCGCAttr();
4557 T1Quals.removeObjCLifetime();
4558 T2Quals.removeObjCGCAttr();
4559 T2Quals.removeObjCLifetime();
Andrey Bokhanko45d41322016-05-11 18:38:21 +00004560 // MS compiler ignores __unaligned qualifier for references; do the same.
4561 T1Quals.removeUnaligned();
4562 T2Quals.removeUnaligned();
John McCall31168b02011-06-15 23:02:42 +00004563 if (!T1Quals.compatiblyIncludes(T2Quals))
4564 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004565 }
4566
4567 // If at least one of the types is a class type, the types are not
4568 // related, and we aren't allowed any user conversions, the
4569 // reference binding fails. This case is important for breaking
4570 // recursion, since TryImplicitConversion below will attempt to
4571 // create a temporary through the use of a copy constructor.
4572 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4573 (T1->isRecordType() || T2->isRecordType()))
4574 return ICS;
4575
Douglas Gregorcba72b12011-01-21 05:18:22 +00004576 // If T1 is reference-related to T2 and the reference is an rvalue
4577 // reference, the initializer expression shall not be an lvalue.
4578 if (RefRelationship >= Sema::Ref_Related &&
4579 isRValRef && Init->Classify(S.Context).isLValue())
4580 return ICS;
4581
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004582 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004583 // When a parameter of reference type is not bound directly to
4584 // an argument expression, the conversion sequence is the one
4585 // required to convert the argument expression to the
4586 // underlying type of the reference according to
4587 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4588 // to copy-initializing a temporary of the underlying type with
4589 // the argument expression. Any difference in top-level
4590 // cv-qualification is subsumed by the initialization itself
4591 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00004592 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4593 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004594 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004595 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004596 /*AllowObjCWritebackConversion=*/false,
4597 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004598
4599 // Of course, that's still a reference binding.
4600 if (ICS.isStandard()) {
4601 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004602 ICS.Standard.IsLvalueReference = !isRValRef;
Richard Smith19172c42014-07-14 02:28:44 +00004603 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004604 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004605 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004606 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004607 } else if (ICS.isUserDefined()) {
Richard Smith19172c42014-07-14 02:28:44 +00004608 const ReferenceType *LValRefType =
4609 ICS.UserDefined.ConversionFunction->getReturnType()
4610 ->getAs<LValueReferenceType>();
4611
4612 // C++ [over.ics.ref]p3:
4613 // Except for an implicit object parameter, for which see 13.3.1, a
4614 // standard conversion sequence cannot be formed if it requires [...]
4615 // binding an rvalue reference to an lvalue other than a function
4616 // lvalue.
4617 // Note that the function case is not possible here.
4618 if (DeclType->isRValueReferenceType() && LValRefType) {
4619 // FIXME: This is the wrong BadConversionSequence. The problem is binding
4620 // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4621 // reference to an rvalue!
4622 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4623 return ICS;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004624 }
Richard Smith19172c42014-07-14 02:28:44 +00004625
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004626 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004627 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
Richard Smith19172c42014-07-14 02:28:44 +00004628 ICS.UserDefined.After.BindsToFunctionLvalue = false;
4629 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004630 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4631 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004632 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00004633
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004634 return ICS;
4635}
4636
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004637static ImplicitConversionSequence
4638TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4639 bool SuppressUserConversions,
4640 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004641 bool AllowObjCWritebackConversion,
4642 bool AllowExplicit = false);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004643
4644/// TryListConversion - Try to copy-initialize a value of type ToType from the
4645/// initializer list From.
4646static ImplicitConversionSequence
4647TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4648 bool SuppressUserConversions,
4649 bool InOverloadResolution,
4650 bool AllowObjCWritebackConversion) {
4651 // C++11 [over.ics.list]p1:
4652 // When an argument is an initializer list, it is not an expression and
4653 // special rules apply for converting it to a parameter type.
4654
4655 ImplicitConversionSequence Result;
4656 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4657
Sebastian Redl09edce02012-01-23 22:09:39 +00004658 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004659 // initialized from init lists.
Richard Smithdb0ac552015-12-18 22:40:25 +00004660 if (!S.isCompleteType(From->getLocStart(), ToType))
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004661 return Result;
4662
Larisse Voufo19d08672015-01-27 18:47:05 +00004663 // Per DR1467:
4664 // If the parameter type is a class X and the initializer list has a single
4665 // element of type cv U, where U is X or a class derived from X, the
4666 // implicit conversion sequence is the one required to convert the element
4667 // to the parameter type.
4668 //
4669 // Otherwise, if the parameter type is a character array [... ]
4670 // and the initializer list has a single element that is an
4671 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4672 // implicit conversion sequence is the identity conversion.
4673 if (From->getNumInits() == 1) {
4674 if (ToType->isRecordType()) {
4675 QualType InitType = From->getInit(0)->getType();
4676 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00004677 S.IsDerivedFrom(From->getLocStart(), InitType, ToType))
Larisse Voufo19d08672015-01-27 18:47:05 +00004678 return TryCopyInitialization(S, From->getInit(0), ToType,
4679 SuppressUserConversions,
4680 InOverloadResolution,
4681 AllowObjCWritebackConversion);
4682 }
Richard Smith1bbaba82015-01-27 23:23:39 +00004683 // FIXME: Check the other conditions here: array of character type,
4684 // initializer is a string literal.
4685 if (ToType->isArrayType()) {
Larisse Voufo19d08672015-01-27 18:47:05 +00004686 InitializedEntity Entity =
4687 InitializedEntity::InitializeParameter(S.Context, ToType,
4688 /*Consumed=*/false);
4689 if (S.CanPerformCopyInitialization(Entity, From)) {
4690 Result.setStandard();
4691 Result.Standard.setAsIdentityConversion();
4692 Result.Standard.setFromType(ToType);
4693 Result.Standard.setAllToTypes(ToType);
4694 return Result;
4695 }
4696 }
4697 }
4698
4699 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004700 // C++11 [over.ics.list]p2:
4701 // If the parameter type is std::initializer_list<X> or "array of X" and
4702 // all the elements can be implicitly converted to X, the implicit
4703 // conversion sequence is the worst conversion necessary to convert an
4704 // element of the list to X.
Larisse Voufo19d08672015-01-27 18:47:05 +00004705 //
4706 // C++14 [over.ics.list]p3:
NAKAMURA Takumib01d86b2015-02-25 11:02:00 +00004707 // Otherwise, if the parameter type is "array of N X", if the initializer
Larisse Voufo19d08672015-01-27 18:47:05 +00004708 // list has exactly N elements or if it has fewer than N elements and X is
4709 // default-constructible, and if all the elements of the initializer list
4710 // can be implicitly converted to X, the implicit conversion sequence is
4711 // the worst conversion necessary to convert an element of the list to X.
Richard Smith1bbaba82015-01-27 23:23:39 +00004712 //
4713 // FIXME: We're missing a lot of these checks.
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004714 bool toStdInitializerList = false;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004715 QualType X;
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004716 if (ToType->isArrayType())
Richard Smith0db1ea52012-12-09 06:48:56 +00004717 X = S.Context.getAsArrayType(ToType)->getElementType();
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004718 else
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004719 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004720 if (!X.isNull()) {
4721 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4722 Expr *Init = From->getInit(i);
4723 ImplicitConversionSequence ICS =
4724 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4725 InOverloadResolution,
4726 AllowObjCWritebackConversion);
4727 // If a single element isn't convertible, fail.
4728 if (ICS.isBad()) {
4729 Result = ICS;
4730 break;
4731 }
4732 // Otherwise, look for the worst conversion.
4733 if (Result.isBad() ||
Richard Smith0f59cb32015-12-18 21:45:41 +00004734 CompareImplicitConversionSequences(S, From->getLocStart(), ICS,
4735 Result) ==
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004736 ImplicitConversionSequence::Worse)
4737 Result = ICS;
4738 }
Douglas Gregor0f5c1c02012-04-04 23:09:20 +00004739
4740 // For an empty list, we won't have computed any conversion sequence.
4741 // Introduce the identity conversion sequence.
4742 if (From->getNumInits() == 0) {
4743 Result.setStandard();
4744 Result.Standard.setAsIdentityConversion();
4745 Result.Standard.setFromType(ToType);
4746 Result.Standard.setAllToTypes(ToType);
4747 }
4748
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004749 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004750 return Result;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004751 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004752
Larisse Voufo19d08672015-01-27 18:47:05 +00004753 // C++14 [over.ics.list]p4:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004754 // C++11 [over.ics.list]p3:
4755 // Otherwise, if the parameter is a non-aggregate class X and overload
4756 // resolution chooses a single best constructor [...] the implicit
4757 // conversion sequence is a user-defined conversion sequence. If multiple
4758 // constructors are viable but none is better than the others, the
4759 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004760 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4761 // This function can deal with initializer lists.
Richard Smitha93f1022013-09-06 22:30:28 +00004762 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4763 /*AllowExplicit=*/false,
4764 InOverloadResolution, /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004765 AllowObjCWritebackConversion,
4766 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004767 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004768
Larisse Voufo19d08672015-01-27 18:47:05 +00004769 // C++14 [over.ics.list]p5:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004770 // C++11 [over.ics.list]p4:
4771 // Otherwise, if the parameter has an aggregate type which can be
4772 // initialized from the initializer list [...] the implicit conversion
4773 // sequence is a user-defined conversion sequence.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004774 if (ToType->isAggregateType()) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004775 // Type is an aggregate, argument is an init list. At this point it comes
4776 // down to checking whether the initialization works.
4777 // FIXME: Find out whether this parameter is consumed or not.
4778 InitializedEntity Entity =
4779 InitializedEntity::InitializeParameter(S.Context, ToType,
4780 /*Consumed=*/false);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004781 if (S.CanPerformCopyInitialization(Entity, From)) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004782 Result.setUserDefined();
4783 Result.UserDefined.Before.setAsIdentityConversion();
4784 // Initializer lists don't have a type.
4785 Result.UserDefined.Before.setFromType(QualType());
4786 Result.UserDefined.Before.setAllToTypes(QualType());
4787
4788 Result.UserDefined.After.setAsIdentityConversion();
4789 Result.UserDefined.After.setFromType(ToType);
4790 Result.UserDefined.After.setAllToTypes(ToType);
Craig Topperc3ec1492014-05-26 06:22:03 +00004791 Result.UserDefined.ConversionFunction = nullptr;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004792 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004793 return Result;
4794 }
4795
Larisse Voufo19d08672015-01-27 18:47:05 +00004796 // C++14 [over.ics.list]p6:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004797 // C++11 [over.ics.list]p5:
4798 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redldf888642011-12-03 14:54:30 +00004799 if (ToType->isReferenceType()) {
4800 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4801 // mention initializer lists in any way. So we go by what list-
4802 // initialization would do and try to extrapolate from that.
4803
4804 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4805
4806 // If the initializer list has a single element that is reference-related
4807 // to the parameter type, we initialize the reference from that.
4808 if (From->getNumInits() == 1) {
4809 Expr *Init = From->getInit(0);
4810
4811 QualType T2 = Init->getType();
4812
4813 // If the initializer is the address of an overloaded function, try
4814 // to resolve the overloaded function. If all goes well, T2 is the
4815 // type of the resulting function.
4816 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4817 DeclAccessPair Found;
4818 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4819 Init, ToType, false, Found))
4820 T2 = Fn->getType();
4821 }
4822
4823 // Compute some basic properties of the types and the initializer.
4824 bool dummy1 = false;
4825 bool dummy2 = false;
4826 bool dummy3 = false;
4827 Sema::ReferenceCompareResult RefRelationship
4828 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4829 dummy2, dummy3);
4830
Richard Smith4d2bbd72013-09-06 01:22:42 +00004831 if (RefRelationship >= Sema::Ref_Related) {
Richard Smitha93f1022013-09-06 22:30:28 +00004832 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4833 SuppressUserConversions,
4834 /*AllowExplicit=*/false);
Richard Smith4d2bbd72013-09-06 01:22:42 +00004835 }
Sebastian Redldf888642011-12-03 14:54:30 +00004836 }
4837
4838 // Otherwise, we bind the reference to a temporary created from the
4839 // initializer list.
4840 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4841 InOverloadResolution,
4842 AllowObjCWritebackConversion);
4843 if (Result.isFailure())
4844 return Result;
4845 assert(!Result.isEllipsis() &&
4846 "Sub-initialization cannot result in ellipsis conversion.");
4847
4848 // Can we even bind to a temporary?
4849 if (ToType->isRValueReferenceType() ||
4850 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4851 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4852 Result.UserDefined.After;
4853 SCS.ReferenceBinding = true;
4854 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4855 SCS.BindsToRvalue = true;
4856 SCS.BindsToFunctionLvalue = false;
4857 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4858 SCS.ObjCLifetimeConversionBinding = false;
4859 } else
4860 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4861 From, ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004862 return Result;
Sebastian Redldf888642011-12-03 14:54:30 +00004863 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004864
Larisse Voufo19d08672015-01-27 18:47:05 +00004865 // C++14 [over.ics.list]p7:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004866 // C++11 [over.ics.list]p6:
4867 // Otherwise, if the parameter type is not a class:
4868 if (!ToType->isRecordType()) {
Larisse Voufo19d08672015-01-27 18:47:05 +00004869 // - if the initializer list has one element that is not itself an
4870 // initializer list, the implicit conversion sequence is the one
4871 // required to convert the element to the parameter type.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004872 unsigned NumInits = From->getNumInits();
Richard Smith1bbaba82015-01-27 23:23:39 +00004873 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004874 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4875 SuppressUserConversions,
4876 InOverloadResolution,
4877 AllowObjCWritebackConversion);
4878 // - if the initializer list has no elements, the implicit conversion
4879 // sequence is the identity conversion.
4880 else if (NumInits == 0) {
4881 Result.setStandard();
4882 Result.Standard.setAsIdentityConversion();
John McCallb73bc9a2012-04-04 02:40:27 +00004883 Result.Standard.setFromType(ToType);
4884 Result.Standard.setAllToTypes(ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004885 }
4886 return Result;
4887 }
4888
Larisse Voufo19d08672015-01-27 18:47:05 +00004889 // C++14 [over.ics.list]p8:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004890 // C++11 [over.ics.list]p7:
4891 // In all cases other than those enumerated above, no conversion is possible
4892 return Result;
4893}
4894
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004895/// TryCopyInitialization - Try to copy-initialize a value of type
4896/// ToType from the expression From. Return the implicit conversion
4897/// sequence required to pass this argument, which may be a bad
4898/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00004899/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00004900/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004901static ImplicitConversionSequence
4902TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004903 bool SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004904 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004905 bool AllowObjCWritebackConversion,
4906 bool AllowExplicit) {
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004907 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4908 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4909 InOverloadResolution,AllowObjCWritebackConversion);
4910
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004911 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004912 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004913 /*FIXME:*/From->getLocStart(),
4914 SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004915 AllowExplicit);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004916
John McCall5c32be02010-08-24 20:38:10 +00004917 return TryImplicitConversion(S, From, ToType,
4918 SuppressUserConversions,
4919 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004920 InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00004921 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004922 AllowObjCWritebackConversion,
4923 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004924}
4925
Anna Zaks1b068122011-07-28 19:46:48 +00004926static bool TryCopyInitialization(const CanQualType FromQTy,
4927 const CanQualType ToQTy,
4928 Sema &S,
4929 SourceLocation Loc,
4930 ExprValueKind FromVK) {
4931 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4932 ImplicitConversionSequence ICS =
4933 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4934
4935 return !ICS.isBad();
4936}
4937
Douglas Gregor436424c2008-11-18 23:14:02 +00004938/// TryObjectArgumentInitialization - Try to initialize the object
4939/// parameter of the given member function (@c Method) from the
4940/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00004941static ImplicitConversionSequence
Richard Smith0f59cb32015-12-18 21:45:41 +00004942TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004943 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00004944 CXXMethodDecl *Method,
4945 CXXRecordDecl *ActingContext) {
4946 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00004947 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4948 // const volatile object.
4949 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4950 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00004951 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00004952
4953 // Set up the conversion sequence as a "bad" conversion, to allow us
4954 // to exit early.
4955 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00004956
4957 // We need to have an object of class type.
Douglas Gregor02824322011-01-26 19:30:28 +00004958 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004959 FromType = PT->getPointeeType();
4960
Douglas Gregor02824322011-01-26 19:30:28 +00004961 // When we had a pointer, it's implicitly dereferenced, so we
4962 // better have an lvalue.
4963 assert(FromClassification.isLValue());
4964 }
4965
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004966 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00004967
Douglas Gregor02824322011-01-26 19:30:28 +00004968 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004969 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00004970 // parameter is
4971 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004972 // - "lvalue reference to cv X" for functions declared without a
4973 // ref-qualifier or with the & ref-qualifier
4974 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00004975 // ref-qualifier
4976 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004977 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00004978 // cv-qualification on the member function declaration.
4979 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004980 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor02824322011-01-26 19:30:28 +00004981 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00004982 // (C++ [over.match.funcs]p5). We perform a simplified version of
4983 // reference binding here, that allows class rvalues to bind to
4984 // non-constant references.
4985
Douglas Gregor02824322011-01-26 19:30:28 +00004986 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00004987 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004988 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004989 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00004990 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00004991 ICS.setBad(BadConversionSequence::bad_qualifiers,
Richard Smith03c66d32013-01-26 02:07:32 +00004992 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004993 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004994 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004995
4996 // Check that we have either the same type or a derived type. It
4997 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00004998 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00004999 ImplicitConversionKind SecondKind;
5000 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5001 SecondKind = ICK_Identity;
Richard Smith0f59cb32015-12-18 21:45:41 +00005002 } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00005003 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00005004 else {
John McCall65eb8792010-02-25 01:37:24 +00005005 ICS.setBad(BadConversionSequence::unrelated_class,
5006 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00005007 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00005008 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005009
Douglas Gregor02824322011-01-26 19:30:28 +00005010 // Check the ref-qualifier.
5011 switch (Method->getRefQualifier()) {
5012 case RQ_None:
5013 // Do nothing; we don't care about lvalueness or rvalueness.
5014 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005015
Douglas Gregor02824322011-01-26 19:30:28 +00005016 case RQ_LValue:
5017 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
5018 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005019 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00005020 ImplicitParamType);
5021 return ICS;
5022 }
5023 break;
5024
5025 case RQ_RValue:
5026 if (!FromClassification.isRValue()) {
5027 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005028 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00005029 ImplicitParamType);
5030 return ICS;
5031 }
5032 break;
5033 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005034
Douglas Gregor436424c2008-11-18 23:14:02 +00005035 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00005036 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00005037 ICS.Standard.setAsIdentityConversion();
5038 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00005039 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00005040 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00005041 ICS.Standard.ReferenceBinding = true;
5042 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005043 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00005044 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00005045 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5046 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5047 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00005048 return ICS;
5049}
5050
5051/// PerformObjectArgumentInitialization - Perform initialization of
5052/// the implicit object parameter for the given Method with the given
5053/// expression.
John Wiegley01296292011-04-08 18:41:53 +00005054ExprResult
5055Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005056 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00005057 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00005058 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005059 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00005060 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005061 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00005062
Douglas Gregor02824322011-01-26 19:30:28 +00005063 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005064 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005065 FromRecordType = PT->getPointeeType();
5066 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00005067 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005068 } else {
5069 FromRecordType = From->getType();
5070 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00005071 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005072 }
5073
John McCall6e9f8f62009-12-03 04:06:58 +00005074 // Note that we always use the true parent context when performing
5075 // the actual argument initialization.
Nico Weberb58e51c2014-11-19 05:21:39 +00005076 ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
Richard Smith0f59cb32015-12-18 21:45:41 +00005077 *this, From->getLocStart(), From->getType(), FromClassification, Method,
5078 Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005079 if (ICS.isBad()) {
5080 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
5081 Qualifiers FromQs = FromRecordType.getQualifiers();
5082 Qualifiers ToQs = DestType.getQualifiers();
5083 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5084 if (CVR) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005085 Diag(From->getLocStart(),
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005086 diag::err_member_function_call_bad_cvr)
5087 << Method->getDeclName() << FromRecordType << (CVR - 1)
5088 << From->getSourceRange();
5089 Diag(Method->getLocation(), diag::note_previous_decl)
5090 << Method->getDeclName();
John Wiegley01296292011-04-08 18:41:53 +00005091 return ExprError();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005092 }
5093 }
5094
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005095 return Diag(From->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00005096 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005097 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005098 }
Mike Stump11289f42009-09-09 15:08:12 +00005099
John Wiegley01296292011-04-08 18:41:53 +00005100 if (ICS.Standard.Second == ICK_Derived_To_Base) {
5101 ExprResult FromRes =
5102 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5103 if (FromRes.isInvalid())
5104 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005105 From = FromRes.get();
John Wiegley01296292011-04-08 18:41:53 +00005106 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005107
Douglas Gregorcc3f3252010-03-03 23:55:11 +00005108 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley01296292011-04-08 18:41:53 +00005109 From = ImpCastExprToType(From, DestType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005110 From->getValueKind()).get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005111 return From;
Douglas Gregor436424c2008-11-18 23:14:02 +00005112}
5113
Douglas Gregor5fb53972009-01-14 15:45:31 +00005114/// TryContextuallyConvertToBool - Attempt to contextually convert the
5115/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00005116static ImplicitConversionSequence
5117TryContextuallyConvertToBool(Sema &S, Expr *From) {
John McCall5c32be02010-08-24 20:38:10 +00005118 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00005119 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00005120 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00005121 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00005122 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005123 /*AllowObjCWritebackConversion=*/false,
5124 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00005125}
5126
5127/// PerformContextuallyConvertToBool - Perform a contextual conversion
5128/// of the expression From to bool (C++0x [conv]p3).
John Wiegley01296292011-04-08 18:41:53 +00005129ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00005130 if (checkPlaceholderForOverload(*this, From))
5131 return ExprError();
5132
John McCall5c32be02010-08-24 20:38:10 +00005133 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00005134 if (!ICS.isBad())
5135 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005136
Fariborz Jahanian76197412009-11-18 18:26:29 +00005137 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005138 return Diag(From->getLocStart(),
John McCall0009fcc2011-04-26 20:42:42 +00005139 diag::err_typecheck_bool_condition)
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00005140 << From->getType() << From->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00005141 return ExprError();
Douglas Gregor5fb53972009-01-14 15:45:31 +00005142}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005143
Richard Smithf8379a02012-01-18 23:55:52 +00005144/// Check that the specified conversion is permitted in a converted constant
5145/// expression, according to C++11 [expr.const]p3. Return true if the conversion
5146/// is acceptable.
5147static bool CheckConvertedConstantConversions(Sema &S,
5148 StandardConversionSequence &SCS) {
5149 // Since we know that the target type is an integral or unscoped enumeration
5150 // type, most conversion kinds are impossible. All possible First and Third
5151 // conversions are fine.
5152 switch (SCS.Second) {
5153 case ICK_Identity:
Richard Smith3c4f8d22016-10-16 17:54:23 +00005154 case ICK_Function_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005155 case ICK_Integral_Promotion:
Richard Smith410cc892014-11-26 03:26:53 +00005156 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
Richard Smithf8379a02012-01-18 23:55:52 +00005157 return true;
5158
5159 case ICK_Boolean_Conversion:
Richard Smithca24ed42012-09-13 22:00:12 +00005160 // Conversion from an integral or unscoped enumeration type to bool is
Richard Smith410cc892014-11-26 03:26:53 +00005161 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5162 // conversion, so we allow it in a converted constant expression.
5163 //
5164 // FIXME: Per core issue 1407, we should not allow this, but that breaks
5165 // a lot of popular code. We should at least add a warning for this
5166 // (non-conforming) extension.
Richard Smithca24ed42012-09-13 22:00:12 +00005167 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5168 SCS.getToType(2)->isBooleanType();
5169
Richard Smith410cc892014-11-26 03:26:53 +00005170 case ICK_Pointer_Conversion:
5171 case ICK_Pointer_Member:
5172 // C++1z: null pointer conversions and null member pointer conversions are
5173 // only permitted if the source type is std::nullptr_t.
5174 return SCS.getFromType()->isNullPtrType();
5175
5176 case ICK_Floating_Promotion:
5177 case ICK_Complex_Promotion:
5178 case ICK_Floating_Conversion:
5179 case ICK_Complex_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005180 case ICK_Floating_Integral:
Richard Smith410cc892014-11-26 03:26:53 +00005181 case ICK_Compatible_Conversion:
5182 case ICK_Derived_To_Base:
5183 case ICK_Vector_Conversion:
5184 case ICK_Vector_Splat:
Richard Smithf8379a02012-01-18 23:55:52 +00005185 case ICK_Complex_Real:
Richard Smith410cc892014-11-26 03:26:53 +00005186 case ICK_Block_Pointer_Conversion:
5187 case ICK_TransparentUnionConversion:
5188 case ICK_Writeback_Conversion:
5189 case ICK_Zero_Event_Conversion:
George Burgess IV45461812015-10-11 20:13:20 +00005190 case ICK_C_Only_Conversion:
George Burgess IV2099b542016-09-02 22:59:57 +00005191 case ICK_Incompatible_Pointer_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005192 return false;
5193
5194 case ICK_Lvalue_To_Rvalue:
5195 case ICK_Array_To_Pointer:
5196 case ICK_Function_To_Pointer:
Richard Smith410cc892014-11-26 03:26:53 +00005197 llvm_unreachable("found a first conversion kind in Second");
5198
Richard Smithf8379a02012-01-18 23:55:52 +00005199 case ICK_Qualification:
Richard Smith410cc892014-11-26 03:26:53 +00005200 llvm_unreachable("found a third conversion kind in Second");
Richard Smithf8379a02012-01-18 23:55:52 +00005201
5202 case ICK_Num_Conversion_Kinds:
5203 break;
5204 }
5205
5206 llvm_unreachable("unknown conversion kind");
5207}
5208
5209/// CheckConvertedConstantExpression - Check that the expression From is a
5210/// converted constant expression of type T, perform the conversion and produce
5211/// the converted expression, per C++11 [expr.const]p3.
Richard Smith410cc892014-11-26 03:26:53 +00005212static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5213 QualType T, APValue &Value,
5214 Sema::CCEKind CCE,
5215 bool RequireInt) {
5216 assert(S.getLangOpts().CPlusPlus11 &&
5217 "converted constant expression outside C++11");
Richard Smithf8379a02012-01-18 23:55:52 +00005218
Richard Smith410cc892014-11-26 03:26:53 +00005219 if (checkPlaceholderForOverload(S, From))
Richard Smithf8379a02012-01-18 23:55:52 +00005220 return ExprError();
5221
Richard Smith410cc892014-11-26 03:26:53 +00005222 // C++1z [expr.const]p3:
5223 // A converted constant expression of type T is an expression,
5224 // implicitly converted to type T, where the converted
5225 // expression is a constant expression and the implicit conversion
5226 // sequence contains only [... list of conversions ...].
Ismail Pazarbasi4a007742016-09-07 18:24:54 +00005227 // C++1z [stmt.if]p2:
5228 // If the if statement is of the form if constexpr, the value of the
5229 // condition shall be a contextually converted constant expression of type
5230 // bool.
Richard Smithf8379a02012-01-18 23:55:52 +00005231 ImplicitConversionSequence ICS =
Ismail Pazarbasi4a007742016-09-07 18:24:54 +00005232 CCE == Sema::CCEK_ConstexprIf
5233 ? TryContextuallyConvertToBool(S, From)
5234 : TryCopyInitialization(S, From, T,
5235 /*SuppressUserConversions=*/false,
5236 /*InOverloadResolution=*/false,
5237 /*AllowObjcWritebackConversion=*/false,
5238 /*AllowExplicit=*/false);
Craig Topperc3ec1492014-05-26 06:22:03 +00005239 StandardConversionSequence *SCS = nullptr;
Richard Smithf8379a02012-01-18 23:55:52 +00005240 switch (ICS.getKind()) {
5241 case ImplicitConversionSequence::StandardConversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005242 SCS = &ICS.Standard;
5243 break;
5244 case ImplicitConversionSequence::UserDefinedConversion:
Richard Smith410cc892014-11-26 03:26:53 +00005245 // We are converting to a non-class type, so the Before sequence
5246 // must be trivial.
Richard Smithf8379a02012-01-18 23:55:52 +00005247 SCS = &ICS.UserDefined.After;
5248 break;
5249 case ImplicitConversionSequence::AmbiguousConversion:
5250 case ImplicitConversionSequence::BadConversion:
Richard Smith410cc892014-11-26 03:26:53 +00005251 if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5252 return S.Diag(From->getLocStart(),
5253 diag::err_typecheck_converted_constant_expression)
5254 << From->getType() << From->getSourceRange() << T;
Richard Smithf8379a02012-01-18 23:55:52 +00005255 return ExprError();
5256
5257 case ImplicitConversionSequence::EllipsisConversion:
5258 llvm_unreachable("ellipsis conversion in converted constant expression");
5259 }
5260
Richard Smith410cc892014-11-26 03:26:53 +00005261 // Check that we would only use permitted conversions.
5262 if (!CheckConvertedConstantConversions(S, *SCS)) {
5263 return S.Diag(From->getLocStart(),
5264 diag::err_typecheck_converted_constant_expression_disallowed)
5265 << From->getType() << From->getSourceRange() << T;
5266 }
5267 // [...] and where the reference binding (if any) binds directly.
5268 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5269 return S.Diag(From->getLocStart(),
5270 diag::err_typecheck_converted_constant_expression_indirect)
5271 << From->getType() << From->getSourceRange() << T;
5272 }
5273
5274 ExprResult Result =
5275 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
Richard Smithf8379a02012-01-18 23:55:52 +00005276 if (Result.isInvalid())
5277 return Result;
5278
5279 // Check for a narrowing implicit conversion.
5280 APValue PreNarrowingValue;
Richard Smith5614ca72012-03-23 23:55:39 +00005281 QualType PreNarrowingType;
Richard Smith410cc892014-11-26 03:26:53 +00005282 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
Richard Smith5614ca72012-03-23 23:55:39 +00005283 PreNarrowingType)) {
Richard Smithf8379a02012-01-18 23:55:52 +00005284 case NK_Variable_Narrowing:
5285 // Implicit conversion to a narrower type, and the value is not a constant
5286 // expression. We'll diagnose this in a moment.
5287 case NK_Not_Narrowing:
5288 break;
5289
5290 case NK_Constant_Narrowing:
Richard Smith410cc892014-11-26 03:26:53 +00005291 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00005292 << CCE << /*Constant*/1
Richard Smith410cc892014-11-26 03:26:53 +00005293 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
Richard Smithf8379a02012-01-18 23:55:52 +00005294 break;
5295
5296 case NK_Type_Narrowing:
Richard Smith410cc892014-11-26 03:26:53 +00005297 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00005298 << CCE << /*Constant*/0 << From->getType() << T;
5299 break;
5300 }
5301
5302 // Check the expression is a constant expression.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005303 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithf8379a02012-01-18 23:55:52 +00005304 Expr::EvalResult Eval;
5305 Eval.Diag = &Notes;
5306
Richard Smith410cc892014-11-26 03:26:53 +00005307 if ((T->isReferenceType()
5308 ? !Result.get()->EvaluateAsLValue(Eval, S.Context)
5309 : !Result.get()->EvaluateAsRValue(Eval, S.Context)) ||
5310 (RequireInt && !Eval.Val.isInt())) {
Richard Smithf8379a02012-01-18 23:55:52 +00005311 // The expression can't be folded, so we can't keep it at this position in
5312 // the AST.
5313 Result = ExprError();
Richard Smith911e1422012-01-30 22:27:01 +00005314 } else {
Richard Smith410cc892014-11-26 03:26:53 +00005315 Value = Eval.Val;
Richard Smith911e1422012-01-30 22:27:01 +00005316
5317 if (Notes.empty()) {
5318 // It's a constant expression.
5319 return Result;
5320 }
Richard Smithf8379a02012-01-18 23:55:52 +00005321 }
5322
5323 // It's not a constant expression. Produce an appropriate diagnostic.
5324 if (Notes.size() == 1 &&
5325 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
Richard Smith410cc892014-11-26 03:26:53 +00005326 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
Richard Smithf8379a02012-01-18 23:55:52 +00005327 else {
Richard Smith410cc892014-11-26 03:26:53 +00005328 S.Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smithf8379a02012-01-18 23:55:52 +00005329 << CCE << From->getSourceRange();
5330 for (unsigned I = 0; I < Notes.size(); ++I)
Richard Smith410cc892014-11-26 03:26:53 +00005331 S.Diag(Notes[I].first, Notes[I].second);
Richard Smithf8379a02012-01-18 23:55:52 +00005332 }
Richard Smith410cc892014-11-26 03:26:53 +00005333 return ExprError();
Richard Smithf8379a02012-01-18 23:55:52 +00005334}
5335
Richard Smith410cc892014-11-26 03:26:53 +00005336ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5337 APValue &Value, CCEKind CCE) {
5338 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5339}
5340
5341ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5342 llvm::APSInt &Value,
5343 CCEKind CCE) {
5344 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5345
5346 APValue V;
5347 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5348 if (!R.isInvalid())
5349 Value = V.getInt();
5350 return R;
5351}
5352
5353
John McCallfec112d2011-09-09 06:11:02 +00005354/// dropPointerConversions - If the given standard conversion sequence
5355/// involves any pointer conversions, remove them. This may change
5356/// the result type of the conversion sequence.
5357static void dropPointerConversion(StandardConversionSequence &SCS) {
5358 if (SCS.Second == ICK_Pointer_Conversion) {
5359 SCS.Second = ICK_Identity;
5360 SCS.Third = ICK_Identity;
5361 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5362 }
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005363}
John McCall5c32be02010-08-24 20:38:10 +00005364
John McCallfec112d2011-09-09 06:11:02 +00005365/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5366/// convert the expression From to an Objective-C pointer type.
5367static ImplicitConversionSequence
5368TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5369 // Do an implicit conversion to 'id'.
5370 QualType Ty = S.Context.getObjCIdType();
5371 ImplicitConversionSequence ICS
5372 = TryImplicitConversion(S, From, Ty,
5373 // FIXME: Are these flags correct?
5374 /*SuppressUserConversions=*/false,
5375 /*AllowExplicit=*/true,
5376 /*InOverloadResolution=*/false,
5377 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005378 /*AllowObjCWritebackConversion=*/false,
5379 /*AllowObjCConversionOnExplicit=*/true);
John McCallfec112d2011-09-09 06:11:02 +00005380
5381 // Strip off any final conversions to 'id'.
5382 switch (ICS.getKind()) {
5383 case ImplicitConversionSequence::BadConversion:
5384 case ImplicitConversionSequence::AmbiguousConversion:
5385 case ImplicitConversionSequence::EllipsisConversion:
5386 break;
5387
5388 case ImplicitConversionSequence::UserDefinedConversion:
5389 dropPointerConversion(ICS.UserDefined.After);
5390 break;
5391
5392 case ImplicitConversionSequence::StandardConversion:
5393 dropPointerConversion(ICS.Standard);
5394 break;
5395 }
5396
5397 return ICS;
5398}
5399
5400/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5401/// conversion of the expression From to an Objective-C pointer type.
Richard Smithe15a3702016-10-06 23:12:58 +00005402/// Returns a valid but null ExprResult if no conversion sequence exists.
John McCallfec112d2011-09-09 06:11:02 +00005403ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00005404 if (checkPlaceholderForOverload(*this, From))
5405 return ExprError();
5406
John McCall8b07ec22010-05-15 11:32:37 +00005407 QualType Ty = Context.getObjCIdType();
John McCallfec112d2011-09-09 06:11:02 +00005408 ImplicitConversionSequence ICS =
5409 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005410 if (!ICS.isBad())
5411 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
Richard Smithe15a3702016-10-06 23:12:58 +00005412 return ExprResult();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005413}
Douglas Gregor5fb53972009-01-14 15:45:31 +00005414
Richard Smith8dd34252012-02-04 07:07:42 +00005415/// Determine whether the provided type is an integral type, or an enumeration
5416/// type of a permitted flavor.
Richard Smithccc11812013-05-21 19:05:48 +00005417bool Sema::ICEConvertDiagnoser::match(QualType T) {
5418 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5419 : T->isIntegralOrUnscopedEnumerationType();
Richard Smith8dd34252012-02-04 07:07:42 +00005420}
5421
Larisse Voufo236bec22013-06-10 06:50:24 +00005422static ExprResult
5423diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5424 Sema::ContextualImplicitConverter &Converter,
5425 QualType T, UnresolvedSetImpl &ViableConversions) {
5426
5427 if (Converter.Suppress)
5428 return ExprError();
5429
5430 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5431 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5432 CXXConversionDecl *Conv =
5433 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5434 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5435 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5436 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005437 return From;
Larisse Voufo236bec22013-06-10 06:50:24 +00005438}
5439
5440static bool
5441diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5442 Sema::ContextualImplicitConverter &Converter,
5443 QualType T, bool HadMultipleCandidates,
5444 UnresolvedSetImpl &ExplicitConversions) {
5445 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5446 DeclAccessPair Found = ExplicitConversions[0];
5447 CXXConversionDecl *Conversion =
5448 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5449
5450 // The user probably meant to invoke the given explicit
5451 // conversion; use it.
5452 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5453 std::string TypeStr;
5454 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5455
5456 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5457 << FixItHint::CreateInsertion(From->getLocStart(),
5458 "static_cast<" + TypeStr + ">(")
5459 << FixItHint::CreateInsertion(
Alp Tokerb6cc5922014-05-03 03:45:55 +00005460 SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
Larisse Voufo236bec22013-06-10 06:50:24 +00005461 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5462
5463 // If we aren't in a SFINAE context, build a call to the
5464 // explicit conversion function.
5465 if (SemaRef.isSFINAEContext())
5466 return true;
5467
Craig Topperc3ec1492014-05-26 06:22:03 +00005468 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
Larisse Voufo236bec22013-06-10 06:50:24 +00005469 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5470 HadMultipleCandidates);
5471 if (Result.isInvalid())
5472 return true;
5473 // Record usage of conversion in an implicit cast.
5474 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005475 CK_UserDefinedConversion, Result.get(),
5476 nullptr, Result.get()->getValueKind());
Larisse Voufo236bec22013-06-10 06:50:24 +00005477 }
5478 return false;
5479}
5480
5481static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5482 Sema::ContextualImplicitConverter &Converter,
5483 QualType T, bool HadMultipleCandidates,
5484 DeclAccessPair &Found) {
5485 CXXConversionDecl *Conversion =
5486 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00005487 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
Larisse Voufo236bec22013-06-10 06:50:24 +00005488
5489 QualType ToType = Conversion->getConversionType().getNonReferenceType();
5490 if (!Converter.SuppressConversion) {
5491 if (SemaRef.isSFINAEContext())
5492 return true;
5493
5494 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5495 << From->getSourceRange();
5496 }
5497
5498 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5499 HadMultipleCandidates);
5500 if (Result.isInvalid())
5501 return true;
5502 // Record usage of conversion in an implicit cast.
5503 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005504 CK_UserDefinedConversion, Result.get(),
5505 nullptr, Result.get()->getValueKind());
Larisse Voufo236bec22013-06-10 06:50:24 +00005506 return false;
5507}
5508
5509static ExprResult finishContextualImplicitConversion(
5510 Sema &SemaRef, SourceLocation Loc, Expr *From,
5511 Sema::ContextualImplicitConverter &Converter) {
5512 if (!Converter.match(From->getType()) && !Converter.Suppress)
5513 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5514 << From->getSourceRange();
5515
5516 return SemaRef.DefaultLvalueConversion(From);
5517}
5518
5519static void
5520collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5521 UnresolvedSetImpl &ViableConversions,
5522 OverloadCandidateSet &CandidateSet) {
5523 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5524 DeclAccessPair FoundDecl = ViableConversions[I];
5525 NamedDecl *D = FoundDecl.getDecl();
5526 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5527 if (isa<UsingShadowDecl>(D))
5528 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5529
5530 CXXConversionDecl *Conv;
5531 FunctionTemplateDecl *ConvTemplate;
5532 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5533 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5534 else
5535 Conv = cast<CXXConversionDecl>(D);
5536
5537 if (ConvTemplate)
5538 SemaRef.AddTemplateConversionCandidate(
Douglas Gregor4b60a152013-11-07 22:34:54 +00005539 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5540 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005541 else
5542 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005543 ToType, CandidateSet,
5544 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005545 }
5546}
5547
Richard Smithccc11812013-05-21 19:05:48 +00005548/// \brief Attempt to convert the given expression to a type which is accepted
5549/// by the given converter.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005550///
Richard Smithccc11812013-05-21 19:05:48 +00005551/// This routine will attempt to convert an expression of class type to a
5552/// type accepted by the specified converter. In C++11 and before, the class
5553/// must have a single non-explicit conversion function converting to a matching
5554/// type. In C++1y, there can be multiple such conversion functions, but only
5555/// one target type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005556///
Douglas Gregor4799d032010-06-30 00:20:43 +00005557/// \param Loc The source location of the construct that requires the
5558/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005559///
James Dennett18348b62012-06-22 08:52:37 +00005560/// \param From The expression we're converting from.
Douglas Gregor4799d032010-06-30 00:20:43 +00005561///
Richard Smithccc11812013-05-21 19:05:48 +00005562/// \param Converter Used to control and diagnose the conversion process.
Richard Smith8dd34252012-02-04 07:07:42 +00005563///
Douglas Gregor4799d032010-06-30 00:20:43 +00005564/// \returns The expression, converted to an integral or enumeration type if
5565/// successful.
Richard Smithccc11812013-05-21 19:05:48 +00005566ExprResult Sema::PerformContextualImplicitConversion(
5567 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005568 // We can't perform any more checking for type-dependent expressions.
5569 if (From->isTypeDependent())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005570 return From;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005571
Eli Friedman1da70392012-01-26 00:26:18 +00005572 // Process placeholders immediately.
5573 if (From->hasPlaceholderType()) {
5574 ExprResult result = CheckPlaceholderExpr(From);
Larisse Voufo236bec22013-06-10 06:50:24 +00005575 if (result.isInvalid())
5576 return result;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005577 From = result.get();
Eli Friedman1da70392012-01-26 00:26:18 +00005578 }
5579
Richard Smithccc11812013-05-21 19:05:48 +00005580 // If the expression already has a matching type, we're golden.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005581 QualType T = From->getType();
Richard Smithccc11812013-05-21 19:05:48 +00005582 if (Converter.match(T))
Eli Friedman1da70392012-01-26 00:26:18 +00005583 return DefaultLvalueConversion(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005584
5585 // FIXME: Check for missing '()' if T is a function type?
5586
Richard Smithccc11812013-05-21 19:05:48 +00005587 // We can only perform contextual implicit conversions on objects of class
5588 // type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005589 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikiebbafb8a2012-03-11 07:00:24 +00005590 if (!RecordTy || !getLangOpts().CPlusPlus) {
Richard Smithccc11812013-05-21 19:05:48 +00005591 if (!Converter.Suppress)
5592 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005593 return From;
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005594 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005595
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005596 // We must have a complete class type.
Douglas Gregora6c5abb2012-05-04 16:48:41 +00005597 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
Richard Smithccc11812013-05-21 19:05:48 +00005598 ContextualImplicitConverter &Converter;
Douglas Gregore2b37442012-05-04 22:38:52 +00005599 Expr *From;
Richard Smithccc11812013-05-21 19:05:48 +00005600
5601 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
Richard Smithdb0ac552015-12-18 22:40:25 +00005602 : Converter(Converter), From(From) {}
Richard Smithccc11812013-05-21 19:05:48 +00005603
Craig Toppere14c0f82014-03-12 04:55:44 +00005604 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00005605 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005606 }
Richard Smithccc11812013-05-21 19:05:48 +00005607 } IncompleteDiagnoser(Converter, From);
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005608
Richard Smithdb0ac552015-12-18 22:40:25 +00005609 if (Converter.Suppress ? !isCompleteType(Loc, T)
5610 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005611 return From;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005612
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005613 // Look for a conversion to an integral or enumeration type.
Larisse Voufo236bec22013-06-10 06:50:24 +00005614 UnresolvedSet<4>
5615 ViableConversions; // These are *potentially* viable in C++1y.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005616 UnresolvedSet<4> ExplicitConversions;
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005617 const auto &Conversions =
Larisse Voufo236bec22013-06-10 06:50:24 +00005618 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005619
Larisse Voufo236bec22013-06-10 06:50:24 +00005620 bool HadMultipleCandidates =
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005621 (std::distance(Conversions.begin(), Conversions.end()) > 1);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005622
Larisse Voufo236bec22013-06-10 06:50:24 +00005623 // To check that there is only one target type, in C++1y:
5624 QualType ToType;
5625 bool HasUniqueTargetType = true;
5626
5627 // Collect explicit or viable (potentially in C++1y) conversions.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005628 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005629 NamedDecl *D = (*I)->getUnderlyingDecl();
5630 CXXConversionDecl *Conversion;
5631 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5632 if (ConvTemplate) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005633 if (getLangOpts().CPlusPlus14)
Larisse Voufo236bec22013-06-10 06:50:24 +00005634 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5635 else
5636 continue; // C++11 does not consider conversion operator templates(?).
5637 } else
5638 Conversion = cast<CXXConversionDecl>(D);
5639
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005640 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
Larisse Voufo236bec22013-06-10 06:50:24 +00005641 "Conversion operator templates are considered potentially "
5642 "viable in C++1y");
5643
5644 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5645 if (Converter.match(CurToType) || ConvTemplate) {
5646
5647 if (Conversion->isExplicit()) {
5648 // FIXME: For C++1y, do we need this restriction?
5649 // cf. diagnoseNoViableConversion()
5650 if (!ConvTemplate)
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005651 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
Larisse Voufo236bec22013-06-10 06:50:24 +00005652 } else {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005653 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005654 if (ToType.isNull())
5655 ToType = CurToType.getUnqualifiedType();
5656 else if (HasUniqueTargetType &&
5657 (CurToType.getUnqualifiedType() != ToType))
5658 HasUniqueTargetType = false;
5659 }
5660 ViableConversions.addDecl(I.getDecl(), I.getAccess());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005661 }
Richard Smith8dd34252012-02-04 07:07:42 +00005662 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005663 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005664
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005665 if (getLangOpts().CPlusPlus14) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005666 // C++1y [conv]p6:
5667 // ... An expression e of class type E appearing in such a context
5668 // is said to be contextually implicitly converted to a specified
5669 // type T and is well-formed if and only if e can be implicitly
5670 // converted to a type T that is determined as follows: E is searched
Larisse Voufo67170bd2013-06-10 08:25:58 +00005671 // for conversion functions whose return type is cv T or reference to
5672 // cv T such that T is allowed by the context. There shall be
Larisse Voufo236bec22013-06-10 06:50:24 +00005673 // exactly one such T.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005674
Larisse Voufo236bec22013-06-10 06:50:24 +00005675 // If no unique T is found:
5676 if (ToType.isNull()) {
5677 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5678 HadMultipleCandidates,
5679 ExplicitConversions))
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005680 return ExprError();
Larisse Voufo236bec22013-06-10 06:50:24 +00005681 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005682 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005683
Larisse Voufo236bec22013-06-10 06:50:24 +00005684 // If more than one unique Ts are found:
5685 if (!HasUniqueTargetType)
5686 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5687 ViableConversions);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005688
Larisse Voufo236bec22013-06-10 06:50:24 +00005689 // If one unique T is found:
5690 // First, build a candidate set from the previously recorded
5691 // potentially viable conversions.
Richard Smith100b24a2014-04-17 01:52:14 +00005692 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Larisse Voufo236bec22013-06-10 06:50:24 +00005693 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5694 CandidateSet);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005695
Larisse Voufo236bec22013-06-10 06:50:24 +00005696 // Then, perform overload resolution over the candidate set.
5697 OverloadCandidateSet::iterator Best;
5698 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5699 case OR_Success: {
5700 // Apply this conversion.
5701 DeclAccessPair Found =
5702 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5703 if (recordConversion(*this, Loc, From, Converter, T,
5704 HadMultipleCandidates, Found))
5705 return ExprError();
5706 break;
5707 }
5708 case OR_Ambiguous:
5709 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5710 ViableConversions);
5711 case OR_No_Viable_Function:
5712 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5713 HadMultipleCandidates,
5714 ExplicitConversions))
5715 return ExprError();
5716 // fall through 'OR_Deleted' case.
5717 case OR_Deleted:
5718 // We'll complain below about a non-integral condition type.
5719 break;
5720 }
5721 } else {
5722 switch (ViableConversions.size()) {
5723 case 0: {
5724 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5725 HadMultipleCandidates,
5726 ExplicitConversions))
Douglas Gregor4799d032010-06-30 00:20:43 +00005727 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005728
Larisse Voufo236bec22013-06-10 06:50:24 +00005729 // We'll complain below about a non-integral condition type.
5730 break;
Douglas Gregor4799d032010-06-30 00:20:43 +00005731 }
Larisse Voufo236bec22013-06-10 06:50:24 +00005732 case 1: {
5733 // Apply this conversion.
5734 DeclAccessPair Found = ViableConversions[0];
5735 if (recordConversion(*this, Loc, From, Converter, T,
5736 HadMultipleCandidates, Found))
5737 return ExprError();
5738 break;
5739 }
5740 default:
5741 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5742 ViableConversions);
5743 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005744 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005745
Larisse Voufo236bec22013-06-10 06:50:24 +00005746 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005747}
5748
Richard Smith100b24a2014-04-17 01:52:14 +00005749/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5750/// an acceptable non-member overloaded operator for a call whose
5751/// arguments have types T1 (and, if non-empty, T2). This routine
5752/// implements the check in C++ [over.match.oper]p3b2 concerning
5753/// enumeration types.
5754static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5755 FunctionDecl *Fn,
5756 ArrayRef<Expr *> Args) {
5757 QualType T1 = Args[0]->getType();
5758 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5759
5760 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5761 return true;
5762
5763 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5764 return true;
5765
5766 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5767 if (Proto->getNumParams() < 1)
5768 return false;
5769
5770 if (T1->isEnumeralType()) {
5771 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5772 if (Context.hasSameUnqualifiedType(T1, ArgType))
5773 return true;
5774 }
5775
5776 if (Proto->getNumParams() < 2)
5777 return false;
5778
5779 if (!T2.isNull() && T2->isEnumeralType()) {
5780 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5781 if (Context.hasSameUnqualifiedType(T2, ArgType))
5782 return true;
5783 }
5784
5785 return false;
5786}
5787
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005788/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00005789/// candidate functions, using the given function call arguments. If
5790/// @p SuppressUserConversions, then don't allow user-defined
5791/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00005792///
James Dennett2a4d13c2012-06-15 07:13:21 +00005793/// \param PartialOverloading true if we are performing "partial" overloading
Douglas Gregorcabea402009-09-22 15:41:20 +00005794/// based on an incomplete set of function arguments. This feature is used by
5795/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00005796void
5797Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00005798 DeclAccessPair FoundDecl,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005799 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005800 OverloadCandidateSet &CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00005801 bool SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005802 bool PartialOverloading,
5803 bool AllowExplicit) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005804 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00005805 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005806 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00005807 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005808 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00005809
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005810 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005811 if (!isa<CXXConstructorDecl>(Method)) {
5812 // If we get here, it's because we're calling a member function
5813 // that is named without a member access expression (e.g.,
5814 // "this->f") that was either written explicitly or created
5815 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00005816 // function, e.g., X::f(). We use an empty type for the implied
5817 // object argument (C++ [over.call.func]p3), and the acting context
5818 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00005819 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005820 QualType(), Expr::Classification::makeSimpleLValue(),
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005821 Args, CandidateSet, SuppressUserConversions,
5822 PartialOverloading);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005823 return;
5824 }
5825 // We treat a constructor like a non-member function, since its object
5826 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005827 }
5828
Douglas Gregorff7028a2009-11-13 23:59:09 +00005829 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005830 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00005831
Richard Smith100b24a2014-04-17 01:52:14 +00005832 // C++ [over.match.oper]p3:
5833 // if no operand has a class type, only those non-member functions in the
5834 // lookup set that have a first parameter of type T1 or "reference to
5835 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5836 // is a right operand) a second parameter of type T2 or "reference to
5837 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
5838 // candidate functions.
5839 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5840 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5841 return;
5842
Richard Smith8b86f2d2013-11-04 01:48:18 +00005843 // C++11 [class.copy]p11: [DR1402]
5844 // A defaulted move constructor that is defined as deleted is ignored by
5845 // overload resolution.
5846 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5847 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5848 Constructor->isMoveConstructor())
5849 return;
5850
Douglas Gregor27381f32009-11-23 12:27:39 +00005851 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005852 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005853
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005854 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005855 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCalla0296f72010-03-19 07:35:19 +00005856 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005857 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005858 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005859 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005860 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005861 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005862
John McCall578a1f82014-12-14 01:46:53 +00005863 if (Constructor) {
5864 // C++ [class.copy]p3:
5865 // A member function template is never instantiated to perform the copy
5866 // of a class object to an object of its class type.
5867 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
Richard Smith0f59cb32015-12-18 21:45:41 +00005868 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
John McCall578a1f82014-12-14 01:46:53 +00005869 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00005870 IsDerivedFrom(Args[0]->getLocStart(), Args[0]->getType(),
5871 ClassType))) {
John McCall578a1f82014-12-14 01:46:53 +00005872 Candidate.Viable = false;
5873 Candidate.FailureKind = ovl_fail_illegal_constructor;
5874 return;
5875 }
5876 }
5877
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005878 unsigned NumParams = Proto->getNumParams();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005879
5880 // (C++ 13.3.2p2): A candidate function having fewer than m
5881 // parameters is viable only if it has an ellipsis in its parameter
5882 // list (8.3.5).
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005883 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
Douglas Gregor2a920012009-09-23 14:56:09 +00005884 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005885 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005886 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005887 return;
5888 }
5889
5890 // (C++ 13.3.2p2): A candidate function having more than m parameters
5891 // is viable only if the (m+1)st parameter has a default argument
5892 // (8.3.6). For the purposes of overload resolution, the
5893 // parameter list is truncated on the right, so that there are
5894 // exactly m parameters.
5895 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005896 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005897 // Not enough arguments.
5898 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005899 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005900 return;
5901 }
5902
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005903 // (CUDA B.1): Check for invalid calls between targets.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005904 if (getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005905 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
Eli Bendersky9a220fc2014-09-29 20:38:29 +00005906 // Skip the check for callers that are implicit members, because in this
5907 // case we may not yet know what the member's target is; the target is
5908 // inferred for the member automatically, based on the bases and fields of
5909 // the class.
Justin Lebarb0080032016-08-10 01:09:11 +00005910 if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005911 Candidate.Viable = false;
5912 Candidate.FailureKind = ovl_fail_bad_target;
5913 return;
5914 }
5915
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005916 // Determine the implicit conversion sequences for each of the
5917 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005918 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005919 if (ArgIdx < NumParams) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005920 // (C++ 13.3.2p3): for F to be a viable function, there shall
5921 // exist for each argument an implicit conversion sequence
5922 // (13.3.3.1) that converts that argument to the corresponding
5923 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00005924 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005925 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005926 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005927 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00005928 /*InOverloadResolution=*/true,
5929 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005930 getLangOpts().ObjCAutoRefCount,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005931 AllowExplicit);
John McCall0d1da222010-01-12 00:44:57 +00005932 if (Candidate.Conversions[ArgIdx].isBad()) {
5933 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005934 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005935 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00005936 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005937 } else {
5938 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5939 // argument for which there is no corresponding parameter is
5940 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005941 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005942 }
5943 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005944
5945 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
5946 Candidate.Viable = false;
5947 Candidate.FailureKind = ovl_fail_enable_if;
5948 Candidate.DeductionFailure.Data = FailedAttr;
5949 return;
5950 }
5951}
5952
Manman Rend2a3cd72016-04-07 19:30:20 +00005953ObjCMethodDecl *
5954Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
5955 SmallVectorImpl<ObjCMethodDecl *> &Methods) {
5956 if (Methods.size() <= 1)
Fariborz Jahanian0ded4242014-08-13 21:24:14 +00005957 return nullptr;
Manman Rend2a3cd72016-04-07 19:30:20 +00005958
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005959 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5960 bool Match = true;
5961 ObjCMethodDecl *Method = Methods[b];
5962 unsigned NumNamedArgs = Sel.getNumArgs();
5963 // Method might have more arguments than selector indicates. This is due
5964 // to addition of c-style arguments in method.
5965 if (Method->param_size() > NumNamedArgs)
5966 NumNamedArgs = Method->param_size();
5967 if (Args.size() < NumNamedArgs)
5968 continue;
5969
5970 for (unsigned i = 0; i < NumNamedArgs; i++) {
5971 // We can't do any type-checking on a type-dependent argument.
5972 if (Args[i]->isTypeDependent()) {
5973 Match = false;
5974 break;
5975 }
5976
5977 ParmVarDecl *param = Method->parameters()[i];
5978 Expr *argExpr = Args[i];
5979 assert(argExpr && "SelectBestMethod(): missing expression");
5980
5981 // Strip the unbridged-cast placeholder expression off unless it's
5982 // a consumed argument.
5983 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
5984 !param->hasAttr<CFConsumedAttr>())
5985 argExpr = stripARCUnbridgedCast(argExpr);
5986
5987 // If the parameter is __unknown_anytype, move on to the next method.
5988 if (param->getType() == Context.UnknownAnyTy) {
5989 Match = false;
5990 break;
5991 }
George Burgess IV45461812015-10-11 20:13:20 +00005992
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005993 ImplicitConversionSequence ConversionState
5994 = TryCopyInitialization(*this, argExpr, param->getType(),
5995 /*SuppressUserConversions*/false,
5996 /*InOverloadResolution=*/true,
5997 /*AllowObjCWritebackConversion=*/
5998 getLangOpts().ObjCAutoRefCount,
5999 /*AllowExplicit*/false);
George Burgess IV2099b542016-09-02 22:59:57 +00006000 // This function looks for a reasonably-exact match, so we consider
6001 // incompatible pointer conversions to be a failure here.
6002 if (ConversionState.isBad() ||
6003 (ConversionState.isStandard() &&
6004 ConversionState.Standard.Second ==
6005 ICK_Incompatible_Pointer_Conversion)) {
6006 Match = false;
6007 break;
6008 }
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006009 }
6010 // Promote additional arguments to variadic methods.
6011 if (Match && Method->isVariadic()) {
6012 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6013 if (Args[i]->isTypeDependent()) {
6014 Match = false;
6015 break;
6016 }
6017 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6018 nullptr);
6019 if (Arg.isInvalid()) {
6020 Match = false;
6021 break;
6022 }
6023 }
Fariborz Jahanian180d76b2014-08-27 16:38:47 +00006024 } else {
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006025 // Check for extra arguments to non-variadic methods.
6026 if (Args.size() != NumNamedArgs)
6027 Match = false;
Fariborz Jahanian180d76b2014-08-27 16:38:47 +00006028 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6029 // Special case when selectors have no argument. In this case, select
6030 // one with the most general result type of 'id'.
6031 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6032 QualType ReturnT = Methods[b]->getReturnType();
6033 if (ReturnT->isObjCIdType())
6034 return Methods[b];
6035 }
6036 }
6037 }
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006038
6039 if (Match)
6040 return Method;
6041 }
6042 return nullptr;
6043}
6044
George Burgess IV2a6150d2015-10-16 01:17:38 +00006045// specific_attr_iterator iterates over enable_if attributes in reverse, and
6046// enable_if is order-sensitive. As a result, we need to reverse things
6047// sometimes. Size of 4 elements is arbitrary.
6048static SmallVector<EnableIfAttr *, 4>
6049getOrderedEnableIfAttrs(const FunctionDecl *Function) {
6050 SmallVector<EnableIfAttr *, 4> Result;
6051 if (!Function->hasAttrs())
6052 return Result;
6053
6054 const auto &FuncAttrs = Function->getAttrs();
6055 for (Attr *Attr : FuncAttrs)
6056 if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr))
6057 Result.push_back(EnableIf);
6058
6059 std::reverse(Result.begin(), Result.end());
6060 return Result;
6061}
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006062
6063EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
6064 bool MissingImplicitThis) {
George Burgess IV2a6150d2015-10-16 01:17:38 +00006065 auto EnableIfAttrs = getOrderedEnableIfAttrs(Function);
6066 if (EnableIfAttrs.empty())
Craig Topperc3ec1492014-05-26 06:22:03 +00006067 return nullptr;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006068
6069 SFINAETrap Trap(*this);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006070 SmallVector<Expr *, 16> ConvertedArgs;
6071 bool InitializationFailed = false;
Nick Lewyckye283c552015-08-25 22:33:16 +00006072
George Burgess IV458b3f32016-08-12 04:19:35 +00006073 // Ignore any variadic arguments. Converting them is pointless, since the
George Burgess IV53b938d2016-08-12 04:12:31 +00006074 // user can't refer to them in the enable_if condition.
6075 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6076
Nick Lewyckye283c552015-08-25 22:33:16 +00006077 // Convert the arguments.
George Burgess IV53b938d2016-08-12 04:12:31 +00006078 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
George Burgess IVe96abf72016-02-24 22:31:14 +00006079 ExprResult R;
6080 if (I == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) &&
Nick Lewyckyb8336b72014-02-28 05:26:13 +00006081 !cast<CXXMethodDecl>(Function)->isStatic() &&
6082 !isa<CXXConstructorDecl>(Function)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006083 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
George Burgess IVe96abf72016-02-24 22:31:14 +00006084 R = PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
6085 Method, Method);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006086 } else {
George Burgess IVe96abf72016-02-24 22:31:14 +00006087 R = PerformCopyInitialization(InitializedEntity::InitializeParameter(
6088 Context, Function->getParamDecl(I)),
6089 SourceLocation(), Args[I]);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006090 }
George Burgess IVe96abf72016-02-24 22:31:14 +00006091
6092 if (R.isInvalid()) {
6093 InitializationFailed = true;
6094 break;
6095 }
6096
George Burgess IVe96abf72016-02-24 22:31:14 +00006097 ConvertedArgs.push_back(R.get());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006098 }
6099
6100 if (InitializationFailed || Trap.hasErrorOccurred())
George Burgess IV2a6150d2015-10-16 01:17:38 +00006101 return EnableIfAttrs[0];
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006102
Nick Lewyckye283c552015-08-25 22:33:16 +00006103 // Push default arguments if needed.
6104 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6105 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6106 ParmVarDecl *P = Function->getParamDecl(i);
6107 ExprResult R = PerformCopyInitialization(
6108 InitializedEntity::InitializeParameter(Context,
6109 Function->getParamDecl(i)),
6110 SourceLocation(),
6111 P->hasUninstantiatedDefaultArg() ? P->getUninstantiatedDefaultArg()
6112 : P->getDefaultArg());
6113 if (R.isInvalid()) {
6114 InitializationFailed = true;
6115 break;
6116 }
Nick Lewyckye283c552015-08-25 22:33:16 +00006117 ConvertedArgs.push_back(R.get());
6118 }
6119
6120 if (InitializationFailed || Trap.hasErrorOccurred())
George Burgess IV2a6150d2015-10-16 01:17:38 +00006121 return EnableIfAttrs[0];
Nick Lewyckye283c552015-08-25 22:33:16 +00006122 }
6123
George Burgess IV2a6150d2015-10-16 01:17:38 +00006124 for (auto *EIA : EnableIfAttrs) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006125 APValue Result;
George Burgess IVe8f10cc2016-05-11 01:38:27 +00006126 // FIXME: This doesn't consider value-dependent cases, because doing so is
6127 // very difficult. Ideally, we should handle them more gracefully.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006128 if (!EIA->getCond()->EvaluateWithSubstitution(
George Burgess IVe8f10cc2016-05-11 01:38:27 +00006129 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006130 return EIA;
George Burgess IVe8f10cc2016-05-11 01:38:27 +00006131
6132 if (!Result.isInt() || !Result.getInt().getBoolValue())
6133 return EIA;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006134 }
Craig Topperc3ec1492014-05-26 06:22:03 +00006135 return nullptr;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006136}
6137
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006138/// \brief Add all of the function declarations in the given function set to
Nick Lewyckyed4265c2013-09-22 10:06:01 +00006139/// the overload candidate set.
John McCall4c4c1df2010-01-26 03:27:55 +00006140void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006141 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006142 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006143 TemplateArgumentListInfo *ExplicitTemplateArgs,
Richard Smithbcc22fc2012-03-09 08:00:36 +00006144 bool SuppressUserConversions,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006145 bool PartialOverloading) {
John McCall4c4c1df2010-01-26 03:27:55 +00006146 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00006147 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6148 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006149 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00006150 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00006151 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00006152 Args[0]->getType(), Args[0]->Classify(Context),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006153 Args.slice(1), CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006154 SuppressUserConversions, PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006155 else
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006156 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006157 SuppressUserConversions, PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006158 } else {
John McCalla0296f72010-03-19 07:35:19 +00006159 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006160 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
6161 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00006162 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00006163 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Richard Smithbcc22fc2012-03-09 08:00:36 +00006164 ExplicitTemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006165 Args[0]->getType(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006166 Args[0]->Classify(Context), Args.slice(1),
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006167 CandidateSet, SuppressUserConversions,
6168 PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006169 else
John McCalla0296f72010-03-19 07:35:19 +00006170 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smithbcc22fc2012-03-09 08:00:36 +00006171 ExplicitTemplateArgs, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006172 CandidateSet, SuppressUserConversions,
6173 PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006174 }
Douglas Gregor15448f82009-06-27 21:05:07 +00006175 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006176}
6177
John McCallf0f1cf02009-11-17 07:50:12 +00006178/// AddMethodCandidate - Adds a named decl (which is some kind of
6179/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00006180void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006181 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006182 Expr::Classification ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00006183 ArrayRef<Expr *> Args,
John McCallf0f1cf02009-11-17 07:50:12 +00006184 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006185 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00006186 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00006187 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00006188
6189 if (isa<UsingShadowDecl>(Decl))
6190 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006191
John McCallf0f1cf02009-11-17 07:50:12 +00006192 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6193 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6194 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00006195 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
Craig Topperc3ec1492014-05-26 06:22:03 +00006196 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006197 ObjectType, ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00006198 Args, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006199 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00006200 } else {
John McCalla0296f72010-03-19 07:35:19 +00006201 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006202 ObjectType, ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00006203 Args,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006204 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00006205 }
6206}
6207
Douglas Gregor436424c2008-11-18 23:14:02 +00006208/// AddMethodCandidate - Adds the given C++ member function to the set
6209/// of candidate functions, using the given function call arguments
6210/// and the object argument (@c Object). For example, in a call
6211/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6212/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6213/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00006214/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00006215void
John McCalla0296f72010-03-19 07:35:19 +00006216Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00006217 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006218 Expr::Classification ObjectClassification,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006219 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006220 OverloadCandidateSet &CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006221 bool SuppressUserConversions,
6222 bool PartialOverloading) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006223 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00006224 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00006225 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00006226 assert(!isa<CXXConstructorDecl>(Method) &&
6227 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00006228
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006229 if (!CandidateSet.isNewCandidate(Method))
6230 return;
6231
Richard Smith8b86f2d2013-11-04 01:48:18 +00006232 // C++11 [class.copy]p23: [DR1402]
6233 // A defaulted move assignment operator that is defined as deleted is
6234 // ignored by overload resolution.
6235 if (Method->isDefaulted() && Method->isDeleted() &&
6236 Method->isMoveAssignmentOperator())
6237 return;
6238
Douglas Gregor27381f32009-11-23 12:27:39 +00006239 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006240 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006241
Douglas Gregor436424c2008-11-18 23:14:02 +00006242 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006243 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00006244 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00006245 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006246 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006247 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006248 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor436424c2008-11-18 23:14:02 +00006249
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006250 unsigned NumParams = Proto->getNumParams();
Douglas Gregor436424c2008-11-18 23:14:02 +00006251
6252 // (C++ 13.3.2p2): A candidate function having fewer than m
6253 // parameters is viable only if it has an ellipsis in its parameter
6254 // list (8.3.5).
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006255 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6256 !Proto->isVariadic()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006257 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006258 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00006259 return;
6260 }
6261
6262 // (C++ 13.3.2p2): A candidate function having more than m parameters
6263 // is viable only if the (m+1)st parameter has a default argument
6264 // (8.3.6). For the purposes of overload resolution, the
6265 // parameter list is truncated on the right, so that there are
6266 // exactly m parameters.
6267 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006268 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006269 // Not enough arguments.
6270 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006271 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00006272 return;
6273 }
6274
6275 Candidate.Viable = true;
Douglas Gregor436424c2008-11-18 23:14:02 +00006276
John McCall6e9f8f62009-12-03 04:06:58 +00006277 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006278 // The implicit object argument is ignored.
6279 Candidate.IgnoreObjectArgument = true;
6280 else {
6281 // Determine the implicit conversion sequence for the object
6282 // parameter.
Richard Smith0f59cb32015-12-18 21:45:41 +00006283 Candidate.Conversions[0] = TryObjectArgumentInitialization(
6284 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6285 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00006286 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006287 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006288 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006289 return;
6290 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006291 }
6292
Eli Bendersky291a57e2014-09-25 23:59:08 +00006293 // (CUDA B.1): Check for invalid calls between targets.
6294 if (getLangOpts().CUDA)
6295 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
Justin Lebarb0080032016-08-10 01:09:11 +00006296 if (!IsAllowedCUDACall(Caller, Method)) {
Eli Bendersky291a57e2014-09-25 23:59:08 +00006297 Candidate.Viable = false;
6298 Candidate.FailureKind = ovl_fail_bad_target;
6299 return;
6300 }
6301
Douglas Gregor436424c2008-11-18 23:14:02 +00006302 // Determine the implicit conversion sequences for each of the
6303 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006304 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006305 if (ArgIdx < NumParams) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006306 // (C++ 13.3.2p3): for F to be a viable function, there shall
6307 // exist for each argument an implicit conversion sequence
6308 // (13.3.3.1) that converts that argument to the corresponding
6309 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00006310 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00006311 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006312 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006313 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00006314 /*InOverloadResolution=*/true,
6315 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006316 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00006317 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006318 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006319 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006320 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00006321 }
6322 } else {
6323 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6324 // argument for which there is no corresponding parameter is
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006325 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006326 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00006327 }
6328 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006329
6330 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6331 Candidate.Viable = false;
6332 Candidate.FailureKind = ovl_fail_enable_if;
6333 Candidate.DeductionFailure.Data = FailedAttr;
6334 return;
6335 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006336}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006337
Douglas Gregor97628d62009-08-21 00:16:32 +00006338/// \brief Add a C++ member function template as a candidate to the candidate
6339/// set, using template argument deduction to produce an appropriate member
6340/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00006341void
Douglas Gregor97628d62009-08-21 00:16:32 +00006342Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00006343 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006344 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006345 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006346 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006347 Expr::Classification ObjectClassification,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006348 ArrayRef<Expr *> Args,
Douglas Gregor97628d62009-08-21 00:16:32 +00006349 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006350 bool SuppressUserConversions,
6351 bool PartialOverloading) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006352 if (!CandidateSet.isNewCandidate(MethodTmpl))
6353 return;
6354
Douglas Gregor97628d62009-08-21 00:16:32 +00006355 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00006356 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00006357 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00006358 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00006359 // candidate functions in the usual way.113) A given name can refer to one
6360 // or more function templates and also to a set of overloaded non-template
6361 // functions. In such a case, the candidate functions generated from each
6362 // function template are combined with the set of non-template candidate
6363 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00006364 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006365 FunctionDecl *Specialization = nullptr;
Douglas Gregor97628d62009-08-21 00:16:32 +00006366 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006367 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006368 Specialization, Info, PartialOverloading)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006369 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006370 Candidate.FoundDecl = FoundDecl;
6371 Candidate.Function = MethodTmpl->getTemplatedDecl();
6372 Candidate.Viable = false;
6373 Candidate.FailureKind = ovl_fail_bad_deduction;
6374 Candidate.IsSurrogate = false;
6375 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006376 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006377 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006378 Info);
6379 return;
6380 }
Mike Stump11289f42009-09-09 15:08:12 +00006381
Douglas Gregor97628d62009-08-21 00:16:32 +00006382 // Add the function template specialization produced by template argument
6383 // deduction as a candidate.
6384 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00006385 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00006386 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00006387 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006388 ActingContext, ObjectType, ObjectClassification, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006389 CandidateSet, SuppressUserConversions, PartialOverloading);
Douglas Gregor97628d62009-08-21 00:16:32 +00006390}
6391
Douglas Gregor05155d82009-08-21 23:19:43 +00006392/// \brief Add a C++ function template specialization as a candidate
6393/// in the candidate set, using template argument deduction to produce
6394/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00006395void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006396Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00006397 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006398 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006399 ArrayRef<Expr *> Args,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006400 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006401 bool SuppressUserConversions,
6402 bool PartialOverloading) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006403 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6404 return;
6405
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006406 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00006407 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006408 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00006409 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006410 // candidate functions in the usual way.113) A given name can refer to one
6411 // or more function templates and also to a set of overloaded non-template
6412 // functions. In such a case, the candidate functions generated from each
6413 // function template are combined with the set of non-template candidate
6414 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00006415 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006416 FunctionDecl *Specialization = nullptr;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006417 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006418 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006419 Specialization, Info, PartialOverloading)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006420 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCalla0296f72010-03-19 07:35:19 +00006421 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00006422 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6423 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006424 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00006425 Candidate.IsSurrogate = false;
6426 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006427 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006428 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006429 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006430 return;
6431 }
Mike Stump11289f42009-09-09 15:08:12 +00006432
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006433 // Add the function template specialization produced by template argument
6434 // deduction as a candidate.
6435 assert(Specialization && "Missing function template specialization?");
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006436 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006437 SuppressUserConversions, PartialOverloading);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006438}
Mike Stump11289f42009-09-09 15:08:12 +00006439
Douglas Gregor4b60a152013-11-07 22:34:54 +00006440/// Determine whether this is an allowable conversion from the result
6441/// of an explicit conversion operator to the expected type, per C++
6442/// [over.match.conv]p1 and [over.match.ref]p1.
6443///
6444/// \param ConvType The return type of the conversion function.
6445///
6446/// \param ToType The type we are converting to.
6447///
6448/// \param AllowObjCPointerConversion Allow a conversion from one
6449/// Objective-C pointer to another.
6450///
6451/// \returns true if the conversion is allowable, false otherwise.
6452static bool isAllowableExplicitConversion(Sema &S,
6453 QualType ConvType, QualType ToType,
6454 bool AllowObjCPointerConversion) {
6455 QualType ToNonRefType = ToType.getNonReferenceType();
6456
6457 // Easy case: the types are the same.
6458 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6459 return true;
6460
6461 // Allow qualification conversions.
6462 bool ObjCLifetimeConversion;
6463 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6464 ObjCLifetimeConversion))
6465 return true;
6466
6467 // If we're not allowed to consider Objective-C pointer conversions,
6468 // we're done.
6469 if (!AllowObjCPointerConversion)
6470 return false;
6471
6472 // Is this an Objective-C pointer conversion?
6473 bool IncompatibleObjC = false;
6474 QualType ConvertedType;
6475 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6476 IncompatibleObjC);
6477}
6478
Douglas Gregora1f013e2008-11-07 22:36:19 +00006479/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00006480/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00006481/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00006482/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00006483/// (which may or may not be the same type as the type that the
6484/// conversion function produces).
6485void
6486Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006487 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006488 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00006489 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006490 OverloadCandidateSet& CandidateSet,
6491 bool AllowObjCConversionOnExplicit) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006492 assert(!Conversion->getDescribedFunctionTemplate() &&
6493 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00006494 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006495 if (!CandidateSet.isNewCandidate(Conversion))
6496 return;
6497
Richard Smith2a7d4812013-05-04 07:00:32 +00006498 // If the conversion function has an undeduced return type, trigger its
6499 // deduction now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006500 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00006501 if (DeduceReturnType(Conversion, From->getExprLoc()))
6502 return;
6503 ConvType = Conversion->getConversionType().getNonReferenceType();
6504 }
6505
Richard Smith089c3162013-09-21 21:55:46 +00006506 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6507 // operator is only a candidate if its return type is the target type or
6508 // can be converted to the target type with a qualification conversion.
Douglas Gregor4b60a152013-11-07 22:34:54 +00006509 if (Conversion->isExplicit() &&
6510 !isAllowableExplicitConversion(*this, ConvType, ToType,
6511 AllowObjCConversionOnExplicit))
Richard Smith089c3162013-09-21 21:55:46 +00006512 return;
6513
Douglas Gregor27381f32009-11-23 12:27:39 +00006514 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006515 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006516
Douglas Gregora1f013e2008-11-07 22:36:19 +00006517 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006518 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCalla0296f72010-03-19 07:35:19 +00006519 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006520 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006521 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006522 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006523 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00006524 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00006525 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00006526 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006527 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006528
Douglas Gregor6affc782010-08-19 15:37:02 +00006529 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006530 // For conversion functions, the function is considered to be a member of
6531 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00006532 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006533 //
6534 // Determine the implicit conversion sequence for the implicit
6535 // object parameter.
6536 QualType ImplicitParamType = From->getType();
6537 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6538 ImplicitParamType = FromPtrType->getPointeeType();
6539 CXXRecordDecl *ConversionContext
6540 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006541
Richard Smith0f59cb32015-12-18 21:45:41 +00006542 Candidate.Conversions[0] = TryObjectArgumentInitialization(
6543 *this, CandidateSet.getLocation(), From->getType(),
6544 From->Classify(Context), Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006545
John McCall0d1da222010-01-12 00:44:57 +00006546 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006547 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006548 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006549 return;
6550 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006551
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006552 // We won't go through a user-defined type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006553 // derived to base as such conversions are given Conversion Rank. They only
6554 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6555 QualType FromCanon
6556 = Context.getCanonicalType(From->getType().getUnqualifiedType());
6557 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
Richard Smith0f59cb32015-12-18 21:45:41 +00006558 if (FromCanon == ToCanon ||
6559 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006560 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006561 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006562 return;
6563 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006564
Douglas Gregora1f013e2008-11-07 22:36:19 +00006565 // To determine what the conversion from the result of calling the
6566 // conversion function to the type we're eventually trying to
6567 // convert to (ToType), we need to synthesize a call to the
6568 // conversion function and attempt copy initialization from it. This
6569 // makes sure that we get the right semantics with respect to
6570 // lvalues/rvalues and the type. Fortunately, we can allocate this
6571 // call on the stack and we don't need its arguments to be
6572 // well-formed.
John McCall113bee02012-03-10 09:33:50 +00006573 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00006574 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00006575 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6576 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00006577 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00006578 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00006579
Richard Smith48d24642011-07-13 22:53:21 +00006580 QualType ConversionType = Conversion->getConversionType();
Richard Smithdb0ac552015-12-18 22:40:25 +00006581 if (!isCompleteType(From->getLocStart(), ConversionType)) {
Douglas Gregor72ebdab2010-11-13 19:36:57 +00006582 Candidate.Viable = false;
6583 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6584 return;
6585 }
6586
Richard Smith48d24642011-07-13 22:53:21 +00006587 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCall7decc9e2010-11-18 06:31:45 +00006588
Mike Stump11289f42009-09-09 15:08:12 +00006589 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00006590 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6591 // allocator).
Richard Smith48d24642011-07-13 22:53:21 +00006592 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00006593 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00006594 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00006595 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006596 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00006597 /*SuppressUserConversions=*/true,
John McCall31168b02011-06-15 23:02:42 +00006598 /*InOverloadResolution=*/false,
6599 /*AllowObjCWritebackConversion=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00006600
John McCall0d1da222010-01-12 00:44:57 +00006601 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006602 case ImplicitConversionSequence::StandardConversion:
6603 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006604
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006605 // C++ [over.ics.user]p3:
6606 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006607 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006608 // shall have exact match rank.
6609 if (Conversion->getPrimaryTemplate() &&
6610 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6611 Candidate.Viable = false;
6612 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006613 return;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006614 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006615
Douglas Gregorcba72b12011-01-21 05:18:22 +00006616 // C++0x [dcl.init.ref]p5:
6617 // In the second case, if the reference is an rvalue reference and
6618 // the second standard conversion sequence of the user-defined
6619 // conversion sequence includes an lvalue-to-rvalue conversion, the
6620 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006621 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00006622 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6623 Candidate.Viable = false;
6624 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006625 return;
Douglas Gregorcba72b12011-01-21 05:18:22 +00006626 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00006627 break;
6628
6629 case ImplicitConversionSequence::BadConversion:
6630 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006631 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006632 return;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006633
6634 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006635 llvm_unreachable(
Douglas Gregora1f013e2008-11-07 22:36:19 +00006636 "Can only end up with a standard conversion sequence or failure");
6637 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006638
Craig Topper5fc8fc22014-08-27 06:28:36 +00006639 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006640 Candidate.Viable = false;
6641 Candidate.FailureKind = ovl_fail_enable_if;
6642 Candidate.DeductionFailure.Data = FailedAttr;
6643 return;
6644 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00006645}
6646
Douglas Gregor05155d82009-08-21 23:19:43 +00006647/// \brief Adds a conversion function template specialization
6648/// candidate to the overload set, using template argument deduction
6649/// to deduce the template arguments of the conversion function
6650/// template from the type that we are converting to (C++
6651/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00006652void
Douglas Gregor05155d82009-08-21 23:19:43 +00006653Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00006654 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006655 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00006656 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006657 OverloadCandidateSet &CandidateSet,
6658 bool AllowObjCConversionOnExplicit) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006659 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
6660 "Only conversion function templates permitted here");
6661
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006662 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6663 return;
6664
Craig Toppere6706e42012-09-19 02:26:47 +00006665 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006666 CXXConversionDecl *Specialization = nullptr;
Douglas Gregor05155d82009-08-21 23:19:43 +00006667 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00006668 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00006669 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006670 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006671 Candidate.FoundDecl = FoundDecl;
6672 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6673 Candidate.Viable = false;
6674 Candidate.FailureKind = ovl_fail_bad_deduction;
6675 Candidate.IsSurrogate = false;
6676 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006677 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006678 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006679 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00006680 return;
6681 }
Mike Stump11289f42009-09-09 15:08:12 +00006682
Douglas Gregor05155d82009-08-21 23:19:43 +00006683 // Add the conversion function template specialization produced by
6684 // template argument deduction as a candidate.
6685 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00006686 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006687 CandidateSet, AllowObjCConversionOnExplicit);
Douglas Gregor05155d82009-08-21 23:19:43 +00006688}
6689
Douglas Gregorab7897a2008-11-19 22:57:39 +00006690/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
6691/// converts the given @c Object to a function pointer via the
6692/// conversion function @c Conversion, and then attempts to call it
6693/// with the given arguments (C++ [over.call.object]p2-4). Proto is
6694/// the type of function that we'll eventually be calling.
6695void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006696 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006697 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006698 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00006699 Expr *Object,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006700 ArrayRef<Expr *> Args,
Douglas Gregorab7897a2008-11-19 22:57:39 +00006701 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006702 if (!CandidateSet.isNewCandidate(Conversion))
6703 return;
6704
Douglas Gregor27381f32009-11-23 12:27:39 +00006705 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006706 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006707
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006708 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00006709 Candidate.FoundDecl = FoundDecl;
Craig Topperc3ec1492014-05-26 06:22:03 +00006710 Candidate.Function = nullptr;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006711 Candidate.Surrogate = Conversion;
6712 Candidate.Viable = true;
6713 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006714 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006715 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006716
6717 // Determine the implicit conversion sequence for the implicit
6718 // object parameter.
Richard Smith0f59cb32015-12-18 21:45:41 +00006719 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
6720 *this, CandidateSet.getLocation(), Object->getType(),
6721 Object->Classify(Context), Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00006722 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006723 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006724 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00006725 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006726 return;
6727 }
6728
6729 // The first conversion is actually a user-defined conversion whose
6730 // first conversion is ObjectInit's standard conversion (which is
6731 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00006732 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006733 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00006734 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006735 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006736 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00006737 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump11289f42009-09-09 15:08:12 +00006738 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00006739 = Candidate.Conversions[0].UserDefined.Before;
6740 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
6741
Mike Stump11289f42009-09-09 15:08:12 +00006742 // Find the
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006743 unsigned NumParams = Proto->getNumParams();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006744
6745 // (C++ 13.3.2p2): A candidate function having fewer than m
6746 // parameters is viable only if it has an ellipsis in its parameter
6747 // list (8.3.5).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006748 if (Args.size() > NumParams && !Proto->isVariadic()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006749 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006750 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006751 return;
6752 }
6753
6754 // Function types don't have any default arguments, so just check if
6755 // we have enough arguments.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006756 if (Args.size() < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006757 // Not enough arguments.
6758 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006759 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006760 return;
6761 }
6762
6763 // Determine the implicit conversion sequences for each of the
6764 // arguments.
Richard Smithe54c3072013-05-05 15:51:06 +00006765 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006766 if (ArgIdx < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006767 // (C++ 13.3.2p3): for F to be a viable function, there shall
6768 // exist for each argument an implicit conversion sequence
6769 // (13.3.3.1) that converts that argument to the corresponding
6770 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00006771 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00006772 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006773 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00006774 /*SuppressUserConversions=*/false,
John McCall31168b02011-06-15 23:02:42 +00006775 /*InOverloadResolution=*/false,
6776 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006777 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00006778 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006779 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006780 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006781 return;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006782 }
6783 } else {
6784 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6785 // argument for which there is no corresponding parameter is
6786 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006787 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006788 }
6789 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006790
Craig Topper5fc8fc22014-08-27 06:28:36 +00006791 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006792 Candidate.Viable = false;
6793 Candidate.FailureKind = ovl_fail_enable_if;
6794 Candidate.DeductionFailure.Data = FailedAttr;
6795 return;
6796 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00006797}
6798
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006799/// \brief Add overload candidates for overloaded operators that are
6800/// member functions.
6801///
6802/// Add the overloaded operator candidates that are member functions
6803/// for the operator Op that was used in an operator expression such
6804/// as "x Op y". , Args/NumArgs provides the operator arguments, and
6805/// CandidateSet will store the added overload candidates. (C++
6806/// [over.match.oper]).
6807void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
6808 SourceLocation OpLoc,
Richard Smithe54c3072013-05-05 15:51:06 +00006809 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006810 OverloadCandidateSet& CandidateSet,
6811 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006812 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6813
6814 // C++ [over.match.oper]p3:
6815 // For a unary operator @ with an operand of a type whose
6816 // cv-unqualified version is T1, and for a binary operator @ with
6817 // a left operand of a type whose cv-unqualified version is T1 and
6818 // a right operand of a type whose cv-unqualified version is T2,
6819 // three sets of candidate functions, designated member
6820 // candidates, non-member candidates and built-in candidates, are
6821 // constructed as follows:
6822 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00006823
Richard Smith0feaf0c2013-04-20 12:41:22 +00006824 // -- If T1 is a complete class type or a class currently being
6825 // defined, the set of member candidates is the result of the
6826 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
6827 // the set of member candidates is empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006828 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Richard Smith0feaf0c2013-04-20 12:41:22 +00006829 // Complete the type if it can be completed.
Richard Smithdb0ac552015-12-18 22:40:25 +00006830 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
Richard Smith82b8d4e2015-12-18 22:19:11 +00006831 return;
Richard Smith0feaf0c2013-04-20 12:41:22 +00006832 // If the type is neither complete nor being defined, bail out now.
6833 if (!T1Rec->getDecl()->getDefinition())
Douglas Gregor6a1f9652009-08-27 23:35:55 +00006834 return;
Mike Stump11289f42009-09-09 15:08:12 +00006835
John McCall27b18f82009-11-17 02:14:36 +00006836 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6837 LookupQualifiedName(Operators, T1Rec->getDecl());
6838 Operators.suppressDiagnostics();
6839
Mike Stump11289f42009-09-09 15:08:12 +00006840 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00006841 OperEnd = Operators.end();
6842 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00006843 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00006844 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
Rafael Espindola51629df2013-04-29 19:29:25 +00006845 Args[0]->Classify(Context),
Richard Smithe54c3072013-05-05 15:51:06 +00006846 Args.slice(1),
Douglas Gregor02824322011-01-26 19:30:28 +00006847 CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00006848 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00006849 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006850}
6851
Douglas Gregora11693b2008-11-12 17:17:38 +00006852/// AddBuiltinCandidate - Add a candidate for a built-in
6853/// operator. ResultTy and ParamTys are the result and parameter types
6854/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00006855/// arguments being passed to the candidate. IsAssignmentOperator
6856/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00006857/// operator. NumContextualBoolArguments is the number of arguments
6858/// (at the beginning of the argument list) that will be contextually
6859/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00006860void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Richard Smithe54c3072013-05-05 15:51:06 +00006861 ArrayRef<Expr *> Args,
Douglas Gregorc5e61072009-01-13 00:52:54 +00006862 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00006863 bool IsAssignmentOperator,
6864 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00006865 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006866 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006867
Douglas Gregora11693b2008-11-12 17:17:38 +00006868 // Add this candidate
Richard Smithe54c3072013-05-05 15:51:06 +00006869 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
Craig Topperc3ec1492014-05-26 06:22:03 +00006870 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
6871 Candidate.Function = nullptr;
Douglas Gregor1d248c52008-12-12 02:00:36 +00006872 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006873 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00006874 Candidate.BuiltinTypes.ResultTy = ResultTy;
Richard Smithe54c3072013-05-05 15:51:06 +00006875 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Douglas Gregora11693b2008-11-12 17:17:38 +00006876 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6877
6878 // Determine the implicit conversion sequences for each of the
6879 // arguments.
6880 Candidate.Viable = true;
Richard Smithe54c3072013-05-05 15:51:06 +00006881 Candidate.ExplicitCallArguments = Args.size();
6882 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00006883 // C++ [over.match.oper]p4:
6884 // For the built-in assignment operators, conversions of the
6885 // left operand are restricted as follows:
6886 // -- no temporaries are introduced to hold the left operand, and
6887 // -- no user-defined conversions are applied to the left
6888 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00006889 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00006890 //
6891 // We block these conversions by turning off user-defined
6892 // conversions, since that is the only way that initialization of
6893 // a reference to a non-class type can occur from something that
6894 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00006895 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00006896 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00006897 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00006898 Candidate.Conversions[ArgIdx]
6899 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006900 } else {
Mike Stump11289f42009-09-09 15:08:12 +00006901 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006902 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00006903 ArgIdx == 0 && IsAssignmentOperator,
John McCall31168b02011-06-15 23:02:42 +00006904 /*InOverloadResolution=*/false,
6905 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006906 getLangOpts().ObjCAutoRefCount);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006907 }
John McCall0d1da222010-01-12 00:44:57 +00006908 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006909 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006910 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00006911 break;
6912 }
Douglas Gregora11693b2008-11-12 17:17:38 +00006913 }
6914}
6915
Craig Toppercd7b0332013-07-01 06:29:40 +00006916namespace {
6917
Douglas Gregora11693b2008-11-12 17:17:38 +00006918/// BuiltinCandidateTypeSet - A set of types that will be used for the
6919/// candidate operator functions for built-in operators (C++
6920/// [over.built]). The types are separated into pointer types and
6921/// enumeration types.
6922class BuiltinCandidateTypeSet {
6923 /// TypeSet - A set of types.
Richard Smith95853072016-03-25 00:08:53 +00006924 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
6925 llvm::SmallPtrSet<QualType, 8>> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00006926
6927 /// PointerTypes - The set of pointer types that will be used in the
6928 /// built-in candidates.
6929 TypeSet PointerTypes;
6930
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006931 /// MemberPointerTypes - The set of member pointer types that will be
6932 /// used in the built-in candidates.
6933 TypeSet MemberPointerTypes;
6934
Douglas Gregora11693b2008-11-12 17:17:38 +00006935 /// EnumerationTypes - The set of enumeration types that will be
6936 /// used in the built-in candidates.
6937 TypeSet EnumerationTypes;
6938
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006939 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006940 /// candidates.
6941 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00006942
6943 /// \brief A flag indicating non-record types are viable candidates
6944 bool HasNonRecordTypes;
6945
6946 /// \brief A flag indicating whether either arithmetic or enumeration types
6947 /// were present in the candidate set.
6948 bool HasArithmeticOrEnumeralTypes;
6949
Douglas Gregor80af3132011-05-21 23:15:46 +00006950 /// \brief A flag indicating whether the nullptr type was present in the
6951 /// candidate set.
6952 bool HasNullPtrType;
6953
Douglas Gregor8a2e6012009-08-24 15:23:48 +00006954 /// Sema - The semantic analysis instance where we are building the
6955 /// candidate type set.
6956 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00006957
Douglas Gregora11693b2008-11-12 17:17:38 +00006958 /// Context - The AST context in which we will build the type sets.
6959 ASTContext &Context;
6960
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006961 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6962 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006963 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00006964
6965public:
6966 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006967 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00006968
Mike Stump11289f42009-09-09 15:08:12 +00006969 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00006970 : HasNonRecordTypes(false),
6971 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor80af3132011-05-21 23:15:46 +00006972 HasNullPtrType(false),
Chandler Carruth00a38332010-12-13 01:44:01 +00006973 SemaRef(SemaRef),
6974 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00006975
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006976 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006977 SourceLocation Loc,
6978 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006979 bool AllowExplicitConversions,
6980 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00006981
6982 /// pointer_begin - First pointer type found;
6983 iterator pointer_begin() { return PointerTypes.begin(); }
6984
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006985 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006986 iterator pointer_end() { return PointerTypes.end(); }
6987
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006988 /// member_pointer_begin - First member pointer type found;
6989 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6990
6991 /// member_pointer_end - Past the last member pointer type found;
6992 iterator member_pointer_end() { return MemberPointerTypes.end(); }
6993
Douglas Gregora11693b2008-11-12 17:17:38 +00006994 /// enumeration_begin - First enumeration type found;
6995 iterator enumeration_begin() { return EnumerationTypes.begin(); }
6996
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006997 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006998 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006999
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007000 iterator vector_begin() { return VectorTypes.begin(); }
7001 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00007002
7003 bool hasNonRecordTypes() { return HasNonRecordTypes; }
7004 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor80af3132011-05-21 23:15:46 +00007005 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregora11693b2008-11-12 17:17:38 +00007006};
7007
Craig Toppercd7b0332013-07-01 06:29:40 +00007008} // end anonymous namespace
7009
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007010/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00007011/// the set of pointer types along with any more-qualified variants of
7012/// that type. For example, if @p Ty is "int const *", this routine
7013/// will add "int const *", "int const volatile *", "int const
7014/// restrict *", and "int const volatile restrict *" to the set of
7015/// pointer types. Returns true if the add of @p Ty itself succeeded,
7016/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00007017///
7018/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007019bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007020BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7021 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00007022
Douglas Gregora11693b2008-11-12 17:17:38 +00007023 // Insert this type.
Richard Smith95853072016-03-25 00:08:53 +00007024 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00007025 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007026
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00007027 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00007028 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00007029 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00007030 if (!PointerTy) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00007031 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7032 PointeeTy = PTy->getPointeeType();
7033 buildObjCPtr = true;
7034 } else {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00007035 PointeeTy = PointerTy->getPointeeType();
Douglas Gregor5bee2582012-06-04 00:15:09 +00007036 }
7037
Sebastian Redl4990a632009-11-18 20:39:26 +00007038 // Don't add qualified variants of arrays. For one, they're not allowed
7039 // (the qualifier would sink to the element type), and for another, the
7040 // only overload situation where it matters is subscript or pointer +- int,
7041 // and those shouldn't have qualifier variants anyway.
7042 if (PointeeTy->isArrayType())
7043 return true;
Douglas Gregor5bee2582012-06-04 00:15:09 +00007044
John McCall8ccfcb52009-09-24 19:53:00 +00007045 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007046 bool hasVolatile = VisibleQuals.hasVolatile();
7047 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007048
John McCall8ccfcb52009-09-24 19:53:00 +00007049 // Iterate through all strict supersets of BaseCVR.
7050 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7051 if ((CVR | BaseCVR) != CVR) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00007052 // Skip over volatile if no volatile found anywhere in the types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007053 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00007054
7055 // Skip over restrict if no restrict found anywhere in the types, or if
7056 // the type cannot be restrict-qualified.
7057 if ((CVR & Qualifiers::Restrict) &&
7058 (!hasRestrict ||
7059 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7060 continue;
7061
7062 // Build qualified pointee type.
John McCall8ccfcb52009-09-24 19:53:00 +00007063 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007064
7065 // Build qualified pointer type.
7066 QualType QPointerTy;
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00007067 if (!buildObjCPtr)
Douglas Gregor5bee2582012-06-04 00:15:09 +00007068 QPointerTy = Context.getPointerType(QPointeeTy);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00007069 else
Douglas Gregor5bee2582012-06-04 00:15:09 +00007070 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
7071
7072 // Insert qualified pointer type.
7073 PointerTypes.insert(QPointerTy);
Douglas Gregora11693b2008-11-12 17:17:38 +00007074 }
7075
7076 return true;
7077}
7078
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007079/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7080/// to the set of pointer types along with any more-qualified variants of
7081/// that type. For example, if @p Ty is "int const *", this routine
7082/// will add "int const *", "int const volatile *", "int const
7083/// restrict *", and "int const volatile restrict *" to the set of
7084/// pointer types. Returns true if the add of @p Ty itself succeeded,
7085/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00007086///
7087/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007088bool
7089BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7090 QualType Ty) {
7091 // Insert this type.
Richard Smith95853072016-03-25 00:08:53 +00007092 if (!MemberPointerTypes.insert(Ty))
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007093 return false;
7094
John McCall8ccfcb52009-09-24 19:53:00 +00007095 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
7096 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007097
John McCall8ccfcb52009-09-24 19:53:00 +00007098 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00007099 // Don't add qualified variants of arrays. For one, they're not allowed
7100 // (the qualifier would sink to the element type), and for another, the
7101 // only overload situation where it matters is subscript or pointer +- int,
7102 // and those shouldn't have qualifier variants anyway.
7103 if (PointeeTy->isArrayType())
7104 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00007105 const Type *ClassTy = PointerTy->getClass();
7106
7107 // Iterate through all strict supersets of the pointee type's CVR
7108 // qualifiers.
7109 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7110 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7111 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007112
John McCall8ccfcb52009-09-24 19:53:00 +00007113 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00007114 MemberPointerTypes.insert(
7115 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007116 }
7117
7118 return true;
7119}
7120
Douglas Gregora11693b2008-11-12 17:17:38 +00007121/// AddTypesConvertedFrom - Add each of the types to which the type @p
7122/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007123/// primarily interested in pointer types and enumeration types. We also
7124/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00007125/// AllowUserConversions is true if we should look at the conversion
7126/// functions of a class type, and AllowExplicitConversions if we
7127/// should also include the explicit conversion functions of a class
7128/// type.
Mike Stump11289f42009-09-09 15:08:12 +00007129void
Douglas Gregor5fb53972009-01-14 15:45:31 +00007130BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007131 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00007132 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007133 bool AllowExplicitConversions,
7134 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007135 // Only deal with canonical types.
7136 Ty = Context.getCanonicalType(Ty);
7137
7138 // Look through reference types; they aren't part of the type of an
7139 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007140 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00007141 Ty = RefTy->getPointeeType();
7142
John McCall33ddac02011-01-19 10:06:00 +00007143 // If we're dealing with an array type, decay to the pointer.
7144 if (Ty->isArrayType())
7145 Ty = SemaRef.Context.getArrayDecayedType(Ty);
7146
7147 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007148 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00007149
Chandler Carruth00a38332010-12-13 01:44:01 +00007150 // Flag if we ever add a non-record type.
7151 const RecordType *TyRec = Ty->getAs<RecordType>();
7152 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7153
Chandler Carruth00a38332010-12-13 01:44:01 +00007154 // Flag if we encounter an arithmetic type.
7155 HasArithmeticOrEnumeralTypes =
7156 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7157
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00007158 if (Ty->isObjCIdType() || Ty->isObjCClassType())
7159 PointerTypes.insert(Ty);
7160 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007161 // Insert our type, and its more-qualified variants, into the set
7162 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007163 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00007164 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007165 } else if (Ty->isMemberPointerType()) {
7166 // Member pointers are far easier, since the pointee can't be converted.
7167 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7168 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00007169 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007170 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00007171 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007172 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007173 // We treat vector types as arithmetic types in many contexts as an
7174 // extension.
7175 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007176 VectorTypes.insert(Ty);
Douglas Gregor80af3132011-05-21 23:15:46 +00007177 } else if (Ty->isNullPtrType()) {
7178 HasNullPtrType = true;
Chandler Carruth00a38332010-12-13 01:44:01 +00007179 } else if (AllowUserConversions && TyRec) {
7180 // No conversion functions in incomplete types.
Richard Smithdb0ac552015-12-18 22:40:25 +00007181 if (!SemaRef.isCompleteType(Loc, Ty))
Chandler Carruth00a38332010-12-13 01:44:01 +00007182 return;
Mike Stump11289f42009-09-09 15:08:12 +00007183
Chandler Carruth00a38332010-12-13 01:44:01 +00007184 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00007185 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007186 if (isa<UsingShadowDecl>(D))
7187 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00007188
Chandler Carruth00a38332010-12-13 01:44:01 +00007189 // Skip conversion function templates; they don't tell us anything
7190 // about which builtin types we can convert to.
7191 if (isa<FunctionTemplateDecl>(D))
7192 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00007193
Chandler Carruth00a38332010-12-13 01:44:01 +00007194 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7195 if (AllowExplicitConversions || !Conv->isExplicit()) {
7196 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7197 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00007198 }
7199 }
7200 }
7201}
7202
Douglas Gregor84605ae2009-08-24 13:43:27 +00007203/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
7204/// the volatile- and non-volatile-qualified assignment operators for the
7205/// given type to the candidate set.
7206static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7207 QualType T,
Richard Smithe54c3072013-05-05 15:51:06 +00007208 ArrayRef<Expr *> Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00007209 OverloadCandidateSet &CandidateSet) {
7210 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00007211
Douglas Gregor84605ae2009-08-24 13:43:27 +00007212 // T& operator=(T&, T)
7213 ParamTypes[0] = S.Context.getLValueReferenceType(T);
7214 ParamTypes[1] = T;
Richard Smithe54c3072013-05-05 15:51:06 +00007215 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor84605ae2009-08-24 13:43:27 +00007216 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00007217
Douglas Gregor84605ae2009-08-24 13:43:27 +00007218 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7219 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00007220 ParamTypes[0]
7221 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00007222 ParamTypes[1] = T;
Richard Smithe54c3072013-05-05 15:51:06 +00007223 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00007224 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00007225 }
7226}
Mike Stump11289f42009-09-09 15:08:12 +00007227
Sebastian Redl1054fae2009-10-25 17:03:50 +00007228/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7229/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007230static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7231 Qualifiers VRQuals;
7232 const RecordType *TyRec;
7233 if (const MemberPointerType *RHSMPType =
7234 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00007235 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007236 else
7237 TyRec = ArgExpr->getType()->getAs<RecordType>();
7238 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007239 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007240 VRQuals.addVolatile();
7241 VRQuals.addRestrict();
7242 return VRQuals;
7243 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007244
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007245 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00007246 if (!ClassDecl->hasDefinition())
7247 return VRQuals;
7248
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00007249 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
John McCallda4458e2010-03-31 01:36:47 +00007250 if (isa<UsingShadowDecl>(D))
7251 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7252 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007253 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7254 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7255 CanTy = ResTypeRef->getPointeeType();
7256 // Need to go down the pointer/mempointer chain and add qualifiers
7257 // as see them.
7258 bool done = false;
7259 while (!done) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00007260 if (CanTy.isRestrictQualified())
7261 VRQuals.addRestrict();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007262 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7263 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007264 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007265 CanTy->getAs<MemberPointerType>())
7266 CanTy = ResTypeMPtr->getPointeeType();
7267 else
7268 done = true;
7269 if (CanTy.isVolatileQualified())
7270 VRQuals.addVolatile();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007271 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7272 return VRQuals;
7273 }
7274 }
7275 }
7276 return VRQuals;
7277}
John McCall52872982010-11-13 05:51:15 +00007278
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007279namespace {
John McCall52872982010-11-13 05:51:15 +00007280
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007281/// \brief Helper class to manage the addition of builtin operator overload
7282/// candidates. It provides shared state and utility methods used throughout
7283/// the process, as well as a helper method to add each group of builtin
7284/// operator overloads from the standard to a candidate set.
7285class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007286 // Common instance state available to all overload candidate addition methods.
7287 Sema &S;
Richard Smithe54c3072013-05-05 15:51:06 +00007288 ArrayRef<Expr *> Args;
Chandler Carruthc6586e52010-12-12 10:35:00 +00007289 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00007290 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007291 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruthc6586e52010-12-12 10:35:00 +00007292 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007293
Chandler Carruthc6586e52010-12-12 10:35:00 +00007294 // Define some constants used to index and iterate over the arithemetic types
7295 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00007296 // The "promoted arithmetic types" are the arithmetic
7297 // types are that preserved by promotion (C++ [over.built]p2).
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00007298 static const unsigned FirstIntegralType = 4;
7299 static const unsigned LastIntegralType = 21;
7300 static const unsigned FirstPromotedIntegralType = 4,
7301 LastPromotedIntegralType = 12;
John McCall52872982010-11-13 05:51:15 +00007302 static const unsigned FirstPromotedArithmeticType = 0,
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00007303 LastPromotedArithmeticType = 12;
7304 static const unsigned NumArithmeticTypes = 21;
John McCall52872982010-11-13 05:51:15 +00007305
Chandler Carruthc6586e52010-12-12 10:35:00 +00007306 /// \brief Get the canonical type for a given arithmetic type index.
7307 CanQualType getArithmeticType(unsigned index) {
7308 assert(index < NumArithmeticTypes);
7309 static CanQualType ASTContext::* const
7310 ArithmeticTypes[NumArithmeticTypes] = {
7311 // Start of promoted types.
7312 &ASTContext::FloatTy,
7313 &ASTContext::DoubleTy,
7314 &ASTContext::LongDoubleTy,
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00007315 &ASTContext::Float128Ty,
John McCall52872982010-11-13 05:51:15 +00007316
Chandler Carruthc6586e52010-12-12 10:35:00 +00007317 // Start of integral types.
7318 &ASTContext::IntTy,
7319 &ASTContext::LongTy,
7320 &ASTContext::LongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00007321 &ASTContext::Int128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00007322 &ASTContext::UnsignedIntTy,
7323 &ASTContext::UnsignedLongTy,
7324 &ASTContext::UnsignedLongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00007325 &ASTContext::UnsignedInt128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00007326 // End of promoted types.
7327
7328 &ASTContext::BoolTy,
7329 &ASTContext::CharTy,
7330 &ASTContext::WCharTy,
7331 &ASTContext::Char16Ty,
7332 &ASTContext::Char32Ty,
7333 &ASTContext::SignedCharTy,
7334 &ASTContext::ShortTy,
7335 &ASTContext::UnsignedCharTy,
7336 &ASTContext::UnsignedShortTy,
7337 // End of integral types.
Richard Smith521ecc12012-06-10 08:00:26 +00007338 // FIXME: What about complex? What about half?
Chandler Carruthc6586e52010-12-12 10:35:00 +00007339 };
7340 return S.Context.*ArithmeticTypes[index];
7341 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007342
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007343 /// \brief Gets the canonical type resulting from the usual arithemetic
7344 /// converions for the given arithmetic types.
7345 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
7346 // Accelerator table for performing the usual arithmetic conversions.
7347 // The rules are basically:
7348 // - if either is floating-point, use the wider floating-point
7349 // - if same signedness, use the higher rank
7350 // - if same size, use unsigned of the higher rank
7351 // - use the larger type
7352 // These rules, together with the axiom that higher ranks are
7353 // never smaller, are sufficient to precompute all of these results
7354 // *except* when dealing with signed types of higher rank.
7355 // (we could precompute SLL x UI for all known platforms, but it's
7356 // better not to make any assumptions).
Richard Smith521ecc12012-06-10 08:00:26 +00007357 // We assume that int128 has a higher rank than long long on all platforms.
George Burgess IVf23ce362016-04-29 21:32:53 +00007358 enum PromotedType : int8_t {
Richard Smith521ecc12012-06-10 08:00:26 +00007359 Dep=-1,
7360 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007361 };
Nuno Lopes9af6b032012-04-21 14:45:25 +00007362 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007363 [LastPromotedArithmeticType] = {
Richard Smith521ecc12012-06-10 08:00:26 +00007364/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
7365/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
7366/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
7367/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
7368/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
7369/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
7370/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
7371/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
7372/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
7373/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
7374/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007375 };
7376
7377 assert(L < LastPromotedArithmeticType);
7378 assert(R < LastPromotedArithmeticType);
7379 int Idx = ConversionsTable[L][R];
7380
7381 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007382 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007383
7384 // Slow path: we need to compare widths.
7385 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007386 CanQualType LT = getArithmeticType(L),
7387 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007388 unsigned LW = S.Context.getIntWidth(LT),
7389 RW = S.Context.getIntWidth(RT);
7390
7391 // If they're different widths, use the signed type.
7392 if (LW > RW) return LT;
7393 else if (LW < RW) return RT;
7394
7395 // Otherwise, use the unsigned type of the signed type's rank.
7396 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
7397 assert(L == SLL || R == SLL);
7398 return S.Context.UnsignedLongLongTy;
7399 }
7400
Chandler Carruth5659c0c2010-12-12 09:22:45 +00007401 /// \brief Helper method to factor out the common pattern of adding overloads
7402 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007403 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007404 bool HasVolatile,
7405 bool HasRestrict) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007406 QualType ParamTypes[2] = {
7407 S.Context.getLValueReferenceType(CandidateTy),
7408 S.Context.IntTy
7409 };
7410
7411 // Non-volatile version.
Richard Smithe54c3072013-05-05 15:51:06 +00007412 if (Args.size() == 1)
7413 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007414 else
Richard Smithe54c3072013-05-05 15:51:06 +00007415 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007416
7417 // Use a heuristic to reduce number of builtin candidates in the set:
7418 // add volatile version only if there are conversions to a volatile type.
7419 if (HasVolatile) {
7420 ParamTypes[0] =
7421 S.Context.getLValueReferenceType(
7422 S.Context.getVolatileType(CandidateTy));
Richard Smithe54c3072013-05-05 15:51:06 +00007423 if (Args.size() == 1)
7424 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007425 else
Richard Smithe54c3072013-05-05 15:51:06 +00007426 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007427 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007428
7429 // Add restrict version only if there are conversions to a restrict type
7430 // and our candidate type is a non-restrict-qualified pointer.
7431 if (HasRestrict && CandidateTy->isAnyPointerType() &&
7432 !CandidateTy.isRestrictQualified()) {
7433 ParamTypes[0]
7434 = S.Context.getLValueReferenceType(
7435 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
Richard Smithe54c3072013-05-05 15:51:06 +00007436 if (Args.size() == 1)
7437 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007438 else
Richard Smithe54c3072013-05-05 15:51:06 +00007439 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007440
7441 if (HasVolatile) {
7442 ParamTypes[0]
7443 = S.Context.getLValueReferenceType(
7444 S.Context.getCVRQualifiedType(CandidateTy,
7445 (Qualifiers::Volatile |
7446 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007447 if (Args.size() == 1)
7448 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007449 else
Richard Smithe54c3072013-05-05 15:51:06 +00007450 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007451 }
7452 }
7453
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007454 }
7455
7456public:
7457 BuiltinOperatorOverloadBuilder(
Richard Smithe54c3072013-05-05 15:51:06 +00007458 Sema &S, ArrayRef<Expr *> Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007459 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00007460 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007461 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007462 OverloadCandidateSet &CandidateSet)
Richard Smithe54c3072013-05-05 15:51:06 +00007463 : S(S), Args(Args),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007464 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00007465 HasArithmeticOrEnumeralCandidateType(
7466 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007467 CandidateTypes(CandidateTypes),
7468 CandidateSet(CandidateSet) {
7469 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007470 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007471 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007472 assert(getArithmeticType(LastPromotedIntegralType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00007473 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007474 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007475 assert(getArithmeticType(FirstPromotedArithmeticType)
7476 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007477 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007478 assert(getArithmeticType(LastPromotedArithmeticType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00007479 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007480 "Invalid last promoted arithmetic type");
7481 }
7482
7483 // C++ [over.built]p3:
7484 //
7485 // For every pair (T, VQ), where T is an arithmetic type, and VQ
7486 // is either volatile or empty, there exist candidate operator
7487 // functions of the form
7488 //
7489 // VQ T& operator++(VQ T&);
7490 // T operator++(VQ T&, int);
7491 //
7492 // C++ [over.built]p4:
7493 //
7494 // For every pair (T, VQ), where T is an arithmetic type other
7495 // than bool, and VQ is either volatile or empty, there exist
7496 // candidate operator functions of the form
7497 //
7498 // VQ T& operator--(VQ T&);
7499 // T operator--(VQ T&, int);
7500 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007501 if (!HasArithmeticOrEnumeralCandidateType)
7502 return;
7503
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007504 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
7505 Arith < NumArithmeticTypes; ++Arith) {
7506 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00007507 getArithmeticType(Arith),
Douglas Gregor5bee2582012-06-04 00:15:09 +00007508 VisibleTypeConversionsQuals.hasVolatile(),
7509 VisibleTypeConversionsQuals.hasRestrict());
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007510 }
7511 }
7512
7513 // C++ [over.built]p5:
7514 //
7515 // For every pair (T, VQ), where T is a cv-qualified or
7516 // cv-unqualified object type, and VQ is either volatile or
7517 // empty, there exist candidate operator functions of the form
7518 //
7519 // T*VQ& operator++(T*VQ&);
7520 // T*VQ& operator--(T*VQ&);
7521 // T* operator++(T*VQ&, int);
7522 // T* operator--(T*VQ&, int);
7523 void addPlusPlusMinusMinusPointerOverloads() {
7524 for (BuiltinCandidateTypeSet::iterator
7525 Ptr = CandidateTypes[0].pointer_begin(),
7526 PtrEnd = CandidateTypes[0].pointer_end();
7527 Ptr != PtrEnd; ++Ptr) {
7528 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00007529 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007530 continue;
7531
7532 addPlusPlusMinusMinusStyleOverloads(*Ptr,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007533 (!(*Ptr).isVolatileQualified() &&
7534 VisibleTypeConversionsQuals.hasVolatile()),
7535 (!(*Ptr).isRestrictQualified() &&
7536 VisibleTypeConversionsQuals.hasRestrict()));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007537 }
7538 }
7539
7540 // C++ [over.built]p6:
7541 // For every cv-qualified or cv-unqualified object type T, there
7542 // exist candidate operator functions of the form
7543 //
7544 // T& operator*(T*);
7545 //
7546 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007547 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00007548 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007549 // T& operator*(T*);
7550 void addUnaryStarPointerOverloads() {
7551 for (BuiltinCandidateTypeSet::iterator
7552 Ptr = CandidateTypes[0].pointer_begin(),
7553 PtrEnd = CandidateTypes[0].pointer_end();
7554 Ptr != PtrEnd; ++Ptr) {
7555 QualType ParamTy = *Ptr;
7556 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007557 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7558 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007559
Douglas Gregor02824322011-01-26 19:30:28 +00007560 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7561 if (Proto->getTypeQuals() || Proto->getRefQualifier())
7562 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007563
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007564 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
Richard Smithe54c3072013-05-05 15:51:06 +00007565 &ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007566 }
7567 }
7568
7569 // C++ [over.built]p9:
7570 // For every promoted arithmetic type T, there exist candidate
7571 // operator functions of the form
7572 //
7573 // T operator+(T);
7574 // T operator-(T);
7575 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007576 if (!HasArithmeticOrEnumeralCandidateType)
7577 return;
7578
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007579 for (unsigned Arith = FirstPromotedArithmeticType;
7580 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007581 QualType ArithTy = getArithmeticType(Arith);
Richard Smithe54c3072013-05-05 15:51:06 +00007582 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007583 }
7584
7585 // Extension: We also add these operators for vector types.
7586 for (BuiltinCandidateTypeSet::iterator
7587 Vec = CandidateTypes[0].vector_begin(),
7588 VecEnd = CandidateTypes[0].vector_end();
7589 Vec != VecEnd; ++Vec) {
7590 QualType VecTy = *Vec;
Richard Smithe54c3072013-05-05 15:51:06 +00007591 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007592 }
7593 }
7594
7595 // C++ [over.built]p8:
7596 // For every type T, there exist candidate operator functions of
7597 // the form
7598 //
7599 // T* operator+(T*);
7600 void addUnaryPlusPointerOverloads() {
7601 for (BuiltinCandidateTypeSet::iterator
7602 Ptr = CandidateTypes[0].pointer_begin(),
7603 PtrEnd = CandidateTypes[0].pointer_end();
7604 Ptr != PtrEnd; ++Ptr) {
7605 QualType ParamTy = *Ptr;
Richard Smithe54c3072013-05-05 15:51:06 +00007606 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007607 }
7608 }
7609
7610 // C++ [over.built]p10:
7611 // For every promoted integral type T, there exist candidate
7612 // operator functions of the form
7613 //
7614 // T operator~(T);
7615 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007616 if (!HasArithmeticOrEnumeralCandidateType)
7617 return;
7618
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007619 for (unsigned Int = FirstPromotedIntegralType;
7620 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007621 QualType IntTy = getArithmeticType(Int);
Richard Smithe54c3072013-05-05 15:51:06 +00007622 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007623 }
7624
7625 // Extension: We also add this operator for vector types.
7626 for (BuiltinCandidateTypeSet::iterator
7627 Vec = CandidateTypes[0].vector_begin(),
7628 VecEnd = CandidateTypes[0].vector_end();
7629 Vec != VecEnd; ++Vec) {
7630 QualType VecTy = *Vec;
Richard Smithe54c3072013-05-05 15:51:06 +00007631 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007632 }
7633 }
7634
7635 // C++ [over.match.oper]p16:
Richard Smith5e9746f2016-10-21 22:00:42 +00007636 // For every pointer to member type T or type std::nullptr_t, there
7637 // exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007638 //
7639 // bool operator==(T,T);
7640 // bool operator!=(T,T);
Richard Smith5e9746f2016-10-21 22:00:42 +00007641 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007642 /// Set of (canonical) types that we've already handled.
7643 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7644
Richard Smithe54c3072013-05-05 15:51:06 +00007645 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007646 for (BuiltinCandidateTypeSet::iterator
7647 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7648 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7649 MemPtr != MemPtrEnd;
7650 ++MemPtr) {
7651 // Don't add the same builtin candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007652 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007653 continue;
7654
7655 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smithe54c3072013-05-05 15:51:06 +00007656 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007657 }
Richard Smith5e9746f2016-10-21 22:00:42 +00007658
7659 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7660 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7661 if (AddedTypes.insert(NullPtrTy).second) {
7662 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
7663 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
7664 CandidateSet);
7665 }
7666 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007667 }
7668 }
7669
7670 // C++ [over.built]p15:
7671 //
Richard Smith5e9746f2016-10-21 22:00:42 +00007672 // For every T, where T is an enumeration type or a pointer type,
7673 // there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007674 //
7675 // bool operator<(T, T);
7676 // bool operator>(T, T);
7677 // bool operator<=(T, T);
7678 // bool operator>=(T, T);
7679 // bool operator==(T, T);
7680 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007681 void addRelationalPointerOrEnumeralOverloads() {
Eli Friedman14f082b2012-09-18 21:52:24 +00007682 // C++ [over.match.oper]p3:
7683 // [...]the built-in candidates include all of the candidate operator
7684 // functions defined in 13.6 that, compared to the given operator, [...]
7685 // do not have the same parameter-type-list as any non-template non-member
7686 // candidate.
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007687 //
Eli Friedman14f082b2012-09-18 21:52:24 +00007688 // Note that in practice, this only affects enumeration types because there
7689 // aren't any built-in candidates of record type, and a user-defined operator
7690 // must have an operand of record or enumeration type. Also, the only other
7691 // overloaded operator with enumeration arguments, operator=,
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007692 // cannot be overloaded for enumeration types, so this is the only place
7693 // where we must suppress candidates like this.
7694 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7695 UserDefinedBinaryOperators;
7696
Richard Smithe54c3072013-05-05 15:51:06 +00007697 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007698 if (CandidateTypes[ArgIdx].enumeration_begin() !=
7699 CandidateTypes[ArgIdx].enumeration_end()) {
7700 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7701 CEnd = CandidateSet.end();
7702 C != CEnd; ++C) {
7703 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7704 continue;
7705
Eli Friedman14f082b2012-09-18 21:52:24 +00007706 if (C->Function->isFunctionTemplateSpecialization())
7707 continue;
7708
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007709 QualType FirstParamType =
7710 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7711 QualType SecondParamType =
7712 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7713
7714 // Skip if either parameter isn't of enumeral type.
7715 if (!FirstParamType->isEnumeralType() ||
7716 !SecondParamType->isEnumeralType())
7717 continue;
7718
7719 // Add this operator to the set of known user-defined operators.
7720 UserDefinedBinaryOperators.insert(
7721 std::make_pair(S.Context.getCanonicalType(FirstParamType),
7722 S.Context.getCanonicalType(SecondParamType)));
7723 }
7724 }
7725 }
7726
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007727 /// Set of (canonical) types that we've already handled.
7728 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7729
Richard Smithe54c3072013-05-05 15:51:06 +00007730 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007731 for (BuiltinCandidateTypeSet::iterator
7732 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7733 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7734 Ptr != PtrEnd; ++Ptr) {
7735 // Don't add the same builtin candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007736 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007737 continue;
7738
7739 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smithe54c3072013-05-05 15:51:06 +00007740 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007741 }
7742 for (BuiltinCandidateTypeSet::iterator
7743 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7744 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7745 Enum != EnumEnd; ++Enum) {
7746 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
7747
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007748 // Don't add the same builtin candidate twice, or if a user defined
7749 // candidate exists.
David Blaikie82e95a32014-11-19 07:49:47 +00007750 if (!AddedTypes.insert(CanonType).second ||
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007751 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
7752 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007753 continue;
7754
7755 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smithe54c3072013-05-05 15:51:06 +00007756 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007757 }
7758 }
7759 }
7760
7761 // C++ [over.built]p13:
7762 //
7763 // For every cv-qualified or cv-unqualified object type T
7764 // there exist candidate operator functions of the form
7765 //
7766 // T* operator+(T*, ptrdiff_t);
7767 // T& operator[](T*, ptrdiff_t); [BELOW]
7768 // T* operator-(T*, ptrdiff_t);
7769 // T* operator+(ptrdiff_t, T*);
7770 // T& operator[](ptrdiff_t, T*); [BELOW]
7771 //
7772 // C++ [over.built]p14:
7773 //
7774 // For every T, where T is a pointer to object type, there
7775 // exist candidate operator functions of the form
7776 //
7777 // ptrdiff_t operator-(T, T);
7778 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
7779 /// Set of (canonical) types that we've already handled.
7780 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7781
7782 for (int Arg = 0; Arg < 2; ++Arg) {
Eric Christopher9207a522015-08-21 16:24:01 +00007783 QualType AsymmetricParamTypes[2] = {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007784 S.Context.getPointerDiffType(),
7785 S.Context.getPointerDiffType(),
7786 };
7787 for (BuiltinCandidateTypeSet::iterator
7788 Ptr = CandidateTypes[Arg].pointer_begin(),
7789 PtrEnd = CandidateTypes[Arg].pointer_end();
7790 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00007791 QualType PointeeTy = (*Ptr)->getPointeeType();
7792 if (!PointeeTy->isObjectType())
7793 continue;
7794
Eric Christopher9207a522015-08-21 16:24:01 +00007795 AsymmetricParamTypes[Arg] = *Ptr;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007796 if (Arg == 0 || Op == OO_Plus) {
7797 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
7798 // T* operator+(ptrdiff_t, T*);
Eric Christopher9207a522015-08-21 16:24:01 +00007799 S.AddBuiltinCandidate(*Ptr, AsymmetricParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007800 }
7801 if (Op == OO_Minus) {
7802 // ptrdiff_t operator-(T, T);
David Blaikie82e95a32014-11-19 07:49:47 +00007803 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007804 continue;
7805
7806 QualType ParamTypes[2] = { *Ptr, *Ptr };
7807 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
Richard Smithe54c3072013-05-05 15:51:06 +00007808 Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007809 }
7810 }
7811 }
7812 }
7813
7814 // C++ [over.built]p12:
7815 //
7816 // For every pair of promoted arithmetic types L and R, there
7817 // exist candidate operator functions of the form
7818 //
7819 // LR operator*(L, R);
7820 // LR operator/(L, R);
7821 // LR operator+(L, R);
7822 // LR operator-(L, R);
7823 // bool operator<(L, R);
7824 // bool operator>(L, R);
7825 // bool operator<=(L, R);
7826 // bool operator>=(L, R);
7827 // bool operator==(L, R);
7828 // bool operator!=(L, R);
7829 //
7830 // where LR is the result of the usual arithmetic conversions
7831 // between types L and R.
7832 //
7833 // C++ [over.built]p24:
7834 //
7835 // For every pair of promoted arithmetic types L and R, there exist
7836 // candidate operator functions of the form
7837 //
7838 // LR operator?(bool, L, R);
7839 //
7840 // where LR is the result of the usual arithmetic conversions
7841 // between types L and R.
7842 // Our candidates ignore the first parameter.
7843 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007844 if (!HasArithmeticOrEnumeralCandidateType)
7845 return;
7846
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007847 for (unsigned Left = FirstPromotedArithmeticType;
7848 Left < LastPromotedArithmeticType; ++Left) {
7849 for (unsigned Right = FirstPromotedArithmeticType;
7850 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007851 QualType LandR[2] = { getArithmeticType(Left),
7852 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007853 QualType Result =
7854 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007855 : getUsualArithmeticConversions(Left, Right);
Richard Smithe54c3072013-05-05 15:51:06 +00007856 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007857 }
7858 }
7859
7860 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7861 // conditional operator for vector types.
7862 for (BuiltinCandidateTypeSet::iterator
7863 Vec1 = CandidateTypes[0].vector_begin(),
7864 Vec1End = CandidateTypes[0].vector_end();
7865 Vec1 != Vec1End; ++Vec1) {
7866 for (BuiltinCandidateTypeSet::iterator
7867 Vec2 = CandidateTypes[1].vector_begin(),
7868 Vec2End = CandidateTypes[1].vector_end();
7869 Vec2 != Vec2End; ++Vec2) {
7870 QualType LandR[2] = { *Vec1, *Vec2 };
7871 QualType Result = S.Context.BoolTy;
7872 if (!isComparison) {
7873 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7874 Result = *Vec1;
7875 else
7876 Result = *Vec2;
7877 }
7878
Richard Smithe54c3072013-05-05 15:51:06 +00007879 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007880 }
7881 }
7882 }
7883
7884 // C++ [over.built]p17:
7885 //
7886 // For every pair of promoted integral types L and R, there
7887 // exist candidate operator functions of the form
7888 //
7889 // LR operator%(L, R);
7890 // LR operator&(L, R);
7891 // LR operator^(L, R);
7892 // LR operator|(L, R);
7893 // L operator<<(L, R);
7894 // L operator>>(L, R);
7895 //
7896 // where LR is the result of the usual arithmetic conversions
7897 // between types L and R.
7898 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007899 if (!HasArithmeticOrEnumeralCandidateType)
7900 return;
7901
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007902 for (unsigned Left = FirstPromotedIntegralType;
7903 Left < LastPromotedIntegralType; ++Left) {
7904 for (unsigned Right = FirstPromotedIntegralType;
7905 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007906 QualType LandR[2] = { getArithmeticType(Left),
7907 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007908 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7909 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007910 : getUsualArithmeticConversions(Left, Right);
Richard Smithe54c3072013-05-05 15:51:06 +00007911 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007912 }
7913 }
7914 }
7915
7916 // C++ [over.built]p20:
7917 //
7918 // For every pair (T, VQ), where T is an enumeration or
7919 // pointer to member type and VQ is either volatile or
7920 // empty, there exist candidate operator functions of the form
7921 //
7922 // VQ T& operator=(VQ T&, T);
7923 void addAssignmentMemberPointerOrEnumeralOverloads() {
7924 /// Set of (canonical) types that we've already handled.
7925 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7926
7927 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7928 for (BuiltinCandidateTypeSet::iterator
7929 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7930 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7931 Enum != EnumEnd; ++Enum) {
David Blaikie82e95a32014-11-19 07:49:47 +00007932 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007933 continue;
7934
Richard Smithe54c3072013-05-05 15:51:06 +00007935 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007936 }
7937
7938 for (BuiltinCandidateTypeSet::iterator
7939 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7940 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7941 MemPtr != MemPtrEnd; ++MemPtr) {
David Blaikie82e95a32014-11-19 07:49:47 +00007942 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007943 continue;
7944
Richard Smithe54c3072013-05-05 15:51:06 +00007945 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007946 }
7947 }
7948 }
7949
7950 // C++ [over.built]p19:
7951 //
7952 // For every pair (T, VQ), where T is any type and VQ is either
7953 // volatile or empty, there exist candidate operator functions
7954 // of the form
7955 //
7956 // T*VQ& operator=(T*VQ&, T*);
7957 //
7958 // C++ [over.built]p21:
7959 //
7960 // For every pair (T, VQ), where T is a cv-qualified or
7961 // cv-unqualified object type and VQ is either volatile or
7962 // empty, there exist candidate operator functions of the form
7963 //
7964 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
7965 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
7966 void addAssignmentPointerOverloads(bool isEqualOp) {
7967 /// Set of (canonical) types that we've already handled.
7968 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7969
7970 for (BuiltinCandidateTypeSet::iterator
7971 Ptr = CandidateTypes[0].pointer_begin(),
7972 PtrEnd = CandidateTypes[0].pointer_end();
7973 Ptr != PtrEnd; ++Ptr) {
7974 // If this is operator=, keep track of the builtin candidates we added.
7975 if (isEqualOp)
7976 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00007977 else if (!(*Ptr)->getPointeeType()->isObjectType())
7978 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007979
7980 // non-volatile version
7981 QualType ParamTypes[2] = {
7982 S.Context.getLValueReferenceType(*Ptr),
7983 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7984 };
Richard Smithe54c3072013-05-05 15:51:06 +00007985 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007986 /*IsAssigmentOperator=*/ isEqualOp);
7987
Douglas Gregor5bee2582012-06-04 00:15:09 +00007988 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7989 VisibleTypeConversionsQuals.hasVolatile();
7990 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007991 // volatile version
7992 ParamTypes[0] =
7993 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007994 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007995 /*IsAssigmentOperator=*/isEqualOp);
7996 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007997
7998 if (!(*Ptr).isRestrictQualified() &&
7999 VisibleTypeConversionsQuals.hasRestrict()) {
8000 // restrict version
8001 ParamTypes[0]
8002 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00008003 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00008004 /*IsAssigmentOperator=*/isEqualOp);
8005
8006 if (NeedVolatile) {
8007 // volatile restrict version
8008 ParamTypes[0]
8009 = S.Context.getLValueReferenceType(
8010 S.Context.getCVRQualifiedType(*Ptr,
8011 (Qualifiers::Volatile |
8012 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00008013 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00008014 /*IsAssigmentOperator=*/isEqualOp);
8015 }
8016 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008017 }
8018
8019 if (isEqualOp) {
8020 for (BuiltinCandidateTypeSet::iterator
8021 Ptr = CandidateTypes[1].pointer_begin(),
8022 PtrEnd = CandidateTypes[1].pointer_end();
8023 Ptr != PtrEnd; ++Ptr) {
8024 // Make sure we don't add the same candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00008025 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008026 continue;
8027
Chandler Carruth8e543b32010-12-12 08:17:55 +00008028 QualType ParamTypes[2] = {
8029 S.Context.getLValueReferenceType(*Ptr),
8030 *Ptr,
8031 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008032
8033 // non-volatile version
Richard Smithe54c3072013-05-05 15:51:06 +00008034 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008035 /*IsAssigmentOperator=*/true);
8036
Douglas Gregor5bee2582012-06-04 00:15:09 +00008037 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8038 VisibleTypeConversionsQuals.hasVolatile();
8039 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008040 // volatile version
8041 ParamTypes[0] =
8042 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00008043 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8044 /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008045 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00008046
8047 if (!(*Ptr).isRestrictQualified() &&
8048 VisibleTypeConversionsQuals.hasRestrict()) {
8049 // restrict version
8050 ParamTypes[0]
8051 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00008052 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8053 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00008054
8055 if (NeedVolatile) {
8056 // volatile restrict version
8057 ParamTypes[0]
8058 = S.Context.getLValueReferenceType(
8059 S.Context.getCVRQualifiedType(*Ptr,
8060 (Qualifiers::Volatile |
8061 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00008062 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8063 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00008064 }
8065 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008066 }
8067 }
8068 }
8069
8070 // C++ [over.built]p18:
8071 //
8072 // For every triple (L, VQ, R), where L is an arithmetic type,
8073 // VQ is either volatile or empty, and R is a promoted
8074 // arithmetic type, there exist candidate operator functions of
8075 // the form
8076 //
8077 // VQ L& operator=(VQ L&, R);
8078 // VQ L& operator*=(VQ L&, R);
8079 // VQ L& operator/=(VQ L&, R);
8080 // VQ L& operator+=(VQ L&, R);
8081 // VQ L& operator-=(VQ L&, R);
8082 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00008083 if (!HasArithmeticOrEnumeralCandidateType)
8084 return;
8085
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008086 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
8087 for (unsigned Right = FirstPromotedArithmeticType;
8088 Right < LastPromotedArithmeticType; ++Right) {
8089 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00008090 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008091
8092 // Add this built-in operator as a candidate (VQ is empty).
8093 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00008094 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smithe54c3072013-05-05 15:51:06 +00008095 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008096 /*IsAssigmentOperator=*/isEqualOp);
8097
8098 // Add this built-in operator as a candidate (VQ is 'volatile').
8099 if (VisibleTypeConversionsQuals.hasVolatile()) {
8100 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00008101 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008102 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00008103 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008104 /*IsAssigmentOperator=*/isEqualOp);
8105 }
8106 }
8107 }
8108
8109 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8110 for (BuiltinCandidateTypeSet::iterator
8111 Vec1 = CandidateTypes[0].vector_begin(),
8112 Vec1End = CandidateTypes[0].vector_end();
8113 Vec1 != Vec1End; ++Vec1) {
8114 for (BuiltinCandidateTypeSet::iterator
8115 Vec2 = CandidateTypes[1].vector_begin(),
8116 Vec2End = CandidateTypes[1].vector_end();
8117 Vec2 != Vec2End; ++Vec2) {
8118 QualType ParamTypes[2];
8119 ParamTypes[1] = *Vec2;
8120 // Add this built-in operator as a candidate (VQ is empty).
8121 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
Richard Smithe54c3072013-05-05 15:51:06 +00008122 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008123 /*IsAssigmentOperator=*/isEqualOp);
8124
8125 // Add this built-in operator as a candidate (VQ is 'volatile').
8126 if (VisibleTypeConversionsQuals.hasVolatile()) {
8127 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
8128 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00008129 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008130 /*IsAssigmentOperator=*/isEqualOp);
8131 }
8132 }
8133 }
8134 }
8135
8136 // C++ [over.built]p22:
8137 //
8138 // For every triple (L, VQ, R), where L is an integral type, VQ
8139 // is either volatile or empty, and R is a promoted integral
8140 // type, there exist candidate operator functions of the form
8141 //
8142 // VQ L& operator%=(VQ L&, R);
8143 // VQ L& operator<<=(VQ L&, R);
8144 // VQ L& operator>>=(VQ L&, R);
8145 // VQ L& operator&=(VQ L&, R);
8146 // VQ L& operator^=(VQ L&, R);
8147 // VQ L& operator|=(VQ L&, R);
8148 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00008149 if (!HasArithmeticOrEnumeralCandidateType)
8150 return;
8151
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008152 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8153 for (unsigned Right = FirstPromotedIntegralType;
8154 Right < LastPromotedIntegralType; ++Right) {
8155 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00008156 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008157
8158 // Add this built-in operator as a candidate (VQ is empty).
8159 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00008160 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smithe54c3072013-05-05 15:51:06 +00008161 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008162 if (VisibleTypeConversionsQuals.hasVolatile()) {
8163 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00008164 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008165 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8166 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00008167 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008168 }
8169 }
8170 }
8171 }
8172
8173 // C++ [over.operator]p23:
8174 //
8175 // There also exist candidate operator functions of the form
8176 //
8177 // bool operator!(bool);
8178 // bool operator&&(bool, bool);
8179 // bool operator||(bool, bool);
8180 void addExclaimOverload() {
8181 QualType ParamTy = S.Context.BoolTy;
Richard Smithe54c3072013-05-05 15:51:06 +00008182 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008183 /*IsAssignmentOperator=*/false,
8184 /*NumContextualBoolArguments=*/1);
8185 }
8186 void addAmpAmpOrPipePipeOverload() {
8187 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
Richard Smithe54c3072013-05-05 15:51:06 +00008188 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008189 /*IsAssignmentOperator=*/false,
8190 /*NumContextualBoolArguments=*/2);
8191 }
8192
8193 // C++ [over.built]p13:
8194 //
8195 // For every cv-qualified or cv-unqualified object type T there
8196 // exist candidate operator functions of the form
8197 //
8198 // T* operator+(T*, ptrdiff_t); [ABOVE]
8199 // T& operator[](T*, ptrdiff_t);
8200 // T* operator-(T*, ptrdiff_t); [ABOVE]
8201 // T* operator+(ptrdiff_t, T*); [ABOVE]
8202 // T& operator[](ptrdiff_t, T*);
8203 void addSubscriptOverloads() {
8204 for (BuiltinCandidateTypeSet::iterator
8205 Ptr = CandidateTypes[0].pointer_begin(),
8206 PtrEnd = CandidateTypes[0].pointer_end();
8207 Ptr != PtrEnd; ++Ptr) {
8208 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8209 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00008210 if (!PointeeType->isObjectType())
8211 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008212
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008213 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8214
8215 // T& operator[](T*, ptrdiff_t)
Richard Smithe54c3072013-05-05 15:51:06 +00008216 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008217 }
8218
8219 for (BuiltinCandidateTypeSet::iterator
8220 Ptr = CandidateTypes[1].pointer_begin(),
8221 PtrEnd = CandidateTypes[1].pointer_end();
8222 Ptr != PtrEnd; ++Ptr) {
8223 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8224 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00008225 if (!PointeeType->isObjectType())
8226 continue;
8227
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008228 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8229
8230 // T& operator[](ptrdiff_t, T*)
Richard Smithe54c3072013-05-05 15:51:06 +00008231 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008232 }
8233 }
8234
8235 // C++ [over.built]p11:
8236 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8237 // C1 is the same type as C2 or is a derived class of C2, T is an object
8238 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8239 // there exist candidate operator functions of the form
8240 //
8241 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8242 //
8243 // where CV12 is the union of CV1 and CV2.
8244 void addArrowStarOverloads() {
8245 for (BuiltinCandidateTypeSet::iterator
8246 Ptr = CandidateTypes[0].pointer_begin(),
8247 PtrEnd = CandidateTypes[0].pointer_end();
8248 Ptr != PtrEnd; ++Ptr) {
8249 QualType C1Ty = (*Ptr);
8250 QualType C1;
8251 QualifierCollector Q1;
8252 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8253 if (!isa<RecordType>(C1))
8254 continue;
8255 // heuristic to reduce number of builtin candidates in the set.
8256 // Add volatile/restrict version only if there are conversions to a
8257 // volatile/restrict type.
8258 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8259 continue;
8260 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8261 continue;
8262 for (BuiltinCandidateTypeSet::iterator
8263 MemPtr = CandidateTypes[1].member_pointer_begin(),
8264 MemPtrEnd = CandidateTypes[1].member_pointer_end();
8265 MemPtr != MemPtrEnd; ++MemPtr) {
8266 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8267 QualType C2 = QualType(mptr->getClass(), 0);
8268 C2 = C2.getUnqualifiedType();
Richard Smith0f59cb32015-12-18 21:45:41 +00008269 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008270 break;
8271 QualType ParamTypes[2] = { *Ptr, *MemPtr };
8272 // build CV12 T&
8273 QualType T = mptr->getPointeeType();
8274 if (!VisibleTypeConversionsQuals.hasVolatile() &&
8275 T.isVolatileQualified())
8276 continue;
8277 if (!VisibleTypeConversionsQuals.hasRestrict() &&
8278 T.isRestrictQualified())
8279 continue;
8280 T = Q1.apply(S.Context, T);
8281 QualType ResultTy = S.Context.getLValueReferenceType(T);
Richard Smithe54c3072013-05-05 15:51:06 +00008282 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008283 }
8284 }
8285 }
8286
8287 // Note that we don't consider the first argument, since it has been
8288 // contextually converted to bool long ago. The candidates below are
8289 // therefore added as binary.
8290 //
8291 // C++ [over.built]p25:
8292 // For every type T, where T is a pointer, pointer-to-member, or scoped
8293 // enumeration type, there exist candidate operator functions of the form
8294 //
8295 // T operator?(bool, T, T);
8296 //
8297 void addConditionalOperatorOverloads() {
8298 /// Set of (canonical) types that we've already handled.
8299 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8300
8301 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8302 for (BuiltinCandidateTypeSet::iterator
8303 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8304 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8305 Ptr != PtrEnd; ++Ptr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008306 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008307 continue;
8308
8309 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smithe54c3072013-05-05 15:51:06 +00008310 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008311 }
8312
8313 for (BuiltinCandidateTypeSet::iterator
8314 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8315 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8316 MemPtr != MemPtrEnd; ++MemPtr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008317 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008318 continue;
8319
8320 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smithe54c3072013-05-05 15:51:06 +00008321 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008322 }
8323
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008324 if (S.getLangOpts().CPlusPlus11) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008325 for (BuiltinCandidateTypeSet::iterator
8326 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8327 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8328 Enum != EnumEnd; ++Enum) {
8329 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8330 continue;
8331
David Blaikie82e95a32014-11-19 07:49:47 +00008332 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008333 continue;
8334
8335 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smithe54c3072013-05-05 15:51:06 +00008336 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008337 }
8338 }
8339 }
8340 }
8341};
8342
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008343} // end anonymous namespace
8344
8345/// AddBuiltinOperatorCandidates - Add the appropriate built-in
8346/// operator overloads to the candidate set (C++ [over.built]), based
8347/// on the operator @p Op and the arguments given. For example, if the
8348/// operator is a binary '+', this routine might add "int
8349/// operator+(int, int)" to cover integer addition.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00008350void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8351 SourceLocation OpLoc,
8352 ArrayRef<Expr *> Args,
8353 OverloadCandidateSet &CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00008354 // Find all of the types that the arguments can convert to, but only
8355 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00008356 // that make use of these types. Also record whether we encounter non-record
8357 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00008358 Qualifiers VisibleTypeConversionsQuals;
8359 VisibleTypeConversionsQuals.addConst();
Richard Smithe54c3072013-05-05 15:51:06 +00008360 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00008361 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00008362
8363 bool HasNonRecordCandidateType = false;
8364 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008365 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Richard Smithe54c3072013-05-05 15:51:06 +00008366 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Benjamin Kramer57dddd482015-02-17 21:55:18 +00008367 CandidateTypes.emplace_back(*this);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00008368 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8369 OpLoc,
8370 true,
8371 (Op == OO_Exclaim ||
8372 Op == OO_AmpAmp ||
8373 Op == OO_PipePipe),
8374 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00008375 HasNonRecordCandidateType = HasNonRecordCandidateType ||
8376 CandidateTypes[ArgIdx].hasNonRecordTypes();
8377 HasArithmeticOrEnumeralCandidateType =
8378 HasArithmeticOrEnumeralCandidateType ||
8379 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00008380 }
Douglas Gregora11693b2008-11-12 17:17:38 +00008381
Chandler Carruth00a38332010-12-13 01:44:01 +00008382 // Exit early when no non-record types have been added to the candidate set
8383 // for any of the arguments to the operator.
Douglas Gregor877d4eb2011-10-10 14:05:31 +00008384 //
8385 // We can't exit early for !, ||, or &&, since there we have always have
8386 // 'bool' overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00008387 if (!HasNonRecordCandidateType &&
Douglas Gregor877d4eb2011-10-10 14:05:31 +00008388 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth00a38332010-12-13 01:44:01 +00008389 return;
8390
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008391 // Setup an object to manage the common state for building overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00008392 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008393 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00008394 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008395 CandidateTypes, CandidateSet);
8396
8397 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00008398 switch (Op) {
8399 case OO_None:
8400 case NUM_OVERLOADED_OPERATORS:
David Blaikie83d382b2011-09-23 05:06:16 +00008401 llvm_unreachable("Expected an overloaded operator");
Douglas Gregora11693b2008-11-12 17:17:38 +00008402
Chandler Carruth5184de02010-12-12 08:51:33 +00008403 case OO_New:
8404 case OO_Delete:
8405 case OO_Array_New:
8406 case OO_Array_Delete:
8407 case OO_Call:
David Blaikie83d382b2011-09-23 05:06:16 +00008408 llvm_unreachable(
8409 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruth5184de02010-12-12 08:51:33 +00008410
8411 case OO_Comma:
8412 case OO_Arrow:
Richard Smith9f690bd2015-10-27 06:02:45 +00008413 case OO_Coawait:
Chandler Carruth5184de02010-12-12 08:51:33 +00008414 // C++ [over.match.oper]p3:
Richard Smith9f690bd2015-10-27 06:02:45 +00008415 // -- For the operator ',', the unary operator '&', the
8416 // operator '->', or the operator 'co_await', the
8417 // built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00008418 break;
8419
8420 case OO_Plus: // '+' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008421 if (Args.size() == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008422 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00008423 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00008424
8425 case OO_Minus: // '-' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008426 if (Args.size() == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008427 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008428 } else {
8429 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8430 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8431 }
Douglas Gregord08452f2008-11-19 15:42:04 +00008432 break;
8433
Chandler Carruth5184de02010-12-12 08:51:33 +00008434 case OO_Star: // '*' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008435 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008436 OpBuilder.addUnaryStarPointerOverloads();
8437 else
8438 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8439 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008440
Chandler Carruth5184de02010-12-12 08:51:33 +00008441 case OO_Slash:
8442 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008443 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008444
8445 case OO_PlusPlus:
8446 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008447 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8448 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00008449 break;
8450
Douglas Gregor84605ae2009-08-24 13:43:27 +00008451 case OO_EqualEqual:
8452 case OO_ExclaimEqual:
Richard Smith5e9746f2016-10-21 22:00:42 +00008453 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00008454 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008455
Douglas Gregora11693b2008-11-12 17:17:38 +00008456 case OO_Less:
8457 case OO_Greater:
8458 case OO_LessEqual:
8459 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00008460 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00008461 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
8462 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008463
Douglas Gregora11693b2008-11-12 17:17:38 +00008464 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00008465 case OO_Caret:
8466 case OO_Pipe:
8467 case OO_LessLess:
8468 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008469 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00008470 break;
8471
Chandler Carruth5184de02010-12-12 08:51:33 +00008472 case OO_Amp: // '&' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008473 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008474 // C++ [over.match.oper]p3:
8475 // -- For the operator ',', the unary operator '&', or the
8476 // operator '->', the built-in candidates set is empty.
8477 break;
8478
8479 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8480 break;
8481
8482 case OO_Tilde:
8483 OpBuilder.addUnaryTildePromotedIntegralOverloads();
8484 break;
8485
Douglas Gregora11693b2008-11-12 17:17:38 +00008486 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008487 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00008488 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00008489
8490 case OO_PlusEqual:
8491 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008492 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008493 // Fall through.
8494
8495 case OO_StarEqual:
8496 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008497 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008498 break;
8499
8500 case OO_PercentEqual:
8501 case OO_LessLessEqual:
8502 case OO_GreaterGreaterEqual:
8503 case OO_AmpEqual:
8504 case OO_CaretEqual:
8505 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008506 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008507 break;
8508
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008509 case OO_Exclaim:
8510 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00008511 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008512
Douglas Gregora11693b2008-11-12 17:17:38 +00008513 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008514 case OO_PipePipe:
8515 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00008516 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008517
8518 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008519 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008520 break;
8521
8522 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008523 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008524 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00008525
8526 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008527 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008528 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8529 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008530 }
8531}
8532
Douglas Gregore254f902009-02-04 00:32:51 +00008533/// \brief Add function candidates found via argument-dependent lookup
8534/// to the set of overloading candidates.
8535///
8536/// This routine performs argument-dependent name lookup based on the
8537/// given function name (which may also be an operator name) and adds
8538/// all of the overload candidates found by ADL to the overload
8539/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00008540void
Douglas Gregore254f902009-02-04 00:32:51 +00008541Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smith100b24a2014-04-17 01:52:14 +00008542 SourceLocation Loc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008543 ArrayRef<Expr *> Args,
Douglas Gregor739b107a2011-03-03 02:41:12 +00008544 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008545 OverloadCandidateSet& CandidateSet,
Richard Smithb6626742012-10-18 17:56:02 +00008546 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00008547 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00008548
John McCall91f61fc2010-01-26 06:04:06 +00008549 // FIXME: This approach for uniquing ADL results (and removing
8550 // redundant candidates from the set) relies on pointer-equality,
8551 // which means we need to key off the canonical decl. However,
8552 // always going back to the canonical decl might not get us the
8553 // right set of default arguments. What default arguments are
8554 // we supposed to consider on ADL candidates, anyway?
8555
Douglas Gregorcabea402009-09-22 15:41:20 +00008556 // FIXME: Pass in the explicit template arguments?
Richard Smith100b24a2014-04-17 01:52:14 +00008557 ArgumentDependentLookup(Name, Loc, Args, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00008558
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008559 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008560 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8561 CandEnd = CandidateSet.end();
8562 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00008563 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00008564 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00008565 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00008566 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00008567 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008568
8569 // For each of the ADL candidates we found, add it to the overload
8570 // set.
John McCall8fe68082010-01-26 07:16:45 +00008571 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00008572 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00008573 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00008574 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00008575 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008576
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008577 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8578 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00008579 } else
John McCall4c4c1df2010-01-26 03:27:55 +00008580 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00008581 FoundDecl, ExplicitTemplateArgs,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00008582 Args, CandidateSet, PartialOverloading);
Douglas Gregor15448f82009-06-27 21:05:07 +00008583 }
Douglas Gregore254f902009-02-04 00:32:51 +00008584}
8585
George Burgess IV3dc166912016-05-10 01:59:34 +00008586namespace {
8587enum class Comparison { Equal, Better, Worse };
8588}
8589
8590/// Compares the enable_if attributes of two FunctionDecls, for the purposes of
8591/// overload resolution.
8592///
8593/// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
8594/// Cand1's first N enable_if attributes have precisely the same conditions as
8595/// Cand2's first N enable_if attributes (where N = the number of enable_if
8596/// attributes on Cand2), and Cand1 has more than N enable_if attributes.
8597///
8598/// Note that you can have a pair of candidates such that Cand1's enable_if
8599/// attributes are worse than Cand2's, and Cand2's enable_if attributes are
8600/// worse than Cand1's.
8601static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
8602 const FunctionDecl *Cand2) {
8603 // Common case: One (or both) decls don't have enable_if attrs.
8604 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
8605 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
8606 if (!Cand1Attr || !Cand2Attr) {
8607 if (Cand1Attr == Cand2Attr)
8608 return Comparison::Equal;
8609 return Cand1Attr ? Comparison::Better : Comparison::Worse;
8610 }
George Burgess IV2a6150d2015-10-16 01:17:38 +00008611
8612 // FIXME: The next several lines are just
8613 // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8614 // instead of reverse order which is how they're stored in the AST.
8615 auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1);
8616 auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2);
8617
George Burgess IV3dc166912016-05-10 01:59:34 +00008618 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
8619 // has fewer enable_if attributes than Cand2.
8620 if (Cand1Attrs.size() < Cand2Attrs.size())
8621 return Comparison::Worse;
George Burgess IV2a6150d2015-10-16 01:17:38 +00008622
8623 auto Cand1I = Cand1Attrs.begin();
8624 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
8625 for (auto &Cand2A : Cand2Attrs) {
8626 Cand1ID.clear();
8627 Cand2ID.clear();
8628
8629 auto &Cand1A = *Cand1I++;
8630 Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true);
8631 Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true);
8632 if (Cand1ID != Cand2ID)
George Burgess IV3dc166912016-05-10 01:59:34 +00008633 return Comparison::Worse;
George Burgess IV2a6150d2015-10-16 01:17:38 +00008634 }
8635
George Burgess IV3dc166912016-05-10 01:59:34 +00008636 return Cand1I == Cand1Attrs.end() ? Comparison::Equal : Comparison::Better;
George Burgess IV2a6150d2015-10-16 01:17:38 +00008637}
8638
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008639/// isBetterOverloadCandidate - Determines whether the first overload
8640/// candidate is a better candidate than the second (C++ 13.3.3p1).
Richard Smith17c00b42014-11-12 01:24:00 +00008641bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1,
8642 const OverloadCandidate &Cand2,
8643 SourceLocation Loc,
8644 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008645 // Define viable functions to be better candidates than non-viable
8646 // functions.
8647 if (!Cand2.Viable)
8648 return Cand1.Viable;
8649 else if (!Cand1.Viable)
8650 return false;
8651
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008652 // C++ [over.match.best]p1:
8653 //
8654 // -- if F is a static member function, ICS1(F) is defined such
8655 // that ICS1(F) is neither better nor worse than ICS1(G) for
8656 // any function G, and, symmetrically, ICS1(G) is neither
8657 // better nor worse than ICS1(F).
8658 unsigned StartArg = 0;
8659 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8660 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008661
George Burgess IVfbad5b22016-09-07 20:03:19 +00008662 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
8663 // We don't allow incompatible pointer conversions in C++.
8664 if (!S.getLangOpts().CPlusPlus)
8665 return ICS.isStandard() &&
8666 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
8667
8668 // The only ill-formed conversion we allow in C++ is the string literal to
8669 // char* conversion, which is only considered ill-formed after C++11.
8670 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
8671 hasDeprecatedStringLiteralToCharPtrConversion(ICS);
8672 };
8673
8674 // Define functions that don't require ill-formed conversions for a given
8675 // argument to be better candidates than functions that do.
8676 unsigned NumArgs = Cand1.NumConversions;
8677 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
8678 bool HasBetterConversion = false;
8679 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
8680 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
8681 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
8682 if (Cand1Bad != Cand2Bad) {
8683 if (Cand1Bad)
8684 return false;
8685 HasBetterConversion = true;
8686 }
8687 }
8688
8689 if (HasBetterConversion)
8690 return true;
8691
Douglas Gregord3cb3562009-07-07 23:38:56 +00008692 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00008693 // A viable function F1 is defined to be a better function than another
8694 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00008695 // conversion sequence than ICSi(F2), and then...
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008696 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Richard Smith0f59cb32015-12-18 21:45:41 +00008697 switch (CompareImplicitConversionSequences(S, Loc,
John McCall5c32be02010-08-24 20:38:10 +00008698 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008699 Cand2.Conversions[ArgIdx])) {
8700 case ImplicitConversionSequence::Better:
8701 // Cand1 has a better conversion sequence.
8702 HasBetterConversion = true;
8703 break;
8704
8705 case ImplicitConversionSequence::Worse:
8706 // Cand1 can't be better than Cand2.
8707 return false;
8708
8709 case ImplicitConversionSequence::Indistinguishable:
8710 // Do nothing.
8711 break;
8712 }
8713 }
8714
Mike Stump11289f42009-09-09 15:08:12 +00008715 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00008716 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008717 if (HasBetterConversion)
8718 return true;
8719
Douglas Gregora1f013e2008-11-07 22:36:19 +00008720 // -- the context is an initialization by user-defined conversion
8721 // (see 8.5, 13.3.1.5) and the standard conversion sequence
8722 // from the return type of F1 to the destination type (i.e.,
8723 // the type of the entity being initialized) is a better
8724 // conversion sequence than the standard conversion sequence
8725 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00008726 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00008727 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00008728 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregor2837aa22012-02-22 17:32:19 +00008729 // First check whether we prefer one of the conversion functions over the
8730 // other. This only distinguishes the results in non-standard, extension
8731 // cases such as the conversion from a lambda closure type to a function
8732 // pointer or block.
Richard Smithec2748a2014-05-17 04:36:39 +00008733 ImplicitConversionSequence::CompareKind Result =
8734 compareConversionFunctions(S, Cand1.Function, Cand2.Function);
8735 if (Result == ImplicitConversionSequence::Indistinguishable)
Richard Smith0f59cb32015-12-18 21:45:41 +00008736 Result = CompareStandardConversionSequences(S, Loc,
Richard Smithec2748a2014-05-17 04:36:39 +00008737 Cand1.FinalConversion,
8738 Cand2.FinalConversion);
Richard Smith6fdeaab2014-05-17 01:58:45 +00008739
Richard Smithec2748a2014-05-17 04:36:39 +00008740 if (Result != ImplicitConversionSequence::Indistinguishable)
8741 return Result == ImplicitConversionSequence::Better;
Richard Smith6fdeaab2014-05-17 01:58:45 +00008742
8743 // FIXME: Compare kind of reference binding if conversion functions
8744 // convert to a reference type used in direct reference binding, per
8745 // C++14 [over.match.best]p1 section 2 bullet 3.
8746 }
8747
8748 // -- F1 is a non-template function and F2 is a function template
8749 // specialization, or, if not that,
8750 bool Cand1IsSpecialization = Cand1.Function &&
8751 Cand1.Function->getPrimaryTemplate();
8752 bool Cand2IsSpecialization = Cand2.Function &&
8753 Cand2.Function->getPrimaryTemplate();
8754 if (Cand1IsSpecialization != Cand2IsSpecialization)
8755 return Cand2IsSpecialization;
8756
8757 // -- F1 and F2 are function template specializations, and the function
8758 // template for F1 is more specialized than the template for F2
8759 // according to the partial ordering rules described in 14.5.5.2, or,
8760 // if not that,
8761 if (Cand1IsSpecialization && Cand2IsSpecialization) {
8762 if (FunctionTemplateDecl *BetterTemplate
8763 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
8764 Cand2.Function->getPrimaryTemplate(),
8765 Loc,
8766 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
8767 : TPOC_Call,
8768 Cand1.ExplicitCallArguments,
8769 Cand2.ExplicitCallArguments))
8770 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregora1f013e2008-11-07 22:36:19 +00008771 }
8772
Richard Smith5179eb72016-06-28 19:03:57 +00008773 // FIXME: Work around a defect in the C++17 inheriting constructor wording.
8774 // A derived-class constructor beats an (inherited) base class constructor.
8775 bool Cand1IsInherited =
8776 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
8777 bool Cand2IsInherited =
8778 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
8779 if (Cand1IsInherited != Cand2IsInherited)
8780 return Cand2IsInherited;
8781 else if (Cand1IsInherited) {
8782 assert(Cand2IsInherited);
8783 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
8784 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
8785 if (Cand1Class->isDerivedFrom(Cand2Class))
8786 return true;
8787 if (Cand2Class->isDerivedFrom(Cand1Class))
8788 return false;
8789 // Inherited from sibling base classes: still ambiguous.
8790 }
8791
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008792 // Check for enable_if value-based overload resolution.
George Burgess IV3dc166912016-05-10 01:59:34 +00008793 if (Cand1.Function && Cand2.Function) {
8794 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
8795 if (Cmp != Comparison::Equal)
8796 return Cmp == Comparison::Better;
8797 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008798
Justin Lebar25c4a812016-03-29 16:24:16 +00008799 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
Artem Belevich94a55e82015-09-22 17:22:59 +00008800 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
8801 return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
8802 S.IdentifyCUDAPreference(Caller, Cand2.Function);
8803 }
8804
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008805 bool HasPS1 = Cand1.Function != nullptr &&
8806 functionHasPassObjectSizeParams(Cand1.Function);
8807 bool HasPS2 = Cand2.Function != nullptr &&
8808 functionHasPassObjectSizeParams(Cand2.Function);
8809 return HasPS1 != HasPS2 && HasPS1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008810}
8811
Richard Smith2dbe4042015-11-04 19:26:32 +00008812/// Determine whether two declarations are "equivalent" for the purposes of
Richard Smith26210db2015-11-13 03:52:13 +00008813/// name lookup and overload resolution. This applies when the same internal/no
8814/// linkage entity is defined by two modules (probably by textually including
Richard Smith2dbe4042015-11-04 19:26:32 +00008815/// the same header). In such a case, we don't consider the declarations to
8816/// declare the same entity, but we also don't want lookups with both
8817/// declarations visible to be ambiguous in some cases (this happens when using
8818/// a modularized libstdc++).
8819bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
8820 const NamedDecl *B) {
Richard Smith26210db2015-11-13 03:52:13 +00008821 auto *VA = dyn_cast_or_null<ValueDecl>(A);
8822 auto *VB = dyn_cast_or_null<ValueDecl>(B);
8823 if (!VA || !VB)
8824 return false;
8825
8826 // The declarations must be declaring the same name as an internal linkage
8827 // entity in different modules.
8828 if (!VA->getDeclContext()->getRedeclContext()->Equals(
8829 VB->getDeclContext()->getRedeclContext()) ||
8830 getOwningModule(const_cast<ValueDecl *>(VA)) ==
8831 getOwningModule(const_cast<ValueDecl *>(VB)) ||
8832 VA->isExternallyVisible() || VB->isExternallyVisible())
8833 return false;
8834
8835 // Check that the declarations appear to be equivalent.
8836 //
8837 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
8838 // For constants and functions, we should check the initializer or body is
8839 // the same. For non-constant variables, we shouldn't allow it at all.
8840 if (Context.hasSameType(VA->getType(), VB->getType()))
8841 return true;
8842
8843 // Enum constants within unnamed enumerations will have different types, but
8844 // may still be similar enough to be interchangeable for our purposes.
8845 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
8846 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
8847 // Only handle anonymous enums. If the enumerations were named and
8848 // equivalent, they would have been merged to the same type.
8849 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
8850 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
8851 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
8852 !Context.hasSameType(EnumA->getIntegerType(),
8853 EnumB->getIntegerType()))
8854 return false;
8855 // Allow this only if the value is the same for both enumerators.
8856 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
8857 }
8858 }
8859
8860 // Nothing else is sufficiently similar.
8861 return false;
Richard Smith2dbe4042015-11-04 19:26:32 +00008862}
8863
8864void Sema::diagnoseEquivalentInternalLinkageDeclarations(
8865 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
8866 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
8867
8868 Module *M = getOwningModule(const_cast<NamedDecl*>(D));
8869 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
8870 << !M << (M ? M->getFullModuleName() : "");
8871
8872 for (auto *E : Equiv) {
8873 Module *M = getOwningModule(const_cast<NamedDecl*>(E));
8874 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
8875 << !M << (M ? M->getFullModuleName() : "");
8876 }
Richard Smith896c66e2015-10-21 07:13:52 +00008877}
8878
Mike Stump11289f42009-09-09 15:08:12 +00008879/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008880/// within an overload candidate set.
8881///
James Dennettffad8b72012-06-22 08:10:18 +00008882/// \param Loc The location of the function name (or operator symbol) for
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008883/// which overload resolution occurs.
8884///
James Dennettffad8b72012-06-22 08:10:18 +00008885/// \param Best If overload resolution was successful or found a deleted
8886/// function, \p Best points to the candidate function found.
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008887///
8888/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00008889OverloadingResult
8890OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00008891 iterator &Best,
Chandler Carruth30141632011-02-25 19:41:05 +00008892 bool UserDefinedConversion) {
Artem Belevich18609102016-02-12 18:29:18 +00008893 llvm::SmallVector<OverloadCandidate *, 16> Candidates;
8894 std::transform(begin(), end(), std::back_inserter(Candidates),
8895 [](OverloadCandidate &Cand) { return &Cand; });
8896
Justin Lebar66a2ab92016-08-10 00:40:43 +00008897 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
8898 // are accepted by both clang and NVCC. However, during a particular
Artem Belevich18609102016-02-12 18:29:18 +00008899 // compilation mode only one call variant is viable. We need to
8900 // exclude non-viable overload candidates from consideration based
8901 // only on their host/device attributes. Specifically, if one
8902 // candidate call is WrongSide and the other is SameSide, we ignore
8903 // the WrongSide candidate.
Justin Lebar25c4a812016-03-29 16:24:16 +00008904 if (S.getLangOpts().CUDA) {
Artem Belevich18609102016-02-12 18:29:18 +00008905 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
8906 bool ContainsSameSideCandidate =
8907 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
8908 return Cand->Function &&
8909 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
8910 Sema::CFP_SameSide;
8911 });
8912 if (ContainsSameSideCandidate) {
8913 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
8914 return Cand->Function &&
8915 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
8916 Sema::CFP_WrongSide;
8917 };
8918 Candidates.erase(std::remove_if(Candidates.begin(), Candidates.end(),
8919 IsWrongSideCandidate),
8920 Candidates.end());
8921 }
8922 }
8923
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008924 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00008925 Best = end();
Artem Belevich18609102016-02-12 18:29:18 +00008926 for (auto *Cand : Candidates)
John McCall5c32be02010-08-24 20:38:10 +00008927 if (Cand->Viable)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008928 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00008929 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008930 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008931
8932 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00008933 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008934 return OR_No_Viable_Function;
8935
Richard Smith2dbe4042015-11-04 19:26:32 +00008936 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
Richard Smith896c66e2015-10-21 07:13:52 +00008937
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008938 // Make sure that this function is better than every other viable
8939 // function. If not, we have an ambiguity.
Artem Belevich18609102016-02-12 18:29:18 +00008940 for (auto *Cand : Candidates) {
Mike Stump11289f42009-09-09 15:08:12 +00008941 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008942 Cand != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008943 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00008944 UserDefinedConversion)) {
Richard Smith2dbe4042015-11-04 19:26:32 +00008945 if (S.isEquivalentInternalLinkageDeclaration(Best->Function,
8946 Cand->Function)) {
8947 EquivalentCands.push_back(Cand->Function);
Richard Smith896c66e2015-10-21 07:13:52 +00008948 continue;
8949 }
8950
John McCall5c32be02010-08-24 20:38:10 +00008951 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008952 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00008953 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008954 }
Mike Stump11289f42009-09-09 15:08:12 +00008955
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008956 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00008957 if (Best->Function &&
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00008958 (Best->Function->isDeleted() ||
8959 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor171c45a2009-02-18 21:56:37 +00008960 return OR_Deleted;
8961
Richard Smith2dbe4042015-11-04 19:26:32 +00008962 if (!EquivalentCands.empty())
8963 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
8964 EquivalentCands);
Richard Smith896c66e2015-10-21 07:13:52 +00008965
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008966 return OR_Success;
8967}
8968
John McCall53262c92010-01-12 02:15:36 +00008969namespace {
8970
8971enum OverloadCandidateKind {
8972 oc_function,
8973 oc_method,
8974 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00008975 oc_function_template,
8976 oc_method_template,
8977 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00008978 oc_implicit_default_constructor,
8979 oc_implicit_copy_constructor,
Alexis Hunt119c10e2011-05-25 23:16:36 +00008980 oc_implicit_move_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00008981 oc_implicit_copy_assignment,
Alexis Hunt119c10e2011-05-25 23:16:36 +00008982 oc_implicit_move_assignment,
Richard Smith5179eb72016-06-28 19:03:57 +00008983 oc_inherited_constructor,
8984 oc_inherited_constructor_template
John McCall53262c92010-01-12 02:15:36 +00008985};
8986
George Burgess IVd66d37c2016-10-28 21:42:06 +00008987static OverloadCandidateKind
8988ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
8989 std::string &Description) {
John McCalle1ac8d12010-01-13 00:25:19 +00008990 bool isTemplate = false;
8991
8992 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
8993 isTemplate = true;
8994 Description = S.getTemplateArgumentBindingsText(
8995 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
8996 }
John McCallfd0b2f82010-01-06 09:43:14 +00008997
8998 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
Richard Smith5179eb72016-06-28 19:03:57 +00008999 if (!Ctor->isImplicit()) {
9000 if (isa<ConstructorUsingShadowDecl>(Found))
9001 return isTemplate ? oc_inherited_constructor_template
9002 : oc_inherited_constructor;
9003 else
9004 return isTemplate ? oc_constructor_template : oc_constructor;
9005 }
Sebastian Redl08905022011-02-05 19:23:19 +00009006
Alexis Hunt119c10e2011-05-25 23:16:36 +00009007 if (Ctor->isDefaultConstructor())
9008 return oc_implicit_default_constructor;
9009
9010 if (Ctor->isMoveConstructor())
9011 return oc_implicit_move_constructor;
9012
9013 assert(Ctor->isCopyConstructor() &&
9014 "unexpected sort of implicit constructor");
9015 return oc_implicit_copy_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00009016 }
9017
9018 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
9019 // This actually gets spelled 'candidate function' for now, but
9020 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00009021 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00009022 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00009023
Alexis Hunt119c10e2011-05-25 23:16:36 +00009024 if (Meth->isMoveAssignmentOperator())
9025 return oc_implicit_move_assignment;
9026
Douglas Gregor12695102012-02-10 08:36:38 +00009027 if (Meth->isCopyAssignmentOperator())
9028 return oc_implicit_copy_assignment;
9029
9030 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
9031 return oc_method;
John McCall53262c92010-01-12 02:15:36 +00009032 }
9033
John McCalle1ac8d12010-01-13 00:25:19 +00009034 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00009035}
9036
Richard Smith5179eb72016-06-28 19:03:57 +00009037void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
9038 // FIXME: It'd be nice to only emit a note once per using-decl per overload
9039 // set.
9040 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
9041 S.Diag(FoundDecl->getLocation(),
9042 diag::note_ovl_candidate_inherited_constructor)
9043 << Shadow->getNominatedBaseClass();
Sebastian Redl08905022011-02-05 19:23:19 +00009044}
9045
John McCall53262c92010-01-12 02:15:36 +00009046} // end anonymous namespace
9047
George Burgess IV5f21c712015-10-12 19:57:04 +00009048static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
9049 const FunctionDecl *FD) {
9050 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
9051 bool AlwaysTrue;
9052 if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
9053 return false;
9054 if (!AlwaysTrue)
9055 return false;
9056 }
9057 return true;
9058}
9059
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009060/// \brief Returns true if we can take the address of the function.
9061///
9062/// \param Complain - If true, we'll emit a diagnostic
9063/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
9064/// we in overload resolution?
9065/// \param Loc - The location of the statement we're complaining about. Ignored
9066/// if we're not complaining, or if we're in overload resolution.
9067static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
9068 bool Complain,
9069 bool InOverloadResolution,
9070 SourceLocation Loc) {
9071 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
9072 if (Complain) {
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009073 if (InOverloadResolution)
9074 S.Diag(FD->getLocStart(),
9075 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
9076 else
9077 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
9078 }
9079 return false;
9080 }
9081
George Burgess IV21081362016-07-24 23:12:40 +00009082 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
9083 return P->hasAttr<PassObjectSizeAttr>();
9084 });
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009085 if (I == FD->param_end())
9086 return true;
9087
9088 if (Complain) {
9089 // Add one to ParamNo because it's user-facing
9090 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
9091 if (InOverloadResolution)
9092 S.Diag(FD->getLocation(),
9093 diag::note_ovl_candidate_has_pass_object_size_params)
9094 << ParamNo;
9095 else
9096 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
9097 << FD << ParamNo;
9098 }
9099 return false;
9100}
9101
9102static bool checkAddressOfCandidateIsAvailable(Sema &S,
9103 const FunctionDecl *FD) {
9104 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
9105 /*InOverloadResolution=*/true,
9106 /*Loc=*/SourceLocation());
9107}
9108
9109bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
9110 bool Complain,
9111 SourceLocation Loc) {
9112 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
9113 /*InOverloadResolution=*/false,
9114 Loc);
9115}
9116
John McCall53262c92010-01-12 02:15:36 +00009117// Notes the location of an overload candidate.
Richard Smithc2bebe92016-05-11 20:37:46 +00009118void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
9119 QualType DestType, bool TakingAddress) {
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009120 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
9121 return;
9122
John McCalle1ac8d12010-01-13 00:25:19 +00009123 std::string FnDesc;
Richard Smithc2bebe92016-05-11 20:37:46 +00009124 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Found, Fn, FnDesc);
Richard Trieucaff2472011-11-23 22:32:32 +00009125 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
9126 << (unsigned) K << FnDesc;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009127
9128 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
Richard Trieucaff2472011-11-23 22:32:32 +00009129 Diag(Fn->getLocation(), PD);
Richard Smith5179eb72016-06-28 19:03:57 +00009130 MaybeEmitInheritedConstructorNote(*this, Found);
John McCallfd0b2f82010-01-06 09:43:14 +00009131}
9132
Nick Lewyckyed4265c2013-09-22 10:06:01 +00009133// Notes the location of all overload candidates designated through
Douglas Gregorb491ed32011-02-19 21:32:49 +00009134// OverloadedExpr
George Burgess IV5f21c712015-10-12 19:57:04 +00009135void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
9136 bool TakingAddress) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009137 assert(OverloadedExpr->getType() == Context.OverloadTy);
9138
9139 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
9140 OverloadExpr *OvlExpr = Ovl.Expression;
9141
9142 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9143 IEnd = OvlExpr->decls_end();
9144 I != IEnd; ++I) {
9145 if (FunctionTemplateDecl *FunTmpl =
9146 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Smithc2bebe92016-05-11 20:37:46 +00009147 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType,
George Burgess IV5f21c712015-10-12 19:57:04 +00009148 TakingAddress);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009149 } else if (FunctionDecl *Fun
9150 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Smithc2bebe92016-05-11 20:37:46 +00009151 NoteOverloadCandidate(*I, Fun, DestType, TakingAddress);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009152 }
9153 }
9154}
9155
John McCall0d1da222010-01-12 00:44:57 +00009156/// Diagnoses an ambiguous conversion. The partial diagnostic is the
9157/// "lead" diagnostic; it will be given two arguments, the source and
9158/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00009159void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
9160 Sema &S,
9161 SourceLocation CaretLoc,
9162 const PartialDiagnostic &PDiag) const {
9163 S.Diag(CaretLoc, PDiag)
9164 << Ambiguous.getFromType() << Ambiguous.getToType();
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00009165 // FIXME: The note limiting machinery is borrowed from
9166 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
9167 // refactoring here.
9168 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9169 unsigned CandsShown = 0;
9170 AmbiguousConversionSequence::const_iterator I, E;
9171 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
9172 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9173 break;
9174 ++CandsShown;
Richard Smithc2bebe92016-05-11 20:37:46 +00009175 S.NoteOverloadCandidate(I->first, I->second);
John McCall0d1da222010-01-12 00:44:57 +00009176 }
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00009177 if (I != E)
9178 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
John McCall12f97bc2010-01-08 04:41:39 +00009179}
9180
Richard Smith17c00b42014-11-12 01:24:00 +00009181static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009182 unsigned I, bool TakingCandidateAddress) {
John McCall6a61b522010-01-13 09:16:55 +00009183 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
9184 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00009185 assert(Cand->Function && "for now, candidate must be a function");
9186 FunctionDecl *Fn = Cand->Function;
9187
9188 // There's a conversion slot for the object argument if this is a
9189 // non-constructor method. Note that 'I' corresponds the
9190 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00009191 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00009192 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00009193 if (I == 0)
9194 isObjectArgument = true;
9195 else
9196 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00009197 }
9198
John McCalle1ac8d12010-01-13 00:25:19 +00009199 std::string FnDesc;
Richard Smithc2bebe92016-05-11 20:37:46 +00009200 OverloadCandidateKind FnKind =
9201 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
John McCalle1ac8d12010-01-13 00:25:19 +00009202
John McCall6a61b522010-01-13 09:16:55 +00009203 Expr *FromExpr = Conv.Bad.FromExpr;
9204 QualType FromTy = Conv.Bad.getFromType();
9205 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00009206
John McCallfb7ad0f2010-02-02 02:42:52 +00009207 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00009208 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00009209 Expr *E = FromExpr->IgnoreParens();
9210 if (isa<UnaryOperator>(E))
9211 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00009212 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00009213
9214 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
9215 << (unsigned) FnKind << FnDesc
9216 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9217 << ToTy << Name << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009218 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCallfb7ad0f2010-02-02 02:42:52 +00009219 return;
9220 }
9221
John McCall6d174642010-01-23 08:10:49 +00009222 // Do some hand-waving analysis to see if the non-viability is due
9223 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00009224 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
9225 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
9226 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
9227 CToTy = RT->getPointeeType();
9228 else {
9229 // TODO: detect and diagnose the full richness of const mismatches.
9230 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
Richard Trieucc3949d2016-02-18 22:34:54 +00009231 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
9232 CFromTy = FromPT->getPointeeType();
9233 CToTy = ToPT->getPointeeType();
9234 }
John McCall47000992010-01-14 03:28:57 +00009235 }
9236
9237 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
9238 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall47000992010-01-14 03:28:57 +00009239 Qualifiers FromQs = CFromTy.getQualifiers();
9240 Qualifiers ToQs = CToTy.getQualifiers();
9241
9242 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
9243 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
9244 << (unsigned) FnKind << FnDesc
9245 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9246 << FromTy
9247 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
9248 << (unsigned) isObjectArgument << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009249 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall47000992010-01-14 03:28:57 +00009250 return;
9251 }
9252
John McCall31168b02011-06-15 23:02:42 +00009253 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00009254 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCall31168b02011-06-15 23:02:42 +00009255 << (unsigned) FnKind << FnDesc
9256 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9257 << FromTy
9258 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
9259 << (unsigned) isObjectArgument << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009260 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall31168b02011-06-15 23:02:42 +00009261 return;
9262 }
9263
Douglas Gregoraec25842011-04-26 23:16:46 +00009264 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
9265 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
9266 << (unsigned) FnKind << FnDesc
9267 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9268 << FromTy
9269 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
9270 << (unsigned) isObjectArgument << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009271 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Douglas Gregoraec25842011-04-26 23:16:46 +00009272 return;
9273 }
9274
Andrey Bokhanko45d41322016-05-11 18:38:21 +00009275 if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
9276 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
9277 << (unsigned) FnKind << FnDesc
9278 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9279 << FromTy << FromQs.hasUnaligned() << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009280 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Andrey Bokhanko45d41322016-05-11 18:38:21 +00009281 return;
9282 }
9283
John McCall47000992010-01-14 03:28:57 +00009284 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
9285 assert(CVR && "unexpected qualifiers mismatch");
9286
9287 if (isObjectArgument) {
9288 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
9289 << (unsigned) FnKind << FnDesc
9290 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9291 << FromTy << (CVR - 1);
9292 } else {
9293 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
9294 << (unsigned) FnKind << FnDesc
9295 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9296 << FromTy << (CVR - 1) << I+1;
9297 }
Richard Smith5179eb72016-06-28 19:03:57 +00009298 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall47000992010-01-14 03:28:57 +00009299 return;
9300 }
9301
Sebastian Redla72462c2011-09-24 17:48:32 +00009302 // Special diagnostic for failure to convert an initializer list, since
9303 // telling the user that it has type void is not useful.
9304 if (FromExpr && isa<InitListExpr>(FromExpr)) {
9305 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
9306 << (unsigned) FnKind << FnDesc
9307 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9308 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009309 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Sebastian Redla72462c2011-09-24 17:48:32 +00009310 return;
9311 }
9312
John McCall6d174642010-01-23 08:10:49 +00009313 // Diagnose references or pointers to incomplete types differently,
9314 // since it's far from impossible that the incompleteness triggered
9315 // the failure.
9316 QualType TempFromTy = FromTy.getNonReferenceType();
9317 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
9318 TempFromTy = PTy->getPointeeType();
9319 if (TempFromTy->isIncompleteType()) {
David Blaikieac928932016-03-04 22:29:11 +00009320 // Emit the generic diagnostic and, optionally, add the hints to it.
John McCall6d174642010-01-23 08:10:49 +00009321 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
9322 << (unsigned) FnKind << FnDesc
9323 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
David Blaikieac928932016-03-04 22:29:11 +00009324 << FromTy << ToTy << (unsigned) isObjectArgument << I+1
9325 << (unsigned) (Cand->Fix.Kind);
9326
Richard Smith5179eb72016-06-28 19:03:57 +00009327 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall6d174642010-01-23 08:10:49 +00009328 return;
9329 }
9330
Douglas Gregor56f2e342010-06-30 23:01:39 +00009331 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009332 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00009333 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
9334 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
9335 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9336 FromPtrTy->getPointeeType()) &&
9337 !FromPtrTy->getPointeeType()->isIncompleteType() &&
9338 !ToPtrTy->getPointeeType()->isIncompleteType() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00009339 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00009340 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009341 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00009342 }
9343 } else if (const ObjCObjectPointerType *FromPtrTy
9344 = FromTy->getAs<ObjCObjectPointerType>()) {
9345 if (const ObjCObjectPointerType *ToPtrTy
9346 = ToTy->getAs<ObjCObjectPointerType>())
9347 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
9348 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
9349 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9350 FromPtrTy->getPointeeType()) &&
9351 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009352 BaseToDerivedConversion = 2;
9353 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009354 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
9355 !FromTy->isIncompleteType() &&
9356 !ToRefTy->getPointeeType()->isIncompleteType() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00009357 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009358 BaseToDerivedConversion = 3;
9359 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
9360 ToTy.getNonReferenceType().getCanonicalType() ==
9361 FromTy.getNonReferenceType().getCanonicalType()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009362 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
9363 << (unsigned) FnKind << FnDesc
9364 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9365 << (unsigned) isObjectArgument << I + 1;
Richard Smith5179eb72016-06-28 19:03:57 +00009366 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009367 return;
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009368 }
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009369 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009370
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009371 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009372 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009373 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00009374 << (unsigned) FnKind << FnDesc
9375 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009376 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009377 << FromTy << ToTy << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009378 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Douglas Gregor56f2e342010-06-30 23:01:39 +00009379 return;
9380 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009381
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00009382 if (isa<ObjCObjectPointerType>(CFromTy) &&
9383 isa<PointerType>(CToTy)) {
9384 Qualifiers FromQs = CFromTy.getQualifiers();
9385 Qualifiers ToQs = CToTy.getQualifiers();
9386 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9387 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
9388 << (unsigned) FnKind << FnDesc
9389 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9390 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009391 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00009392 return;
9393 }
9394 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009395
9396 if (TakingCandidateAddress &&
9397 !checkAddressOfCandidateIsAvailable(S, Cand->Function))
9398 return;
9399
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009400 // Emit the generic diagnostic and, optionally, add the hints to it.
9401 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
9402 FDiag << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00009403 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009404 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
9405 << (unsigned) (Cand->Fix.Kind);
9406
9407 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer490afa62012-01-14 21:05:10 +00009408 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
9409 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009410 FDiag << *HI;
9411 S.Diag(Fn->getLocation(), FDiag);
9412
Richard Smith5179eb72016-06-28 19:03:57 +00009413 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall6a61b522010-01-13 09:16:55 +00009414}
9415
Larisse Voufo98b20f12013-07-19 23:00:19 +00009416/// Additional arity mismatch diagnosis specific to a function overload
9417/// candidates. This is not covered by the more general DiagnoseArityMismatch()
9418/// over a candidate in any candidate set.
Richard Smith17c00b42014-11-12 01:24:00 +00009419static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
9420 unsigned NumArgs) {
John McCall6a61b522010-01-13 09:16:55 +00009421 FunctionDecl *Fn = Cand->Function;
John McCall6a61b522010-01-13 09:16:55 +00009422 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009423
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009424 // With invalid overloaded operators, it's possible that we think we
Larisse Voufo98b20f12013-07-19 23:00:19 +00009425 // have an arity mismatch when in fact it looks like we have the
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009426 // right number of arguments, because only overloaded operators have
9427 // the weird behavior of overloading member and non-member functions.
9428 // Just don't report anything.
9429 if (Fn->isInvalidDecl() &&
9430 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009431 return true;
9432
9433 if (NumArgs < MinParams) {
9434 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
9435 (Cand->FailureKind == ovl_fail_bad_deduction &&
9436 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
9437 } else {
9438 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
9439 (Cand->FailureKind == ovl_fail_bad_deduction &&
9440 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
9441 }
9442
9443 return false;
9444}
9445
9446/// General arity mismatch diagnosis over a candidate in a candidate set.
Richard Smithc2bebe92016-05-11 20:37:46 +00009447static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
9448 unsigned NumFormalArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009449 assert(isa<FunctionDecl>(D) &&
9450 "The templated declaration should at least be a function"
9451 " when diagnosing bad template argument deduction due to too many"
9452 " or too few arguments");
9453
9454 FunctionDecl *Fn = cast<FunctionDecl>(D);
9455
9456 // TODO: treat calls to a missing default constructor as a special case
9457 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
9458 unsigned MinParams = Fn->getMinRequiredArguments();
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009459
John McCall6a61b522010-01-13 09:16:55 +00009460 // at least / at most / exactly
9461 unsigned mode, modeCount;
9462 if (NumFormalArgs < MinParams) {
Alp Toker9cacbab2014-01-20 20:26:09 +00009463 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
9464 FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00009465 mode = 0; // "at least"
9466 else
9467 mode = 2; // "exactly"
9468 modeCount = MinParams;
9469 } else {
Alp Toker9cacbab2014-01-20 20:26:09 +00009470 if (MinParams != FnTy->getNumParams())
John McCall6a61b522010-01-13 09:16:55 +00009471 mode = 1; // "at most"
9472 else
9473 mode = 2; // "exactly"
Alp Toker9cacbab2014-01-20 20:26:09 +00009474 modeCount = FnTy->getNumParams();
John McCall6a61b522010-01-13 09:16:55 +00009475 }
9476
9477 std::string Description;
Richard Smithc2bebe92016-05-11 20:37:46 +00009478 OverloadCandidateKind FnKind =
9479 ClassifyOverloadCandidate(S, Found, Fn, Description);
John McCall6a61b522010-01-13 09:16:55 +00009480
Richard Smith10ff50d2012-05-11 05:16:41 +00009481 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
9482 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
Craig Topperc3ec1492014-05-26 06:22:03 +00009483 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9484 << mode << Fn->getParamDecl(0) << NumFormalArgs;
Richard Smith10ff50d2012-05-11 05:16:41 +00009485 else
9486 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Craig Topperc3ec1492014-05-26 06:22:03 +00009487 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9488 << mode << modeCount << NumFormalArgs;
Richard Smith5179eb72016-06-28 19:03:57 +00009489 MaybeEmitInheritedConstructorNote(S, Found);
John McCalle1ac8d12010-01-13 00:25:19 +00009490}
9491
Larisse Voufo98b20f12013-07-19 23:00:19 +00009492/// Arity mismatch diagnosis specific to a function overload candidate.
Richard Smith17c00b42014-11-12 01:24:00 +00009493static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
9494 unsigned NumFormalArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009495 if (!CheckArityMismatch(S, Cand, NumFormalArgs))
Richard Smithc2bebe92016-05-11 20:37:46 +00009496 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
Larisse Voufo98b20f12013-07-19 23:00:19 +00009497}
Larisse Voufo47c08452013-07-19 22:53:23 +00009498
Richard Smith17c00b42014-11-12 01:24:00 +00009499static TemplateDecl *getDescribedTemplate(Decl *Templated) {
Serge Pavlov7dcc97e2016-04-19 06:19:52 +00009500 if (TemplateDecl *TD = Templated->getDescribedTemplate())
9501 return TD;
Larisse Voufo98b20f12013-07-19 23:00:19 +00009502 llvm_unreachable("Unsupported: Getting the described template declaration"
9503 " for bad deduction diagnosis");
9504}
9505
9506/// Diagnose a failed template-argument deduction.
Richard Smithc2bebe92016-05-11 20:37:46 +00009507static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
Richard Smith17c00b42014-11-12 01:24:00 +00009508 DeductionFailureInfo &DeductionFailure,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009509 unsigned NumArgs,
9510 bool TakingCandidateAddress) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009511 TemplateParameter Param = DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009512 NamedDecl *ParamD;
9513 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
9514 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
9515 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
Larisse Voufo98b20f12013-07-19 23:00:19 +00009516 switch (DeductionFailure.Result) {
John McCall8b9ed552010-02-01 18:53:26 +00009517 case Sema::TDK_Success:
9518 llvm_unreachable("TDK_success while diagnosing bad deduction");
9519
9520 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00009521 assert(ParamD && "no parameter found for incomplete deduction result");
Larisse Voufo98b20f12013-07-19 23:00:19 +00009522 S.Diag(Templated->getLocation(),
9523 diag::note_ovl_candidate_incomplete_deduction)
9524 << ParamD->getDeclName();
Richard Smith5179eb72016-06-28 19:03:57 +00009525 MaybeEmitInheritedConstructorNote(S, Found);
John McCall8b9ed552010-02-01 18:53:26 +00009526 return;
9527 }
9528
John McCall42d7d192010-08-05 09:05:08 +00009529 case Sema::TDK_Underqualified: {
9530 assert(ParamD && "no parameter found for bad qualifiers deduction result");
9531 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
9532
Larisse Voufo98b20f12013-07-19 23:00:19 +00009533 QualType Param = DeductionFailure.getFirstArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00009534
9535 // Param will have been canonicalized, but it should just be a
9536 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00009537 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00009538 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00009539 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00009540 assert(S.Context.hasSameType(Param, NonCanonParam));
9541
9542 // Arg has also been canonicalized, but there's nothing we can do
9543 // about that. It also doesn't matter as much, because it won't
9544 // have any template parameters in it (because deduction isn't
9545 // done on dependent types).
Larisse Voufo98b20f12013-07-19 23:00:19 +00009546 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00009547
Larisse Voufo98b20f12013-07-19 23:00:19 +00009548 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
9549 << ParamD->getDeclName() << Arg << NonCanonParam;
Richard Smith5179eb72016-06-28 19:03:57 +00009550 MaybeEmitInheritedConstructorNote(S, Found);
John McCall42d7d192010-08-05 09:05:08 +00009551 return;
9552 }
9553
9554 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00009555 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009556 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009557 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009558 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009559 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009560 which = 1;
9561 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009562 which = 2;
9563 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009564
Larisse Voufo98b20f12013-07-19 23:00:19 +00009565 S.Diag(Templated->getLocation(),
9566 diag::note_ovl_candidate_inconsistent_deduction)
9567 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
9568 << *DeductionFailure.getSecondArg();
Richard Smith5179eb72016-06-28 19:03:57 +00009569 MaybeEmitInheritedConstructorNote(S, Found);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009570 return;
9571 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00009572
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009573 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009574 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009575 if (ParamD->getDeclName())
Larisse Voufo98b20f12013-07-19 23:00:19 +00009576 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009577 diag::note_ovl_candidate_explicit_arg_mismatch_named)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009578 << ParamD->getDeclName();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009579 else {
9580 int index = 0;
9581 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
9582 index = TTP->getIndex();
9583 else if (NonTypeTemplateParmDecl *NTTP
9584 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
9585 index = NTTP->getIndex();
9586 else
9587 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
Larisse Voufo98b20f12013-07-19 23:00:19 +00009588 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009589 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009590 << (index + 1);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009591 }
Richard Smith5179eb72016-06-28 19:03:57 +00009592 MaybeEmitInheritedConstructorNote(S, Found);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009593 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009594
Douglas Gregor02eb4832010-05-08 18:13:28 +00009595 case Sema::TDK_TooManyArguments:
9596 case Sema::TDK_TooFewArguments:
Richard Smithc2bebe92016-05-11 20:37:46 +00009597 DiagnoseArityMismatch(S, Found, Templated, NumArgs);
Douglas Gregor02eb4832010-05-08 18:13:28 +00009598 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00009599
9600 case Sema::TDK_InstantiationDepth:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009601 S.Diag(Templated->getLocation(),
9602 diag::note_ovl_candidate_instantiation_depth);
Richard Smith5179eb72016-06-28 19:03:57 +00009603 MaybeEmitInheritedConstructorNote(S, Found);
Douglas Gregord09efd42010-05-08 20:07:26 +00009604 return;
9605
9606 case Sema::TDK_SubstitutionFailure: {
Richard Smith9ca64612012-05-07 09:03:25 +00009607 // Format the template argument list into the argument string.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009608 SmallString<128> TemplateArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00009609 if (TemplateArgumentList *Args =
Larisse Voufo98b20f12013-07-19 23:00:19 +00009610 DeductionFailure.getTemplateArgumentList()) {
Richard Smith9ca64612012-05-07 09:03:25 +00009611 TemplateArgString = " ";
9612 TemplateArgString += S.getTemplateArgumentBindingsText(
Larisse Voufo98b20f12013-07-19 23:00:19 +00009613 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
Richard Smith9ca64612012-05-07 09:03:25 +00009614 }
9615
Richard Smith6f8d2c62012-05-09 05:17:00 +00009616 // If this candidate was disabled by enable_if, say so.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009617 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
Richard Smith6f8d2c62012-05-09 05:17:00 +00009618 if (PDiag && PDiag->second.getDiagID() ==
9619 diag::err_typename_nested_not_found_enable_if) {
9620 // FIXME: Use the source range of the condition, and the fully-qualified
9621 // name of the enable_if template. These are both present in PDiag.
9622 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
9623 << "'enable_if'" << TemplateArgString;
9624 return;
9625 }
9626
Richard Smith9ca64612012-05-07 09:03:25 +00009627 // Format the SFINAE diagnostic into the argument string.
9628 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
9629 // formatted message in another diagnostic.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009630 SmallString<128> SFINAEArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00009631 SourceRange R;
Richard Smith6f8d2c62012-05-09 05:17:00 +00009632 if (PDiag) {
Richard Smith9ca64612012-05-07 09:03:25 +00009633 SFINAEArgString = ": ";
9634 R = SourceRange(PDiag->first, PDiag->first);
9635 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
9636 }
9637
Larisse Voufo98b20f12013-07-19 23:00:19 +00009638 S.Diag(Templated->getLocation(),
9639 diag::note_ovl_candidate_substitution_failure)
9640 << TemplateArgString << SFINAEArgString << R;
Richard Smith5179eb72016-06-28 19:03:57 +00009641 MaybeEmitInheritedConstructorNote(S, Found);
Douglas Gregord09efd42010-05-08 20:07:26 +00009642 return;
9643 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009644
Richard Smith8c6eeb92013-01-31 04:03:12 +00009645 case Sema::TDK_FailedOverloadResolution: {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009646 OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr());
9647 S.Diag(Templated->getLocation(),
Richard Smith8c6eeb92013-01-31 04:03:12 +00009648 diag::note_ovl_candidate_failed_overload_resolution)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009649 << R.Expression->getName();
Richard Smith8c6eeb92013-01-31 04:03:12 +00009650 return;
9651 }
9652
Richard Smith9b534542015-12-31 02:02:54 +00009653 case Sema::TDK_DeducedMismatch: {
9654 // Format the template argument list into the argument string.
9655 SmallString<128> TemplateArgString;
9656 if (TemplateArgumentList *Args =
9657 DeductionFailure.getTemplateArgumentList()) {
9658 TemplateArgString = " ";
9659 TemplateArgString += S.getTemplateArgumentBindingsText(
9660 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9661 }
9662
9663 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
9664 << (*DeductionFailure.getCallArgIndex() + 1)
9665 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
9666 << TemplateArgString;
9667 break;
9668 }
9669
Richard Trieue3732352013-04-08 21:11:40 +00009670 case Sema::TDK_NonDeducedMismatch: {
Richard Smith44ecdbd2013-01-31 05:19:49 +00009671 // FIXME: Provide a source location to indicate what we couldn't match.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009672 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
9673 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
Richard Trieue3732352013-04-08 21:11:40 +00009674 if (FirstTA.getKind() == TemplateArgument::Template &&
9675 SecondTA.getKind() == TemplateArgument::Template) {
9676 TemplateName FirstTN = FirstTA.getAsTemplate();
9677 TemplateName SecondTN = SecondTA.getAsTemplate();
9678 if (FirstTN.getKind() == TemplateName::Template &&
9679 SecondTN.getKind() == TemplateName::Template) {
9680 if (FirstTN.getAsTemplateDecl()->getName() ==
9681 SecondTN.getAsTemplateDecl()->getName()) {
9682 // FIXME: This fixes a bad diagnostic where both templates are named
9683 // the same. This particular case is a bit difficult since:
9684 // 1) It is passed as a string to the diagnostic printer.
9685 // 2) The diagnostic printer only attempts to find a better
9686 // name for types, not decls.
9687 // Ideally, this should folded into the diagnostic printer.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009688 S.Diag(Templated->getLocation(),
Richard Trieue3732352013-04-08 21:11:40 +00009689 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
9690 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
9691 return;
9692 }
9693 }
9694 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009695
9696 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
9697 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
9698 return;
9699
Faisal Vali2b391ab2013-09-26 19:54:12 +00009700 // FIXME: For generic lambda parameters, check if the function is a lambda
9701 // call operator, and if so, emit a prettier and more informative
9702 // diagnostic that mentions 'auto' and lambda in addition to
9703 // (or instead of?) the canonical template type parameters.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009704 S.Diag(Templated->getLocation(),
9705 diag::note_ovl_candidate_non_deduced_mismatch)
9706 << FirstTA << SecondTA;
Richard Smith44ecdbd2013-01-31 05:19:49 +00009707 return;
Richard Trieue3732352013-04-08 21:11:40 +00009708 }
John McCall8b9ed552010-02-01 18:53:26 +00009709 // TODO: diagnose these individually, then kill off
9710 // note_ovl_candidate_bad_deduction, which is uselessly vague.
Richard Smith44ecdbd2013-01-31 05:19:49 +00009711 case Sema::TDK_MiscellaneousDeductionFailure:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009712 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
Richard Smith5179eb72016-06-28 19:03:57 +00009713 MaybeEmitInheritedConstructorNote(S, Found);
John McCall8b9ed552010-02-01 18:53:26 +00009714 return;
9715 }
9716}
9717
Larisse Voufo98b20f12013-07-19 23:00:19 +00009718/// Diagnose a failed template-argument deduction, for function calls.
Richard Smith17c00b42014-11-12 01:24:00 +00009719static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009720 unsigned NumArgs,
9721 bool TakingCandidateAddress) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009722 unsigned TDK = Cand->DeductionFailure.Result;
9723 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
9724 if (CheckArityMismatch(S, Cand, NumArgs))
9725 return;
9726 }
Richard Smithc2bebe92016-05-11 20:37:46 +00009727 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009728 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
Larisse Voufo98b20f12013-07-19 23:00:19 +00009729}
9730
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009731/// CUDA: diagnose an invalid call across targets.
Richard Smith17c00b42014-11-12 01:24:00 +00009732static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009733 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
9734 FunctionDecl *Callee = Cand->Function;
9735
9736 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
9737 CalleeTarget = S.IdentifyCUDATarget(Callee);
9738
9739 std::string FnDesc;
Richard Smithc2bebe92016-05-11 20:37:46 +00009740 OverloadCandidateKind FnKind =
9741 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc);
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009742
9743 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
Eli Bendersky9a220fc2014-09-29 20:38:29 +00009744 << (unsigned)FnKind << CalleeTarget << CallerTarget;
9745
9746 // This could be an implicit constructor for which we could not infer the
9747 // target due to a collsion. Diagnose that case.
9748 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
9749 if (Meth != nullptr && Meth->isImplicit()) {
9750 CXXRecordDecl *ParentClass = Meth->getParent();
9751 Sema::CXXSpecialMember CSM;
9752
9753 switch (FnKind) {
9754 default:
9755 return;
9756 case oc_implicit_default_constructor:
9757 CSM = Sema::CXXDefaultConstructor;
9758 break;
9759 case oc_implicit_copy_constructor:
9760 CSM = Sema::CXXCopyConstructor;
9761 break;
9762 case oc_implicit_move_constructor:
9763 CSM = Sema::CXXMoveConstructor;
9764 break;
9765 case oc_implicit_copy_assignment:
9766 CSM = Sema::CXXCopyAssignment;
9767 break;
9768 case oc_implicit_move_assignment:
9769 CSM = Sema::CXXMoveAssignment;
9770 break;
9771 };
9772
9773 bool ConstRHS = false;
9774 if (Meth->getNumParams()) {
9775 if (const ReferenceType *RT =
9776 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
9777 ConstRHS = RT->getPointeeType().isConstQualified();
9778 }
9779 }
9780
9781 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
9782 /* ConstRHS */ ConstRHS,
9783 /* Diagnose */ true);
9784 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009785}
9786
Richard Smith17c00b42014-11-12 01:24:00 +00009787static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009788 FunctionDecl *Callee = Cand->Function;
9789 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
9790
9791 S.Diag(Callee->getLocation(),
9792 diag::note_ovl_candidate_disabled_by_enable_if_attr)
9793 << Attr->getCond()->getSourceRange() << Attr->getMessage();
9794}
9795
John McCall8b9ed552010-02-01 18:53:26 +00009796/// Generates a 'note' diagnostic for an overload candidate. We've
9797/// already generated a primary error at the call site.
9798///
9799/// It really does need to be a single diagnostic with its caret
9800/// pointed at the candidate declaration. Yes, this creates some
9801/// major challenges of technical writing. Yes, this makes pointing
9802/// out problems with specific arguments quite awkward. It's still
9803/// better than generating twenty screens of text for every failed
9804/// overload.
9805///
9806/// It would be great to be able to express per-candidate problems
9807/// more richly for those diagnostic clients that cared, but we'd
9808/// still have to be just as careful with the default diagnostics.
Richard Smith17c00b42014-11-12 01:24:00 +00009809static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009810 unsigned NumArgs,
9811 bool TakingCandidateAddress) {
John McCall53262c92010-01-12 02:15:36 +00009812 FunctionDecl *Fn = Cand->Function;
9813
John McCall12f97bc2010-01-08 04:41:39 +00009814 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00009815 if (Cand->Viable && (Fn->isDeleted() ||
9816 S.isFunctionConsideredUnavailable(Fn))) {
John McCalle1ac8d12010-01-13 00:25:19 +00009817 std::string FnDesc;
Richard Smithc2bebe92016-05-11 20:37:46 +00009818 OverloadCandidateKind FnKind =
9819 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00009820
9821 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
Richard Smith6f1e2c62012-04-02 20:59:25 +00009822 << FnKind << FnDesc
9823 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
Richard Smith5179eb72016-06-28 19:03:57 +00009824 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCalld3224162010-01-08 00:58:21 +00009825 return;
John McCall12f97bc2010-01-08 04:41:39 +00009826 }
9827
John McCalle1ac8d12010-01-13 00:25:19 +00009828 // We don't really have anything else to say about viable candidates.
9829 if (Cand->Viable) {
Richard Smithc2bebe92016-05-11 20:37:46 +00009830 S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009831 return;
9832 }
John McCall0d1da222010-01-12 00:44:57 +00009833
John McCall6a61b522010-01-13 09:16:55 +00009834 switch (Cand->FailureKind) {
9835 case ovl_fail_too_many_arguments:
9836 case ovl_fail_too_few_arguments:
9837 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00009838
John McCall6a61b522010-01-13 09:16:55 +00009839 case ovl_fail_bad_deduction:
Richard Smithc2bebe92016-05-11 20:37:46 +00009840 return DiagnoseBadDeduction(S, Cand, NumArgs,
9841 TakingCandidateAddress);
John McCall8b9ed552010-02-01 18:53:26 +00009842
John McCall578a1f82014-12-14 01:46:53 +00009843 case ovl_fail_illegal_constructor: {
9844 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
9845 << (Fn->getPrimaryTemplate() ? 1 : 0);
Richard Smith5179eb72016-06-28 19:03:57 +00009846 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall578a1f82014-12-14 01:46:53 +00009847 return;
9848 }
9849
John McCallfe796dd2010-01-23 05:17:32 +00009850 case ovl_fail_trivial_conversion:
9851 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00009852 case ovl_fail_final_conversion_not_exact:
Richard Smithc2bebe92016-05-11 20:37:46 +00009853 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009854
John McCall65eb8792010-02-25 01:37:24 +00009855 case ovl_fail_bad_conversion: {
9856 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009857 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00009858 if (Cand->Conversions[I].isBad())
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009859 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009860
John McCall6a61b522010-01-13 09:16:55 +00009861 // FIXME: this currently happens when we're called from SemaInit
9862 // when user-conversion overload fails. Figure out how to handle
9863 // those conditions and diagnose them well.
Richard Smithc2bebe92016-05-11 20:37:46 +00009864 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009865 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009866
9867 case ovl_fail_bad_target:
9868 return DiagnoseBadTarget(S, Cand);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009869
9870 case ovl_fail_enable_if:
9871 return DiagnoseFailedEnableIfAttr(S, Cand);
George Burgess IV7204ed92016-01-07 02:26:57 +00009872
9873 case ovl_fail_addr_not_available: {
9874 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
9875 (void)Available;
9876 assert(!Available);
9877 break;
9878 }
John McCall65eb8792010-02-25 01:37:24 +00009879 }
John McCalld3224162010-01-08 00:58:21 +00009880}
9881
Richard Smith17c00b42014-11-12 01:24:00 +00009882static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
John McCalld3224162010-01-08 00:58:21 +00009883 // Desugar the type of the surrogate down to a function type,
9884 // retaining as many typedefs as possible while still showing
9885 // the function type (and, therefore, its parameter types).
9886 QualType FnType = Cand->Surrogate->getConversionType();
9887 bool isLValueReference = false;
9888 bool isRValueReference = false;
9889 bool isPointer = false;
9890 if (const LValueReferenceType *FnTypeRef =
9891 FnType->getAs<LValueReferenceType>()) {
9892 FnType = FnTypeRef->getPointeeType();
9893 isLValueReference = true;
9894 } else if (const RValueReferenceType *FnTypeRef =
9895 FnType->getAs<RValueReferenceType>()) {
9896 FnType = FnTypeRef->getPointeeType();
9897 isRValueReference = true;
9898 }
9899 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
9900 FnType = FnTypePtr->getPointeeType();
9901 isPointer = true;
9902 }
9903 // Desugar down to a function type.
9904 FnType = QualType(FnType->getAs<FunctionType>(), 0);
9905 // Reconstruct the pointer/reference as appropriate.
9906 if (isPointer) FnType = S.Context.getPointerType(FnType);
9907 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
9908 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
9909
9910 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
9911 << FnType;
9912}
9913
Richard Smith17c00b42014-11-12 01:24:00 +00009914static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
9915 SourceLocation OpLoc,
9916 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00009917 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalld3224162010-01-08 00:58:21 +00009918 std::string TypeStr("operator");
9919 TypeStr += Opc;
9920 TypeStr += "(";
9921 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramerb0095172012-01-14 16:32:05 +00009922 if (Cand->NumConversions == 1) {
John McCalld3224162010-01-08 00:58:21 +00009923 TypeStr += ")";
9924 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
9925 } else {
9926 TypeStr += ", ";
9927 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
9928 TypeStr += ")";
9929 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
9930 }
9931}
9932
Richard Smith17c00b42014-11-12 01:24:00 +00009933static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
9934 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00009935 unsigned NoOperands = Cand->NumConversions;
John McCalld3224162010-01-08 00:58:21 +00009936 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
9937 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00009938 if (ICS.isBad()) break; // all meaningless after first invalid
9939 if (!ICS.isAmbiguous()) continue;
9940
Richard Smithc2bebe92016-05-11 20:37:46 +00009941 ICS.DiagnoseAmbiguousConversion(
9942 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00009943 }
9944}
9945
Larisse Voufo98b20f12013-07-19 23:00:19 +00009946static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
John McCall3712d9e2010-01-15 23:32:50 +00009947 if (Cand->Function)
9948 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00009949 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00009950 return Cand->Surrogate->getLocation();
9951 return SourceLocation();
9952}
9953
Larisse Voufo98b20f12013-07-19 23:00:19 +00009954static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
Chandler Carruth73fddfe2011-09-10 00:51:24 +00009955 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009956 case Sema::TDK_Success:
David Blaikie83d382b2011-09-23 05:06:16 +00009957 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00009958
Douglas Gregorc5c01a62012-09-13 21:01:57 +00009959 case Sema::TDK_Invalid:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009960 case Sema::TDK_Incomplete:
9961 return 1;
9962
9963 case Sema::TDK_Underqualified:
9964 case Sema::TDK_Inconsistent:
9965 return 2;
9966
9967 case Sema::TDK_SubstitutionFailure:
Richard Smith9b534542015-12-31 02:02:54 +00009968 case Sema::TDK_DeducedMismatch:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009969 case Sema::TDK_NonDeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +00009970 case Sema::TDK_MiscellaneousDeductionFailure:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009971 return 3;
9972
9973 case Sema::TDK_InstantiationDepth:
9974 case Sema::TDK_FailedOverloadResolution:
9975 return 4;
9976
9977 case Sema::TDK_InvalidExplicitArguments:
9978 return 5;
9979
9980 case Sema::TDK_TooManyArguments:
9981 case Sema::TDK_TooFewArguments:
9982 return 6;
9983 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00009984 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009985}
9986
Richard Smith17c00b42014-11-12 01:24:00 +00009987namespace {
John McCallad2587a2010-01-12 00:48:53 +00009988struct CompareOverloadCandidatesForDisplay {
9989 Sema &S;
Richard Smith0f59cb32015-12-18 21:45:41 +00009990 SourceLocation Loc;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009991 size_t NumArgs;
9992
Richard Smith0f59cb32015-12-18 21:45:41 +00009993 CompareOverloadCandidatesForDisplay(Sema &S, SourceLocation Loc, size_t nArgs)
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009994 : S(S), NumArgs(nArgs) {}
John McCall12f97bc2010-01-08 04:41:39 +00009995
9996 bool operator()(const OverloadCandidate *L,
9997 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00009998 // Fast-path this check.
9999 if (L == R) return false;
10000
John McCall12f97bc2010-01-08 04:41:39 +000010001 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +000010002 if (L->Viable) {
10003 if (!R->Viable) return true;
10004
10005 // TODO: introduce a tri-valued comparison for overload
10006 // candidates. Would be more worthwhile if we had a sort
10007 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +000010008 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
10009 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +000010010 } else if (R->Viable)
10011 return false;
John McCall12f97bc2010-01-08 04:41:39 +000010012
John McCall3712d9e2010-01-15 23:32:50 +000010013 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +000010014
John McCall3712d9e2010-01-15 23:32:50 +000010015 // Criteria by which we can sort non-viable candidates:
10016 if (!L->Viable) {
10017 // 1. Arity mismatches come after other candidates.
10018 if (L->FailureKind == ovl_fail_too_many_arguments ||
Kaelyn Takatab96b3be2014-05-01 21:15:24 +000010019 L->FailureKind == ovl_fail_too_few_arguments) {
10020 if (R->FailureKind == ovl_fail_too_many_arguments ||
10021 R->FailureKind == ovl_fail_too_few_arguments) {
Kaelyn Takata50c4ffc2014-05-07 00:43:38 +000010022 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
10023 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
10024 if (LDist == RDist) {
10025 if (L->FailureKind == R->FailureKind)
10026 // Sort non-surrogates before surrogates.
10027 return !L->IsSurrogate && R->IsSurrogate;
10028 // Sort candidates requiring fewer parameters than there were
10029 // arguments given after candidates requiring more parameters
10030 // than there were arguments given.
10031 return L->FailureKind == ovl_fail_too_many_arguments;
10032 }
Kaelyn Takatab96b3be2014-05-01 21:15:24 +000010033 return LDist < RDist;
10034 }
John McCall3712d9e2010-01-15 23:32:50 +000010035 return false;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +000010036 }
John McCall3712d9e2010-01-15 23:32:50 +000010037 if (R->FailureKind == ovl_fail_too_many_arguments ||
10038 R->FailureKind == ovl_fail_too_few_arguments)
10039 return true;
John McCall12f97bc2010-01-08 04:41:39 +000010040
John McCallfe796dd2010-01-23 05:17:32 +000010041 // 2. Bad conversions come first and are ordered by the number
10042 // of bad conversions and quality of good conversions.
10043 if (L->FailureKind == ovl_fail_bad_conversion) {
10044 if (R->FailureKind != ovl_fail_bad_conversion)
10045 return true;
10046
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010047 // The conversion that can be fixed with a smaller number of changes,
10048 // comes first.
10049 unsigned numLFixes = L->Fix.NumConversionsFixed;
10050 unsigned numRFixes = R->Fix.NumConversionsFixed;
10051 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
10052 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +000010053 if (numLFixes != numRFixes) {
David Blaikie7a3cbb22015-03-09 02:02:07 +000010054 return numLFixes < numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +000010055 }
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010056
John McCallfe796dd2010-01-23 05:17:32 +000010057 // If there's any ordering between the defined conversions...
10058 // FIXME: this might not be transitive.
Benjamin Kramerb0095172012-01-14 16:32:05 +000010059 assert(L->NumConversions == R->NumConversions);
John McCallfe796dd2010-01-23 05:17:32 +000010060
10061 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +000010062 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramerb0095172012-01-14 16:32:05 +000010063 for (unsigned E = L->NumConversions; I != E; ++I) {
Richard Smith0f59cb32015-12-18 21:45:41 +000010064 switch (CompareImplicitConversionSequences(S, Loc,
John McCall5c32be02010-08-24 20:38:10 +000010065 L->Conversions[I],
10066 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +000010067 case ImplicitConversionSequence::Better:
10068 leftBetter++;
10069 break;
10070
10071 case ImplicitConversionSequence::Worse:
10072 leftBetter--;
10073 break;
10074
10075 case ImplicitConversionSequence::Indistinguishable:
10076 break;
10077 }
10078 }
10079 if (leftBetter > 0) return true;
10080 if (leftBetter < 0) return false;
10081
10082 } else if (R->FailureKind == ovl_fail_bad_conversion)
10083 return false;
10084
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010085 if (L->FailureKind == ovl_fail_bad_deduction) {
10086 if (R->FailureKind != ovl_fail_bad_deduction)
10087 return true;
10088
10089 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10090 return RankDeductionFailure(L->DeductionFailure)
Eli Friedman1e7a0c62011-10-14 23:10:30 +000010091 < RankDeductionFailure(R->DeductionFailure);
Eli Friedmane2c600c2011-10-14 21:52:24 +000010092 } else if (R->FailureKind == ovl_fail_bad_deduction)
10093 return false;
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010094
John McCall3712d9e2010-01-15 23:32:50 +000010095 // TODO: others?
10096 }
10097
10098 // Sort everything else by location.
10099 SourceLocation LLoc = GetLocationForCandidate(L);
10100 SourceLocation RLoc = GetLocationForCandidate(R);
10101
10102 // Put candidates without locations (e.g. builtins) at the end.
10103 if (LLoc.isInvalid()) return false;
10104 if (RLoc.isInvalid()) return true;
10105
10106 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +000010107 }
10108};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010109}
John McCall12f97bc2010-01-08 04:41:39 +000010110
John McCallfe796dd2010-01-23 05:17:32 +000010111/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010112/// computes up to the first. Produces the FixIt set if possible.
Richard Smith17c00b42014-11-12 01:24:00 +000010113static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
10114 ArrayRef<Expr *> Args) {
John McCallfe796dd2010-01-23 05:17:32 +000010115 assert(!Cand->Viable);
10116
10117 // Don't do anything on failures other than bad conversion.
10118 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
10119
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010120 // We only want the FixIts if all the arguments can be corrected.
10121 bool Unfixable = false;
Anna Zaks1b068122011-07-28 19:46:48 +000010122 // Use a implicit copy initialization to check conversion fixes.
10123 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010124
John McCallfe796dd2010-01-23 05:17:32 +000010125 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +000010126 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +000010127 unsigned ConvCount = Cand->NumConversions;
John McCallfe796dd2010-01-23 05:17:32 +000010128 while (true) {
10129 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
10130 ConvIdx++;
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010131 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaks1b068122011-07-28 19:46:48 +000010132 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCallfe796dd2010-01-23 05:17:32 +000010133 break;
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010134 }
John McCallfe796dd2010-01-23 05:17:32 +000010135 }
10136
10137 if (ConvIdx == ConvCount)
10138 return;
10139
John McCall65eb8792010-02-25 01:37:24 +000010140 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
10141 "remaining conversion is initialized?");
10142
Douglas Gregoradc7a702010-04-16 17:45:54 +000010143 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +000010144 // operation somehow.
10145 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +000010146
10147 const FunctionProtoType* Proto;
10148 unsigned ArgIdx = ConvIdx;
10149
10150 if (Cand->IsSurrogate) {
10151 QualType ConvType
10152 = Cand->Surrogate->getConversionType().getNonReferenceType();
10153 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10154 ConvType = ConvPtrType->getPointeeType();
10155 Proto = ConvType->getAs<FunctionProtoType>();
10156 ArgIdx--;
10157 } else if (Cand->Function) {
10158 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
10159 if (isa<CXXMethodDecl>(Cand->Function) &&
10160 !isa<CXXConstructorDecl>(Cand->Function))
10161 ArgIdx--;
10162 } else {
10163 // Builtin binary operator with a bad first conversion.
10164 assert(ConvCount <= 3);
10165 for (; ConvIdx != ConvCount; ++ConvIdx)
10166 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +000010167 = TryCopyInitialization(S, Args[ConvIdx],
10168 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010169 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +000010170 /*InOverloadResolution*/ true,
10171 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +000010172 S.getLangOpts().ObjCAutoRefCount);
John McCallfe796dd2010-01-23 05:17:32 +000010173 return;
10174 }
10175
10176 // Fill in the rest of the conversions.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000010177 unsigned NumParams = Proto->getNumParams();
John McCallfe796dd2010-01-23 05:17:32 +000010178 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000010179 if (ArgIdx < NumParams) {
Alp Toker9cacbab2014-01-20 20:26:09 +000010180 Cand->Conversions[ConvIdx] = TryCopyInitialization(
10181 S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions,
10182 /*InOverloadResolution=*/true,
10183 /*AllowObjCWritebackConversion=*/
10184 S.getLangOpts().ObjCAutoRefCount);
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010185 // Store the FixIt in the candidate if it exists.
10186 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaks1b068122011-07-28 19:46:48 +000010187 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010188 }
John McCallfe796dd2010-01-23 05:17:32 +000010189 else
10190 Cand->Conversions[ConvIdx].setEllipsis();
10191 }
10192}
10193
Douglas Gregor5251f1b2008-10-21 16:13:35 +000010194/// PrintOverloadCandidates - When overload resolution fails, prints
10195/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +000010196/// set.
Richard Smithb2f0f052016-10-10 18:54:32 +000010197void OverloadCandidateSet::NoteCandidates(
10198 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
10199 StringRef Opc, SourceLocation OpLoc,
10200 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
John McCall12f97bc2010-01-08 04:41:39 +000010201 // Sort the candidates by viability and position. Sorting directly would
10202 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010203 SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +000010204 if (OCD == OCD_AllCandidates) Cands.reserve(size());
10205 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
Richard Smithb2f0f052016-10-10 18:54:32 +000010206 if (!Filter(*Cand))
10207 continue;
John McCallfe796dd2010-01-23 05:17:32 +000010208 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +000010209 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +000010210 else if (OCD == OCD_AllCandidates) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010211 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010212 if (Cand->Function || Cand->IsSurrogate)
10213 Cands.push_back(Cand);
10214 // Otherwise, this a non-viable builtin candidate. We do not, in general,
10215 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +000010216 }
10217 }
10218
John McCallad2587a2010-01-12 00:48:53 +000010219 std::sort(Cands.begin(), Cands.end(),
Richard Smith0f59cb32015-12-18 21:45:41 +000010220 CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size()));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010221
John McCall0d1da222010-01-12 00:44:57 +000010222 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +000010223
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010224 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Douglas Gregor79591782012-10-23 23:11:23 +000010225 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010226 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +000010227 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10228 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +000010229
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010230 // Set an arbitrary limit on the number of candidate functions we'll spam
10231 // the user with. FIXME: This limit should depend on details of the
10232 // candidate list.
Douglas Gregor79591782012-10-23 23:11:23 +000010233 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010234 break;
10235 }
10236 ++CandsShown;
10237
John McCalld3224162010-01-08 00:58:21 +000010238 if (Cand->Function)
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010239 NoteFunctionCandidate(S, Cand, Args.size(),
10240 /*TakingCandidateAddress=*/false);
John McCalld3224162010-01-08 00:58:21 +000010241 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +000010242 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010243 else {
10244 assert(Cand->Viable &&
10245 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +000010246 // Generally we only see ambiguities including viable builtin
10247 // operators if overload resolution got screwed up by an
10248 // ambiguous user-defined conversion.
10249 //
10250 // FIXME: It's quite possible for different conversions to see
10251 // different ambiguities, though.
10252 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +000010253 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +000010254 ReportedAmbiguousConversions = true;
10255 }
John McCalld3224162010-01-08 00:58:21 +000010256
John McCall0d1da222010-01-12 00:44:57 +000010257 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +000010258 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +000010259 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +000010260 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010261
10262 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +000010263 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +000010264}
10265
Larisse Voufo98b20f12013-07-19 23:00:19 +000010266static SourceLocation
10267GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
10268 return Cand->Specialization ? Cand->Specialization->getLocation()
10269 : SourceLocation();
10270}
10271
Richard Smith17c00b42014-11-12 01:24:00 +000010272namespace {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010273struct CompareTemplateSpecCandidatesForDisplay {
10274 Sema &S;
10275 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
10276
10277 bool operator()(const TemplateSpecCandidate *L,
10278 const TemplateSpecCandidate *R) {
10279 // Fast-path this check.
10280 if (L == R)
10281 return false;
10282
10283 // Assuming that both candidates are not matches...
10284
10285 // Sort by the ranking of deduction failures.
10286 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10287 return RankDeductionFailure(L->DeductionFailure) <
10288 RankDeductionFailure(R->DeductionFailure);
10289
10290 // Sort everything else by location.
10291 SourceLocation LLoc = GetLocationForCandidate(L);
10292 SourceLocation RLoc = GetLocationForCandidate(R);
10293
10294 // Put candidates without locations (e.g. builtins) at the end.
10295 if (LLoc.isInvalid())
10296 return false;
10297 if (RLoc.isInvalid())
10298 return true;
10299
10300 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10301 }
10302};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010303}
Larisse Voufo98b20f12013-07-19 23:00:19 +000010304
10305/// Diagnose a template argument deduction failure.
10306/// We are treating these failures as overload failures due to bad
10307/// deductions.
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010308void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
10309 bool ForTakingAddress) {
Richard Smithc2bebe92016-05-11 20:37:46 +000010310 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010311 DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010312}
10313
10314void TemplateSpecCandidateSet::destroyCandidates() {
10315 for (iterator i = begin(), e = end(); i != e; ++i) {
10316 i->DeductionFailure.Destroy();
10317 }
10318}
10319
10320void TemplateSpecCandidateSet::clear() {
10321 destroyCandidates();
10322 Candidates.clear();
10323}
10324
10325/// NoteCandidates - When no template specialization match is found, prints
10326/// diagnostic messages containing the non-matching specializations that form
10327/// the candidate set.
10328/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
10329/// OCD == OCD_AllCandidates and Cand->Viable == false.
10330void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
10331 // Sort the candidates by position (assuming no candidate is a match).
10332 // Sorting directly would be prohibitive, so we make a set of pointers
10333 // and sort those.
10334 SmallVector<TemplateSpecCandidate *, 32> Cands;
10335 Cands.reserve(size());
10336 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10337 if (Cand->Specialization)
10338 Cands.push_back(Cand);
Alp Tokerd4733632013-12-05 04:47:09 +000010339 // Otherwise, this is a non-matching builtin candidate. We do not,
Larisse Voufo98b20f12013-07-19 23:00:19 +000010340 // in general, want to list every possible builtin candidate.
10341 }
10342
10343 std::sort(Cands.begin(), Cands.end(),
10344 CompareTemplateSpecCandidatesForDisplay(S));
10345
10346 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
10347 // for generalization purposes (?).
10348 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10349
10350 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
10351 unsigned CandsShown = 0;
10352 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10353 TemplateSpecCandidate *Cand = *I;
10354
10355 // Set an arbitrary limit on the number of candidates we'll spam
10356 // the user with. FIXME: This limit should depend on details of the
10357 // candidate list.
10358 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10359 break;
10360 ++CandsShown;
10361
10362 assert(Cand->Specialization &&
10363 "Non-matching built-in candidates are not added to Cands.");
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010364 Cand->NoteDeductionFailure(S, ForTakingAddress);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010365 }
10366
10367 if (I != E)
10368 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
10369}
10370
Douglas Gregorb491ed32011-02-19 21:32:49 +000010371// [PossiblyAFunctionType] --> [Return]
10372// NonFunctionType --> NonFunctionType
10373// R (A) --> R(A)
10374// R (*)(A) --> R (A)
10375// R (&)(A) --> R (A)
10376// R (S::*)(A) --> R (A)
10377QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
10378 QualType Ret = PossiblyAFunctionType;
10379 if (const PointerType *ToTypePtr =
10380 PossiblyAFunctionType->getAs<PointerType>())
10381 Ret = ToTypePtr->getPointeeType();
10382 else if (const ReferenceType *ToTypeRef =
10383 PossiblyAFunctionType->getAs<ReferenceType>())
10384 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +000010385 else if (const MemberPointerType *MemTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +000010386 PossiblyAFunctionType->getAs<MemberPointerType>())
10387 Ret = MemTypePtr->getPointeeType();
10388 Ret =
10389 Context.getCanonicalType(Ret).getUnqualifiedType();
10390 return Ret;
10391}
Douglas Gregorcd695e52008-11-10 20:40:00 +000010392
Richard Smith9095e5b2016-11-01 01:31:23 +000010393static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
10394 bool Complain = true) {
10395 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
10396 S.DeduceReturnType(FD, Loc, Complain))
10397 return true;
10398
10399 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
10400 if (S.getLangOpts().CPlusPlus1z &&
10401 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
10402 !S.ResolveExceptionSpec(Loc, FPT))
10403 return true;
10404
10405 return false;
10406}
10407
Richard Smith17c00b42014-11-12 01:24:00 +000010408namespace {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010409// A helper class to help with address of function resolution
10410// - allows us to avoid passing around all those ugly parameters
Richard Smith17c00b42014-11-12 01:24:00 +000010411class AddressOfFunctionResolver {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010412 Sema& S;
10413 Expr* SourceExpr;
10414 const QualType& TargetType;
10415 QualType TargetFunctionType; // Extracted function type from target type
10416
10417 bool Complain;
10418 //DeclAccessPair& ResultFunctionAccessPair;
10419 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010420
Douglas Gregorb491ed32011-02-19 21:32:49 +000010421 bool TargetTypeIsNonStaticMemberFunction;
10422 bool FoundNonTemplateFunction;
David Majnemera4f7c7a2013-08-01 06:13:59 +000010423 bool StaticMemberFunctionFromBoundPointer;
George Burgess IV5f2ef452015-10-12 18:40:58 +000010424 bool HasComplained;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010425
Douglas Gregorb491ed32011-02-19 21:32:49 +000010426 OverloadExpr::FindResult OvlExprInfo;
10427 OverloadExpr *OvlExpr;
10428 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010429 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Larisse Voufo98b20f12013-07-19 23:00:19 +000010430 TemplateSpecCandidateSet FailedCandidates;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010431
Douglas Gregorb491ed32011-02-19 21:32:49 +000010432public:
Larisse Voufo98b20f12013-07-19 23:00:19 +000010433 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
10434 const QualType &TargetType, bool Complain)
10435 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
10436 Complain(Complain), Context(S.getASTContext()),
10437 TargetTypeIsNonStaticMemberFunction(
10438 !!TargetType->getAs<MemberPointerType>()),
10439 FoundNonTemplateFunction(false),
David Majnemera4f7c7a2013-08-01 06:13:59 +000010440 StaticMemberFunctionFromBoundPointer(false),
George Burgess IV5f2ef452015-10-12 18:40:58 +000010441 HasComplained(false),
Larisse Voufo98b20f12013-07-19 23:00:19 +000010442 OvlExprInfo(OverloadExpr::find(SourceExpr)),
10443 OvlExpr(OvlExprInfo.Expression),
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010444 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010445 ExtractUnqualifiedFunctionTypeFromTargetType();
Chandler Carruthffce2452011-03-29 08:08:18 +000010446
David Majnemera4f7c7a2013-08-01 06:13:59 +000010447 if (TargetFunctionType->isFunctionType()) {
10448 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
10449 if (!UME->isImplicitAccess() &&
10450 !S.ResolveSingleFunctionTemplateSpecialization(UME))
10451 StaticMemberFunctionFromBoundPointer = true;
10452 } else if (OvlExpr->hasExplicitTemplateArgs()) {
10453 DeclAccessPair dap;
10454 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
10455 OvlExpr, false, &dap)) {
10456 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
10457 if (!Method->isStatic()) {
10458 // If the target type is a non-function type and the function found
10459 // is a non-static member function, pretend as if that was the
10460 // target, it's the only possible type to end up with.
10461 TargetTypeIsNonStaticMemberFunction = true;
Chandler Carruthffce2452011-03-29 08:08:18 +000010462
David Majnemera4f7c7a2013-08-01 06:13:59 +000010463 // And skip adding the function if its not in the proper form.
10464 // We'll diagnose this due to an empty set of functions.
10465 if (!OvlExprInfo.HasFormOfMemberPointer)
10466 return;
Chandler Carruthffce2452011-03-29 08:08:18 +000010467 }
10468
David Majnemera4f7c7a2013-08-01 06:13:59 +000010469 Matches.push_back(std::make_pair(dap, Fn));
Douglas Gregor9b146582009-07-08 20:55:45 +000010470 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010471 return;
Douglas Gregor9b146582009-07-08 20:55:45 +000010472 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010473
10474 if (OvlExpr->hasExplicitTemplateArgs())
James Y Knight04ec5bf2015-12-24 02:59:37 +000010475 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +000010476
Douglas Gregorb491ed32011-02-19 21:32:49 +000010477 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
10478 // C++ [over.over]p4:
10479 // If more than one function is selected, [...]
George Burgess IV2a6150d2015-10-16 01:17:38 +000010480 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010481 if (FoundNonTemplateFunction)
10482 EliminateAllTemplateMatches();
10483 else
10484 EliminateAllExceptMostSpecializedTemplate();
10485 }
10486 }
Artem Belevich94a55e82015-09-22 17:22:59 +000010487
Justin Lebar25c4a812016-03-29 16:24:16 +000010488 if (S.getLangOpts().CUDA && Matches.size() > 1)
Artem Belevich94a55e82015-09-22 17:22:59 +000010489 EliminateSuboptimalCudaMatches();
Douglas Gregorb491ed32011-02-19 21:32:49 +000010490 }
George Burgess IV5f2ef452015-10-12 18:40:58 +000010491
10492 bool hasComplained() const { return HasComplained; }
10493
Douglas Gregorb491ed32011-02-19 21:32:49 +000010494private:
George Burgess IV6da4c202016-03-23 02:33:58 +000010495 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
10496 QualType Discard;
10497 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
Richard Smith3c4f8d22016-10-16 17:54:23 +000010498 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
George Burgess IV2a6150d2015-10-16 01:17:38 +000010499 }
10500
George Burgess IV6da4c202016-03-23 02:33:58 +000010501 /// \return true if A is considered a better overload candidate for the
10502 /// desired type than B.
10503 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
10504 // If A doesn't have exactly the correct type, we don't want to classify it
10505 // as "better" than anything else. This way, the user is required to
10506 // disambiguate for us if there are multiple candidates and no exact match.
10507 return candidateHasExactlyCorrectType(A) &&
10508 (!candidateHasExactlyCorrectType(B) ||
George Burgess IV3dc166912016-05-10 01:59:34 +000010509 compareEnableIfAttrs(S, A, B) == Comparison::Better);
George Burgess IV6da4c202016-03-23 02:33:58 +000010510 }
10511
10512 /// \return true if we were able to eliminate all but one overload candidate,
10513 /// false otherwise.
George Burgess IV2a6150d2015-10-16 01:17:38 +000010514 bool eliminiateSuboptimalOverloadCandidates() {
10515 // Same algorithm as overload resolution -- one pass to pick the "best",
10516 // another pass to be sure that nothing is better than the best.
10517 auto Best = Matches.begin();
10518 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
10519 if (isBetterCandidate(I->second, Best->second))
10520 Best = I;
10521
10522 const FunctionDecl *BestFn = Best->second;
10523 auto IsBestOrInferiorToBest = [this, BestFn](
10524 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
10525 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
10526 };
10527
10528 // Note: We explicitly leave Matches unmodified if there isn't a clear best
10529 // option, so we can potentially give the user a better error
10530 if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest))
10531 return false;
10532 Matches[0] = *Best;
10533 Matches.resize(1);
10534 return true;
10535 }
10536
Douglas Gregorb491ed32011-02-19 21:32:49 +000010537 bool isTargetTypeAFunction() const {
10538 return TargetFunctionType->isFunctionType();
10539 }
10540
10541 // [ToType] [Return]
10542
10543 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
10544 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
10545 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
10546 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
10547 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
10548 }
10549
10550 // return true if any matching specializations were found
10551 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
10552 const DeclAccessPair& CurAccessFunPair) {
10553 if (CXXMethodDecl *Method
10554 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
10555 // Skip non-static function templates when converting to pointer, and
10556 // static when converting to member pointer.
10557 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10558 return false;
10559 }
10560 else if (TargetTypeIsNonStaticMemberFunction)
10561 return false;
10562
10563 // C++ [over.over]p2:
10564 // If the name is a function template, template argument deduction is
10565 // done (14.8.2.2), and if the argument deduction succeeds, the
10566 // resulting template argument list is used to generate a single
10567 // function template specialization, which is added to the set of
10568 // overloaded functions considered.
Craig Topperc3ec1492014-05-26 06:22:03 +000010569 FunctionDecl *Specialization = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +000010570 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregorb491ed32011-02-19 21:32:49 +000010571 if (Sema::TemplateDeductionResult Result
10572 = S.DeduceTemplateArguments(FunctionTemplate,
10573 &OvlExplicitTemplateArgs,
10574 TargetFunctionType, Specialization,
Douglas Gregor19a41f12013-04-17 08:45:07 +000010575 Info, /*InOverloadResolution=*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010576 // Make a note of the failed deduction for diagnostics.
10577 FailedCandidates.addCandidate()
Richard Smithc2bebe92016-05-11 20:37:46 +000010578 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
Larisse Voufo98b20f12013-07-19 23:00:19 +000010579 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregorb491ed32011-02-19 21:32:49 +000010580 return false;
10581 }
10582
Douglas Gregor19a41f12013-04-17 08:45:07 +000010583 // Template argument deduction ensures that we have an exact match or
10584 // compatible pointer-to-function arguments that would be adjusted by ICS.
Douglas Gregorb491ed32011-02-19 21:32:49 +000010585 // This function template specicalization works.
Douglas Gregor19a41f12013-04-17 08:45:07 +000010586 assert(S.isSameOrCompatibleFunctionType(
10587 Context.getCanonicalType(Specialization->getType()),
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010588 Context.getCanonicalType(TargetFunctionType)));
George Burgess IV5f21c712015-10-12 19:57:04 +000010589
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010590 if (!S.checkAddressOfFunctionIsAvailable(Specialization))
George Burgess IV5f21c712015-10-12 19:57:04 +000010591 return false;
10592
Douglas Gregorb491ed32011-02-19 21:32:49 +000010593 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
10594 return true;
10595 }
10596
10597 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
10598 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +000010599 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +000010600 // Skip non-static functions when converting to pointer, and static
10601 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +000010602 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10603 return false;
10604 }
10605 else if (TargetTypeIsNonStaticMemberFunction)
10606 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010607
Chandler Carruthc25c6ee2009-12-29 06:17:27 +000010608 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000010609 if (S.getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010610 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
Justin Lebarb0080032016-08-10 01:09:11 +000010611 if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010612 return false;
10613
Richard Smith2a7d4812013-05-04 07:00:32 +000010614 // If any candidate has a placeholder return type, trigger its deduction
10615 // now.
Richard Smith9095e5b2016-11-01 01:31:23 +000010616 if (completeFunctionType(S, FunDecl, SourceExpr->getLocStart(),
10617 Complain)) {
George Burgess IV5f2ef452015-10-12 18:40:58 +000010618 HasComplained |= Complain;
Richard Smith2a7d4812013-05-04 07:00:32 +000010619 return false;
George Burgess IV5f2ef452015-10-12 18:40:58 +000010620 }
Richard Smith2a7d4812013-05-04 07:00:32 +000010621
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010622 if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
George Burgess IV5f21c712015-10-12 19:57:04 +000010623 return false;
10624
George Burgess IV6da4c202016-03-23 02:33:58 +000010625 // If we're in C, we need to support types that aren't exactly identical.
10626 if (!S.getLangOpts().CPlusPlus ||
10627 candidateHasExactlyCorrectType(FunDecl)) {
George Burgess IV5f21c712015-10-12 19:57:04 +000010628 Matches.push_back(std::make_pair(
10629 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +000010630 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010631 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +000010632 }
Mike Stump11289f42009-09-09 15:08:12 +000010633 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010634
10635 return false;
10636 }
10637
10638 bool FindAllFunctionsThatMatchTargetTypeExactly() {
10639 bool Ret = false;
10640
10641 // If the overload expression doesn't have the form of a pointer to
10642 // member, don't try to convert it to a pointer-to-member type.
10643 if (IsInvalidFormOfPointerToMemberFunction())
10644 return false;
10645
10646 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10647 E = OvlExpr->decls_end();
10648 I != E; ++I) {
10649 // Look through any using declarations to find the underlying function.
10650 NamedDecl *Fn = (*I)->getUnderlyingDecl();
10651
10652 // C++ [over.over]p3:
10653 // Non-member functions and static member functions match
10654 // targets of type "pointer-to-function" or "reference-to-function."
10655 // Nonstatic member functions match targets of
10656 // type "pointer-to-member-function."
10657 // Note that according to DR 247, the containing class does not matter.
10658 if (FunctionTemplateDecl *FunctionTemplate
10659 = dyn_cast<FunctionTemplateDecl>(Fn)) {
10660 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
10661 Ret = true;
10662 }
10663 // If we have explicit template arguments supplied, skip non-templates.
10664 else if (!OvlExpr->hasExplicitTemplateArgs() &&
10665 AddMatchingNonTemplateFunction(Fn, I.getPair()))
10666 Ret = true;
10667 }
10668 assert(Ret || Matches.empty());
10669 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010670 }
10671
Douglas Gregorb491ed32011-02-19 21:32:49 +000010672 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +000010673 // [...] and any given function template specialization F1 is
10674 // eliminated if the set contains a second function template
10675 // specialization whose function template is more specialized
10676 // than the function template of F1 according to the partial
10677 // ordering rules of 14.5.5.2.
10678
10679 // The algorithm specified above is quadratic. We instead use a
10680 // two-pass algorithm (similar to the one used to identify the
10681 // best viable function in an overload set) that identifies the
10682 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +000010683
10684 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
10685 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
10686 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010687
Larisse Voufo98b20f12013-07-19 23:00:19 +000010688 // TODO: It looks like FailedCandidates does not serve much purpose
10689 // here, since the no_viable diagnostic has index 0.
10690 UnresolvedSetIterator Result = S.getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +000010691 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +000010692 SourceExpr->getLocStart(), S.PDiag(),
Richard Smith5179eb72016-06-28 19:03:57 +000010693 S.PDiag(diag::err_addr_ovl_ambiguous)
10694 << Matches[0].second->getDeclName(),
10695 S.PDiag(diag::note_ovl_candidate)
10696 << (unsigned)oc_function_template,
Larisse Voufo98b20f12013-07-19 23:00:19 +000010697 Complain, TargetFunctionType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010698
Douglas Gregorb491ed32011-02-19 21:32:49 +000010699 if (Result != MatchesCopy.end()) {
10700 // Make it the first and only element
10701 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
10702 Matches[0].second = cast<FunctionDecl>(*Result);
10703 Matches.resize(1);
George Burgess IV5f2ef452015-10-12 18:40:58 +000010704 } else
10705 HasComplained |= Complain;
John McCall58cc69d2010-01-27 01:50:18 +000010706 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010707
Douglas Gregorb491ed32011-02-19 21:32:49 +000010708 void EliminateAllTemplateMatches() {
10709 // [...] any function template specializations in the set are
10710 // eliminated if the set also contains a non-template function, [...]
10711 for (unsigned I = 0, N = Matches.size(); I != N; ) {
Craig Topperc3ec1492014-05-26 06:22:03 +000010712 if (Matches[I].second->getPrimaryTemplate() == nullptr)
Douglas Gregorb491ed32011-02-19 21:32:49 +000010713 ++I;
10714 else {
10715 Matches[I] = Matches[--N];
Artem Belevich94a55e82015-09-22 17:22:59 +000010716 Matches.resize(N);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010717 }
10718 }
10719 }
10720
Artem Belevich94a55e82015-09-22 17:22:59 +000010721 void EliminateSuboptimalCudaMatches() {
10722 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
10723 }
10724
Douglas Gregorb491ed32011-02-19 21:32:49 +000010725public:
10726 void ComplainNoMatchesFound() const {
10727 assert(Matches.empty());
10728 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
10729 << OvlExpr->getName() << TargetFunctionType
10730 << OvlExpr->getSourceRange();
Richard Smith0d905472013-08-14 00:00:44 +000010731 if (FailedCandidates.empty())
George Burgess IV5f21c712015-10-12 19:57:04 +000010732 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
10733 /*TakingAddress=*/true);
Richard Smith0d905472013-08-14 00:00:44 +000010734 else {
10735 // We have some deduction failure messages. Use them to diagnose
10736 // the function templates, and diagnose the non-template candidates
10737 // normally.
10738 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10739 IEnd = OvlExpr->decls_end();
10740 I != IEnd; ++I)
10741 if (FunctionDecl *Fun =
10742 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010743 if (!functionHasPassObjectSizeParams(Fun))
Richard Smithc2bebe92016-05-11 20:37:46 +000010744 S.NoteOverloadCandidate(*I, Fun, TargetFunctionType,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010745 /*TakingAddress=*/true);
Richard Smith0d905472013-08-14 00:00:44 +000010746 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
10747 }
10748 }
10749
Douglas Gregorb491ed32011-02-19 21:32:49 +000010750 bool IsInvalidFormOfPointerToMemberFunction() const {
10751 return TargetTypeIsNonStaticMemberFunction &&
10752 !OvlExprInfo.HasFormOfMemberPointer;
10753 }
David Majnemera4f7c7a2013-08-01 06:13:59 +000010754
Douglas Gregorb491ed32011-02-19 21:32:49 +000010755 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
10756 // TODO: Should we condition this on whether any functions might
10757 // have matched, or is it more appropriate to do that in callers?
10758 // TODO: a fixit wouldn't hurt.
10759 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
10760 << TargetType << OvlExpr->getSourceRange();
10761 }
David Majnemera4f7c7a2013-08-01 06:13:59 +000010762
10763 bool IsStaticMemberFunctionFromBoundPointer() const {
10764 return StaticMemberFunctionFromBoundPointer;
10765 }
10766
10767 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
10768 S.Diag(OvlExpr->getLocStart(),
10769 diag::err_invalid_form_pointer_member_function)
10770 << OvlExpr->getSourceRange();
10771 }
10772
Douglas Gregorb491ed32011-02-19 21:32:49 +000010773 void ComplainOfInvalidConversion() const {
10774 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
10775 << OvlExpr->getName() << TargetType;
10776 }
10777
10778 void ComplainMultipleMatchesFound() const {
10779 assert(Matches.size() > 1);
10780 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
10781 << OvlExpr->getName()
10782 << OvlExpr->getSourceRange();
George Burgess IV5f21c712015-10-12 19:57:04 +000010783 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
10784 /*TakingAddress=*/true);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010785 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010786
10787 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
10788
Douglas Gregorb491ed32011-02-19 21:32:49 +000010789 int getNumMatches() const { return Matches.size(); }
10790
10791 FunctionDecl* getMatchingFunctionDecl() const {
Craig Topperc3ec1492014-05-26 06:22:03 +000010792 if (Matches.size() != 1) return nullptr;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010793 return Matches[0].second;
10794 }
10795
10796 const DeclAccessPair* getMatchingFunctionAccessPair() const {
Craig Topperc3ec1492014-05-26 06:22:03 +000010797 if (Matches.size() != 1) return nullptr;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010798 return &Matches[0].first;
10799 }
10800};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010801}
Richard Smith17c00b42014-11-12 01:24:00 +000010802
Douglas Gregorb491ed32011-02-19 21:32:49 +000010803/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
10804/// an overloaded function (C++ [over.over]), where @p From is an
10805/// expression with overloaded function type and @p ToType is the type
10806/// we're trying to resolve to. For example:
10807///
10808/// @code
10809/// int f(double);
10810/// int f(int);
10811///
10812/// int (*pfd)(double) = f; // selects f(double)
10813/// @endcode
10814///
10815/// This routine returns the resulting FunctionDecl if it could be
10816/// resolved, and NULL otherwise. When @p Complain is true, this
10817/// routine will emit diagnostics if there is an error.
10818FunctionDecl *
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010819Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
10820 QualType TargetType,
10821 bool Complain,
10822 DeclAccessPair &FoundResult,
10823 bool *pHadMultipleCandidates) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010824 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010825
10826 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
10827 Complain);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010828 int NumMatches = Resolver.getNumMatches();
Craig Topperc3ec1492014-05-26 06:22:03 +000010829 FunctionDecl *Fn = nullptr;
George Burgess IV5f2ef452015-10-12 18:40:58 +000010830 bool ShouldComplain = Complain && !Resolver.hasComplained();
10831 if (NumMatches == 0 && ShouldComplain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010832 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
10833 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
10834 else
10835 Resolver.ComplainNoMatchesFound();
10836 }
George Burgess IV5f2ef452015-10-12 18:40:58 +000010837 else if (NumMatches > 1 && ShouldComplain)
Douglas Gregorb491ed32011-02-19 21:32:49 +000010838 Resolver.ComplainMultipleMatchesFound();
10839 else if (NumMatches == 1) {
10840 Fn = Resolver.getMatchingFunctionDecl();
10841 assert(Fn);
Richard Smith9095e5b2016-11-01 01:31:23 +000010842 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
10843 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010844 FoundResult = *Resolver.getMatchingFunctionAccessPair();
David Majnemera4f7c7a2013-08-01 06:13:59 +000010845 if (Complain) {
10846 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
10847 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
10848 else
10849 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
10850 }
Sebastian Redldf4b80e2009-10-17 21:12:09 +000010851 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010852
10853 if (pHadMultipleCandidates)
10854 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregorb491ed32011-02-19 21:32:49 +000010855 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010856}
10857
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010858/// \brief Given an expression that refers to an overloaded function, try to
George Burgess IV3cde9bf2016-03-19 21:36:10 +000010859/// resolve that function to a single function that can have its address taken.
10860/// This will modify `Pair` iff it returns non-null.
10861///
10862/// This routine can only realistically succeed if all but one candidates in the
10863/// overload set for SrcExpr cannot have their addresses taken.
10864FunctionDecl *
10865Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
10866 DeclAccessPair &Pair) {
10867 OverloadExpr::FindResult R = OverloadExpr::find(E);
10868 OverloadExpr *Ovl = R.Expression;
10869 FunctionDecl *Result = nullptr;
10870 DeclAccessPair DAP;
10871 // Don't use the AddressOfResolver because we're specifically looking for
10872 // cases where we have one overload candidate that lacks
10873 // enable_if/pass_object_size/...
10874 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
10875 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
10876 if (!FD)
10877 return nullptr;
10878
10879 if (!checkAddressOfFunctionIsAvailable(FD))
10880 continue;
10881
10882 // We have more than one result; quit.
10883 if (Result)
10884 return nullptr;
10885 DAP = I.getPair();
10886 Result = FD;
10887 }
10888
10889 if (Result)
10890 Pair = DAP;
10891 return Result;
10892}
10893
George Burgess IVbeca4a32016-06-08 00:34:22 +000010894/// \brief Given an overloaded function, tries to turn it into a non-overloaded
10895/// function reference using resolveAddressOfOnlyViableOverloadCandidate. This
10896/// will perform access checks, diagnose the use of the resultant decl, and, if
10897/// necessary, perform a function-to-pointer decay.
10898///
10899/// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails.
10900/// Otherwise, returns true. This may emit diagnostics and return true.
10901bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate(
10902 ExprResult &SrcExpr) {
10903 Expr *E = SrcExpr.get();
10904 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
10905
10906 DeclAccessPair DAP;
10907 FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP);
10908 if (!Found)
10909 return false;
10910
10911 // Emitting multiple diagnostics for a function that is both inaccessible and
10912 // unavailable is consistent with our behavior elsewhere. So, always check
10913 // for both.
10914 DiagnoseUseOfDecl(Found, E->getExprLoc());
10915 CheckAddressOfMemberAccess(E, DAP);
10916 Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
10917 if (Fixed->getType()->isFunctionType())
10918 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
10919 else
10920 SrcExpr = Fixed;
10921 return true;
10922}
10923
George Burgess IV3cde9bf2016-03-19 21:36:10 +000010924/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010925/// resolve that overloaded function expression down to a single function.
10926///
10927/// This routine can only resolve template-ids that refer to a single function
10928/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010929/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010930/// as described in C++0x [temp.arg.explicit]p3.
Alp Toker67b47ac2013-10-20 18:48:56 +000010931///
10932/// If no template-ids are found, no diagnostics are emitted and NULL is
10933/// returned.
John McCall0009fcc2011-04-26 20:42:42 +000010934FunctionDecl *
10935Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
10936 bool Complain,
10937 DeclAccessPair *FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010938 // C++ [over.over]p1:
10939 // [...] [Note: any redundant set of parentheses surrounding the
10940 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010941 // C++ [over.over]p1:
10942 // [...] The overloaded function name can be preceded by the &
10943 // operator.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010944
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010945 // If we didn't actually find any template-ids, we're done.
John McCall0009fcc2011-04-26 20:42:42 +000010946 if (!ovl->hasExplicitTemplateArgs())
Craig Topperc3ec1492014-05-26 06:22:03 +000010947 return nullptr;
John McCall1acbbb52010-02-02 06:20:04 +000010948
10949 TemplateArgumentListInfo ExplicitTemplateArgs;
James Y Knight04ec5bf2015-12-24 02:59:37 +000010950 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010951 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010952
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010953 // Look through all of the overloaded functions, searching for one
10954 // whose type matches exactly.
Craig Topperc3ec1492014-05-26 06:22:03 +000010955 FunctionDecl *Matched = nullptr;
John McCall0009fcc2011-04-26 20:42:42 +000010956 for (UnresolvedSetIterator I = ovl->decls_begin(),
10957 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010958 // C++0x [temp.arg.explicit]p3:
10959 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010960 // where deduction is not done, if a template argument list is
10961 // specified and it, along with any default template arguments,
10962 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010963 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +000010964 FunctionTemplateDecl *FunctionTemplate
10965 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010966
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010967 // C++ [over.over]p2:
10968 // If the name is a function template, template argument deduction is
10969 // done (14.8.2.2), and if the argument deduction succeeds, the
10970 // resulting template argument list is used to generate a single
10971 // function template specialization, which is added to the set of
10972 // overloaded functions considered.
Craig Topperc3ec1492014-05-26 06:22:03 +000010973 FunctionDecl *Specialization = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +000010974 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010975 if (TemplateDeductionResult Result
10976 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
Douglas Gregor19a41f12013-04-17 08:45:07 +000010977 Specialization, Info,
10978 /*InOverloadResolution=*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010979 // Make a note of the failed deduction for diagnostics.
10980 // TODO: Actually use the failed-deduction info?
10981 FailedCandidates.addCandidate()
Richard Smithc2bebe92016-05-11 20:37:46 +000010982 .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
Larisse Voufo98b20f12013-07-19 23:00:19 +000010983 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010984 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010985 }
10986
John McCall0009fcc2011-04-26 20:42:42 +000010987 assert(Specialization && "no specialization and no error?");
10988
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010989 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +000010990 if (Matched) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010991 if (Complain) {
John McCall0009fcc2011-04-26 20:42:42 +000010992 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
10993 << ovl->getName();
10994 NoteAllOverloadCandidates(ovl);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010995 }
Craig Topperc3ec1492014-05-26 06:22:03 +000010996 return nullptr;
John McCall0009fcc2011-04-26 20:42:42 +000010997 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010998
John McCall0009fcc2011-04-26 20:42:42 +000010999 Matched = Specialization;
11000 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011001 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011002
Richard Smith9095e5b2016-11-01 01:31:23 +000011003 if (Matched &&
11004 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
Craig Topperc3ec1492014-05-26 06:22:03 +000011005 return nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +000011006
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011007 return Matched;
11008}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011009
Douglas Gregor1beec452011-03-12 01:48:56 +000011010
11011
11012
John McCall50a2c2c2011-10-11 23:14:30 +000011013// Resolve and fix an overloaded expression that can be resolved
11014// because it identifies a single function template specialization.
11015//
Douglas Gregor1beec452011-03-12 01:48:56 +000011016// Last three arguments should only be supplied if Complain = true
John McCall50a2c2c2011-10-11 23:14:30 +000011017//
11018// Return true if it was logically possible to so resolve the
11019// expression, regardless of whether or not it succeeded. Always
11020// returns true if 'complain' is set.
11021bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
11022 ExprResult &SrcExpr, bool doFunctionPointerConverion,
Craig Toppere335f252015-10-04 04:53:55 +000011023 bool complain, SourceRange OpRangeForComplaining,
Douglas Gregor1beec452011-03-12 01:48:56 +000011024 QualType DestTypeForComplaining,
John McCall0009fcc2011-04-26 20:42:42 +000011025 unsigned DiagIDForComplaining) {
John McCall50a2c2c2011-10-11 23:14:30 +000011026 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregor1beec452011-03-12 01:48:56 +000011027
John McCall50a2c2c2011-10-11 23:14:30 +000011028 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregor1beec452011-03-12 01:48:56 +000011029
John McCall0009fcc2011-04-26 20:42:42 +000011030 DeclAccessPair found;
11031 ExprResult SingleFunctionExpression;
11032 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
11033 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011034 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall50a2c2c2011-10-11 23:14:30 +000011035 SrcExpr = ExprError();
11036 return true;
11037 }
John McCall0009fcc2011-04-26 20:42:42 +000011038
11039 // It is only correct to resolve to an instance method if we're
11040 // resolving a form that's permitted to be a pointer to member.
11041 // Otherwise we'll end up making a bound member expression, which
11042 // is illegal in all the contexts we resolve like this.
11043 if (!ovl.HasFormOfMemberPointer &&
11044 isa<CXXMethodDecl>(fn) &&
11045 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall50a2c2c2011-10-11 23:14:30 +000011046 if (!complain) return false;
11047
11048 Diag(ovl.Expression->getExprLoc(),
11049 diag::err_bound_member_function)
11050 << 0 << ovl.Expression->getSourceRange();
11051
11052 // TODO: I believe we only end up here if there's a mix of
11053 // static and non-static candidates (otherwise the expression
11054 // would have 'bound member' type, not 'overload' type).
11055 // Ideally we would note which candidate was chosen and why
11056 // the static candidates were rejected.
11057 SrcExpr = ExprError();
11058 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000011059 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +000011060
Sylvestre Ledrua5202662012-07-31 06:56:50 +000011061 // Fix the expression to refer to 'fn'.
John McCall0009fcc2011-04-26 20:42:42 +000011062 SingleFunctionExpression =
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011063 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
John McCall0009fcc2011-04-26 20:42:42 +000011064
11065 // If desired, do function-to-pointer decay.
John McCall50a2c2c2011-10-11 23:14:30 +000011066 if (doFunctionPointerConverion) {
John McCall0009fcc2011-04-26 20:42:42 +000011067 SingleFunctionExpression =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011068 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
John McCall50a2c2c2011-10-11 23:14:30 +000011069 if (SingleFunctionExpression.isInvalid()) {
11070 SrcExpr = ExprError();
11071 return true;
11072 }
11073 }
John McCall0009fcc2011-04-26 20:42:42 +000011074 }
11075
11076 if (!SingleFunctionExpression.isUsable()) {
11077 if (complain) {
11078 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
11079 << ovl.Expression->getName()
11080 << DestTypeForComplaining
11081 << OpRangeForComplaining
11082 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall50a2c2c2011-10-11 23:14:30 +000011083 NoteAllOverloadCandidates(SrcExpr.get());
11084
11085 SrcExpr = ExprError();
11086 return true;
11087 }
11088
11089 return false;
John McCall0009fcc2011-04-26 20:42:42 +000011090 }
11091
John McCall50a2c2c2011-10-11 23:14:30 +000011092 SrcExpr = SingleFunctionExpression;
11093 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000011094}
11095
Douglas Gregorcabea402009-09-22 15:41:20 +000011096/// \brief Add a single candidate to the overload set.
11097static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +000011098 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +000011099 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011100 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000011101 OverloadCandidateSet &CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +000011102 bool PartialOverloading,
11103 bool KnownValid) {
John McCalla0296f72010-03-19 07:35:19 +000011104 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +000011105 if (isa<UsingShadowDecl>(Callee))
11106 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
11107
Douglas Gregorcabea402009-09-22 15:41:20 +000011108 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith95ce4f62011-06-26 22:19:54 +000011109 if (ExplicitTemplateArgs) {
11110 assert(!KnownValid && "Explicit template arguments?");
11111 return;
11112 }
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011113 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
11114 /*SuppressUsedConversions=*/false,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011115 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000011116 return;
John McCalld14a8642009-11-21 08:51:07 +000011117 }
11118
11119 if (FunctionTemplateDecl *FuncTemplate
11120 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +000011121 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011122 ExplicitTemplateArgs, Args, CandidateSet,
11123 /*SuppressUsedConversions=*/false,
11124 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +000011125 return;
11126 }
11127
Richard Smith95ce4f62011-06-26 22:19:54 +000011128 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregorcabea402009-09-22 15:41:20 +000011129}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011130
Douglas Gregorcabea402009-09-22 15:41:20 +000011131/// \brief Add the overload candidates named by callee and/or found by argument
11132/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +000011133void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011134 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000011135 OverloadCandidateSet &CandidateSet,
11136 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +000011137
11138#ifndef NDEBUG
11139 // Verify that ArgumentDependentLookup is consistent with the rules
11140 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +000011141 //
Douglas Gregorcabea402009-09-22 15:41:20 +000011142 // Let X be the lookup set produced by unqualified lookup (3.4.1)
11143 // and let Y be the lookup set produced by argument dependent
11144 // lookup (defined as follows). If X contains
11145 //
11146 // -- a declaration of a class member, or
11147 //
11148 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +000011149 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +000011150 //
11151 // -- a declaration that is neither a function or a function
11152 // template
11153 //
11154 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +000011155
John McCall57500772009-12-16 12:17:52 +000011156 if (ULE->requiresADL()) {
11157 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11158 E = ULE->decls_end(); I != E; ++I) {
11159 assert(!(*I)->getDeclContext()->isRecord());
11160 assert(isa<UsingShadowDecl>(*I) ||
11161 !(*I)->getDeclContext()->isFunctionOrMethod());
11162 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +000011163 }
11164 }
11165#endif
11166
John McCall57500772009-12-16 12:17:52 +000011167 // It would be nice to avoid this copy.
11168 TemplateArgumentListInfo TABuffer;
Craig Topperc3ec1492014-05-26 06:22:03 +000011169 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
John McCall57500772009-12-16 12:17:52 +000011170 if (ULE->hasExplicitTemplateArgs()) {
11171 ULE->copyTemplateArgumentsInto(TABuffer);
11172 ExplicitTemplateArgs = &TABuffer;
11173 }
11174
11175 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11176 E = ULE->decls_end(); I != E; ++I)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011177 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
11178 CandidateSet, PartialOverloading,
11179 /*KnownValid*/ true);
John McCalld14a8642009-11-21 08:51:07 +000011180
John McCall57500772009-12-16 12:17:52 +000011181 if (ULE->requiresADL())
Richard Smith100b24a2014-04-17 01:52:14 +000011182 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011183 Args, ExplicitTemplateArgs,
Richard Smithb6626742012-10-18 17:56:02 +000011184 CandidateSet, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000011185}
John McCalld681c392009-12-16 08:11:27 +000011186
Richard Smith0603bbb2013-06-12 22:56:54 +000011187/// Determine whether a declaration with the specified name could be moved into
11188/// a different namespace.
11189static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
11190 switch (Name.getCXXOverloadedOperator()) {
11191 case OO_New: case OO_Array_New:
11192 case OO_Delete: case OO_Array_Delete:
11193 return false;
11194
11195 default:
11196 return true;
11197 }
11198}
11199
Richard Smith998a5912011-06-05 22:42:48 +000011200/// Attempt to recover from an ill-formed use of a non-dependent name in a
11201/// template, where the non-dependent name was declared after the template
11202/// was defined. This is common in code written for a compilers which do not
11203/// correctly implement two-stage name lookup.
11204///
11205/// Returns true if a viable candidate was found and a diagnostic was issued.
11206static bool
11207DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
11208 const CXXScopeSpec &SS, LookupResult &R,
Richard Smith100b24a2014-04-17 01:52:14 +000011209 OverloadCandidateSet::CandidateSetKind CSK,
Richard Smith998a5912011-06-05 22:42:48 +000011210 TemplateArgumentListInfo *ExplicitTemplateArgs,
Hans Wennborg64937c62015-06-11 21:21:57 +000011211 ArrayRef<Expr *> Args,
11212 bool *DoDiagnoseEmptyLookup = nullptr) {
Richard Smith998a5912011-06-05 22:42:48 +000011213 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
11214 return false;
11215
11216 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewyckyfcd5e7a2012-03-14 20:41:00 +000011217 if (DC->isTransparentContext())
11218 continue;
11219
Richard Smith998a5912011-06-05 22:42:48 +000011220 SemaRef.LookupQualifiedName(R, DC);
11221
11222 if (!R.empty()) {
11223 R.suppressDiagnostics();
11224
11225 if (isa<CXXRecordDecl>(DC)) {
11226 // Don't diagnose names we find in classes; we get much better
11227 // diagnostics for these from DiagnoseEmptyLookup.
11228 R.clear();
Hans Wennborg64937c62015-06-11 21:21:57 +000011229 if (DoDiagnoseEmptyLookup)
11230 *DoDiagnoseEmptyLookup = true;
Richard Smith998a5912011-06-05 22:42:48 +000011231 return false;
11232 }
11233
Richard Smith100b24a2014-04-17 01:52:14 +000011234 OverloadCandidateSet Candidates(FnLoc, CSK);
Richard Smith998a5912011-06-05 22:42:48 +000011235 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
11236 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011237 ExplicitTemplateArgs, Args,
Richard Smith95ce4f62011-06-26 22:19:54 +000011238 Candidates, false, /*KnownValid*/ false);
Richard Smith998a5912011-06-05 22:42:48 +000011239
11240 OverloadCandidateSet::iterator Best;
Richard Smith95ce4f62011-06-26 22:19:54 +000011241 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smith998a5912011-06-05 22:42:48 +000011242 // No viable functions. Don't bother the user with notes for functions
11243 // which don't work and shouldn't be found anyway.
Richard Smith95ce4f62011-06-26 22:19:54 +000011244 R.clear();
Richard Smith998a5912011-06-05 22:42:48 +000011245 return false;
Richard Smith95ce4f62011-06-26 22:19:54 +000011246 }
Richard Smith998a5912011-06-05 22:42:48 +000011247
11248 // Find the namespaces where ADL would have looked, and suggest
11249 // declaring the function there instead.
11250 Sema::AssociatedNamespaceSet AssociatedNamespaces;
11251 Sema::AssociatedClassSet AssociatedClasses;
John McCall7d8b0412012-08-24 20:38:34 +000011252 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
Richard Smith998a5912011-06-05 22:42:48 +000011253 AssociatedNamespaces,
11254 AssociatedClasses);
Chandler Carruthd50f1692011-06-05 23:36:55 +000011255 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smith0603bbb2013-06-12 22:56:54 +000011256 if (canBeDeclaredInNamespace(R.getLookupName())) {
11257 DeclContext *Std = SemaRef.getStdNamespace();
11258 for (Sema::AssociatedNamespaceSet::iterator
11259 it = AssociatedNamespaces.begin(),
11260 end = AssociatedNamespaces.end(); it != end; ++it) {
11261 // Never suggest declaring a function within namespace 'std'.
11262 if (Std && Std->Encloses(*it))
11263 continue;
Richard Smith21bae432012-12-22 02:46:14 +000011264
Richard Smith0603bbb2013-06-12 22:56:54 +000011265 // Never suggest declaring a function within a namespace with a
11266 // reserved name, like __gnu_cxx.
11267 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
11268 if (NS &&
11269 NS->getQualifiedNameAsString().find("__") != std::string::npos)
11270 continue;
11271
11272 SuggestedNamespaces.insert(*it);
11273 }
Richard Smith998a5912011-06-05 22:42:48 +000011274 }
11275
11276 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
11277 << R.getLookupName();
Chandler Carruthd50f1692011-06-05 23:36:55 +000011278 if (SuggestedNamespaces.empty()) {
Richard Smith998a5912011-06-05 22:42:48 +000011279 SemaRef.Diag(Best->Function->getLocation(),
11280 diag::note_not_found_by_two_phase_lookup)
11281 << R.getLookupName() << 0;
Chandler Carruthd50f1692011-06-05 23:36:55 +000011282 } else if (SuggestedNamespaces.size() == 1) {
Richard Smith998a5912011-06-05 22:42:48 +000011283 SemaRef.Diag(Best->Function->getLocation(),
11284 diag::note_not_found_by_two_phase_lookup)
Chandler Carruthd50f1692011-06-05 23:36:55 +000011285 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smith998a5912011-06-05 22:42:48 +000011286 } else {
11287 // FIXME: It would be useful to list the associated namespaces here,
11288 // but the diagnostics infrastructure doesn't provide a way to produce
11289 // a localized representation of a list of items.
11290 SemaRef.Diag(Best->Function->getLocation(),
11291 diag::note_not_found_by_two_phase_lookup)
11292 << R.getLookupName() << 2;
11293 }
11294
11295 // Try to recover by calling this function.
11296 return true;
11297 }
11298
11299 R.clear();
11300 }
11301
11302 return false;
11303}
11304
11305/// Attempt to recover from ill-formed use of a non-dependent operator in a
11306/// template, where the non-dependent operator was declared after the template
11307/// was defined.
11308///
11309/// Returns true if a viable candidate was found and a diagnostic was issued.
11310static bool
11311DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
11312 SourceLocation OpLoc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011313 ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +000011314 DeclarationName OpName =
11315 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
11316 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
11317 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Richard Smith100b24a2014-04-17 01:52:14 +000011318 OverloadCandidateSet::CSK_Operator,
Craig Topperc3ec1492014-05-26 06:22:03 +000011319 /*ExplicitTemplateArgs=*/nullptr, Args);
Richard Smith998a5912011-06-05 22:42:48 +000011320}
11321
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000011322namespace {
Richard Smith88d67f32012-09-25 04:46:05 +000011323class BuildRecoveryCallExprRAII {
11324 Sema &SemaRef;
11325public:
11326 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
11327 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
11328 SemaRef.IsBuildingRecoveryCallExpr = true;
11329 }
11330
11331 ~BuildRecoveryCallExprRAII() {
11332 SemaRef.IsBuildingRecoveryCallExpr = false;
11333 }
11334};
11335
Alexander Kornienkoab9db512015-06-22 23:07:51 +000011336}
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000011337
Kaelyn Takata89c881b2014-10-27 18:07:29 +000011338static std::unique_ptr<CorrectionCandidateCallback>
11339MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
11340 bool HasTemplateArgs, bool AllowTypoCorrection) {
11341 if (!AllowTypoCorrection)
11342 return llvm::make_unique<NoTypoCorrectionCCC>();
11343 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
11344 HasTemplateArgs, ME);
11345}
11346
John McCalld681c392009-12-16 08:11:27 +000011347/// Attempts to recover from a call where no functions were found.
11348///
11349/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +000011350static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +000011351BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +000011352 UnresolvedLookupExpr *ULE,
11353 SourceLocation LParenLoc,
Craig Toppere3d2ecbe2014-06-28 23:22:33 +000011354 MutableArrayRef<Expr *> Args,
Richard Smith998a5912011-06-05 22:42:48 +000011355 SourceLocation RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000011356 bool EmptyLookup, bool AllowTypoCorrection) {
Richard Smith88d67f32012-09-25 04:46:05 +000011357 // Do not try to recover if it is already building a recovery call.
11358 // This stops infinite loops for template instantiations like
11359 //
11360 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
11361 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
11362 //
11363 if (SemaRef.IsBuildingRecoveryCallExpr)
11364 return ExprError();
11365 BuildRecoveryCallExprRAII RCE(SemaRef);
John McCalld681c392009-12-16 08:11:27 +000011366
11367 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +000011368 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +000011369 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCalld681c392009-12-16 08:11:27 +000011370
John McCall57500772009-12-16 12:17:52 +000011371 TemplateArgumentListInfo TABuffer;
Craig Topperc3ec1492014-05-26 06:22:03 +000011372 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
John McCall57500772009-12-16 12:17:52 +000011373 if (ULE->hasExplicitTemplateArgs()) {
11374 ULE->copyTemplateArgumentsInto(TABuffer);
11375 ExplicitTemplateArgs = &TABuffer;
11376 }
11377
John McCalld681c392009-12-16 08:11:27 +000011378 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
11379 Sema::LookupOrdinaryName);
Hans Wennborg64937c62015-06-11 21:21:57 +000011380 bool DoDiagnoseEmptyLookup = EmptyLookup;
Richard Smith998a5912011-06-05 22:42:48 +000011381 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Richard Smith100b24a2014-04-17 01:52:14 +000011382 OverloadCandidateSet::CSK_Normal,
Hans Wennborg64937c62015-06-11 21:21:57 +000011383 ExplicitTemplateArgs, Args,
11384 &DoDiagnoseEmptyLookup) &&
11385 (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup(
11386 S, SS, R,
11387 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
11388 ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
11389 ExplicitTemplateArgs, Args)))
John McCallfaf5fb42010-08-26 23:41:50 +000011390 return ExprError();
John McCalld681c392009-12-16 08:11:27 +000011391
John McCall57500772009-12-16 12:17:52 +000011392 assert(!R.empty() && "lookup results empty despite recovery");
11393
11394 // Build an implicit member call if appropriate. Just drop the
11395 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +000011396 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +000011397 if ((*R.begin())->isCXXClassMember())
Aaron Ballman6924dcd2015-09-01 14:49:24 +000011398 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
11399 ExplicitTemplateArgs, S);
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000011400 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnara7945c982012-01-27 09:46:47 +000011401 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000011402 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +000011403 else
11404 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
11405
11406 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +000011407 return ExprError();
John McCall57500772009-12-16 12:17:52 +000011408
11409 // This shouldn't cause an infinite loop because we're giving it
Richard Smith998a5912011-06-05 22:42:48 +000011410 // an expression with viable lookup results, which should never
John McCall57500772009-12-16 12:17:52 +000011411 // end up here.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011412 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011413 MultiExprArg(Args.data(), Args.size()),
11414 RParenLoc);
John McCalld681c392009-12-16 08:11:27 +000011415}
Douglas Gregor4038cf42010-06-08 17:35:15 +000011416
Sam Panzer0f384432012-08-21 00:52:01 +000011417/// \brief Constructs and populates an OverloadedCandidateSet from
11418/// the given function.
11419/// \returns true when an the ExprResult output parameter has been set.
11420bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
11421 UnresolvedLookupExpr *ULE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011422 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011423 SourceLocation RParenLoc,
11424 OverloadCandidateSet *CandidateSet,
11425 ExprResult *Result) {
John McCall57500772009-12-16 12:17:52 +000011426#ifndef NDEBUG
11427 if (ULE->requiresADL()) {
11428 // To do ADL, we must have found an unqualified name.
11429 assert(!ULE->getQualifier() && "qualified name with ADL");
11430
11431 // We don't perform ADL for implicit declarations of builtins.
11432 // Verify that this was correctly set up.
11433 FunctionDecl *F;
11434 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
11435 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
11436 F->getBuiltinID() && F->isImplicit())
David Blaikie83d382b2011-09-23 05:06:16 +000011437 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011438
John McCall57500772009-12-16 12:17:52 +000011439 // We don't perform ADL in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011440 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smithb6626742012-10-18 17:56:02 +000011441 }
John McCall57500772009-12-16 12:17:52 +000011442#endif
11443
John McCall4124c492011-10-17 18:40:02 +000011444 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011445 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
Sam Panzer0f384432012-08-21 00:52:01 +000011446 *Result = ExprError();
11447 return true;
11448 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +000011449
John McCall57500772009-12-16 12:17:52 +000011450 // Add the functions denoted by the callee to the set of candidate
11451 // functions, including those from argument-dependent lookup.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011452 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
John McCalld681c392009-12-16 08:11:27 +000011453
Hans Wennborgb2747382015-06-12 21:23:23 +000011454 if (getLangOpts().MSVCCompat &&
11455 CurContext->isDependentContext() && !isSFINAEContext() &&
Hans Wennborg64937c62015-06-11 21:21:57 +000011456 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
11457
11458 OverloadCandidateSet::iterator Best;
11459 if (CandidateSet->empty() ||
11460 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) ==
11461 OR_No_Viable_Function) {
11462 // In Microsoft mode, if we are inside a template class member function then
11463 // create a type dependent CallExpr. The goal is to postpone name lookup
11464 // to instantiation time to be able to search into type dependent base
11465 // classes.
11466 CallExpr *CE = new (Context) CallExpr(
11467 Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc);
Sebastian Redlb49c46c2011-09-24 17:48:00 +000011468 CE->setTypeDependent(true);
Richard Smithed9b8f02015-09-23 21:30:47 +000011469 CE->setValueDependent(true);
11470 CE->setInstantiationDependent(true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011471 *Result = CE;
Sam Panzer0f384432012-08-21 00:52:01 +000011472 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +000011473 }
Francois Pichetbcf64712011-09-07 00:14:57 +000011474 }
John McCalld681c392009-12-16 08:11:27 +000011475
Hans Wennborg64937c62015-06-11 21:21:57 +000011476 if (CandidateSet->empty())
11477 return false;
11478
John McCall4124c492011-10-17 18:40:02 +000011479 UnbridgedCasts.restore();
Sam Panzer0f384432012-08-21 00:52:01 +000011480 return false;
11481}
John McCall4124c492011-10-17 18:40:02 +000011482
Sam Panzer0f384432012-08-21 00:52:01 +000011483/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
11484/// the completed call expression. If overload resolution fails, emits
11485/// diagnostics and returns ExprError()
11486static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11487 UnresolvedLookupExpr *ULE,
11488 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011489 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011490 SourceLocation RParenLoc,
11491 Expr *ExecConfig,
11492 OverloadCandidateSet *CandidateSet,
11493 OverloadCandidateSet::iterator *Best,
11494 OverloadingResult OverloadResult,
11495 bool AllowTypoCorrection) {
11496 if (CandidateSet->empty())
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011497 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011498 RParenLoc, /*EmptyLookup=*/true,
11499 AllowTypoCorrection);
11500
11501 switch (OverloadResult) {
John McCall57500772009-12-16 12:17:52 +000011502 case OR_Success: {
Sam Panzer0f384432012-08-21 00:52:01 +000011503 FunctionDecl *FDecl = (*Best)->Function;
Sam Panzer0f384432012-08-21 00:52:01 +000011504 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000011505 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
11506 return ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000011507 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011508 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11509 ExecConfig);
John McCall57500772009-12-16 12:17:52 +000011510 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011511
Richard Smith998a5912011-06-05 22:42:48 +000011512 case OR_No_Viable_Function: {
11513 // Try to recover by looking for viable functions which the user might
11514 // have meant to call.
Sam Panzer0f384432012-08-21 00:52:01 +000011515 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011516 Args, RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000011517 /*EmptyLookup=*/false,
11518 AllowTypoCorrection);
Richard Smith998a5912011-06-05 22:42:48 +000011519 if (!Recovery.isInvalid())
11520 return Recovery;
11521
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011522 // If the user passes in a function that we can't take the address of, we
11523 // generally end up emitting really bad error messages. Here, we attempt to
11524 // emit better ones.
11525 for (const Expr *Arg : Args) {
11526 if (!Arg->getType()->isFunctionType())
11527 continue;
11528 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
11529 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
11530 if (FD &&
11531 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
11532 Arg->getExprLoc()))
11533 return ExprError();
11534 }
11535 }
11536
11537 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_no_viable_function_in_call)
11538 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011539 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011540 break;
Richard Smith998a5912011-06-05 22:42:48 +000011541 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011542
11543 case OR_Ambiguous:
Sam Panzer0f384432012-08-21 00:52:01 +000011544 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +000011545 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011546 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011547 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000011548
Sam Panzer0f384432012-08-21 00:52:01 +000011549 case OR_Deleted: {
11550 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
11551 << (*Best)->Function->isDeleted()
11552 << ULE->getName()
11553 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
11554 << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011555 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Argyrios Kyrtzidis3eaa22a2011-11-04 15:58:13 +000011556
Sam Panzer0f384432012-08-21 00:52:01 +000011557 // We emitted an error for the unvailable/deleted function call but keep
11558 // the call in the AST.
11559 FunctionDecl *FDecl = (*Best)->Function;
11560 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011561 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11562 ExecConfig);
Sam Panzer0f384432012-08-21 00:52:01 +000011563 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011564 }
11565
Douglas Gregorb412e172010-07-25 18:17:45 +000011566 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +000011567 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011568}
11569
George Burgess IV7204ed92016-01-07 02:26:57 +000011570static void markUnaddressableCandidatesUnviable(Sema &S,
11571 OverloadCandidateSet &CS) {
11572 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
11573 if (I->Viable &&
11574 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
11575 I->Viable = false;
11576 I->FailureKind = ovl_fail_addr_not_available;
11577 }
11578 }
11579}
11580
Sam Panzer0f384432012-08-21 00:52:01 +000011581/// BuildOverloadedCallExpr - Given the call expression that calls Fn
11582/// (which eventually refers to the declaration Func) and the call
11583/// arguments Args/NumArgs, attempt to resolve the function call down
11584/// to a specific function. If overload resolution succeeds, returns
11585/// the call expression produced by overload resolution.
11586/// Otherwise, emits diagnostics and returns ExprError.
11587ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
11588 UnresolvedLookupExpr *ULE,
11589 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011590 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011591 SourceLocation RParenLoc,
11592 Expr *ExecConfig,
George Burgess IV7204ed92016-01-07 02:26:57 +000011593 bool AllowTypoCorrection,
11594 bool CalleesAddressIsTaken) {
Richard Smith100b24a2014-04-17 01:52:14 +000011595 OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
11596 OverloadCandidateSet::CSK_Normal);
Sam Panzer0f384432012-08-21 00:52:01 +000011597 ExprResult result;
11598
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011599 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
11600 &result))
Sam Panzer0f384432012-08-21 00:52:01 +000011601 return result;
11602
George Burgess IV7204ed92016-01-07 02:26:57 +000011603 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
11604 // functions that aren't addressible are considered unviable.
11605 if (CalleesAddressIsTaken)
11606 markUnaddressableCandidatesUnviable(*this, CandidateSet);
11607
Sam Panzer0f384432012-08-21 00:52:01 +000011608 OverloadCandidateSet::iterator Best;
11609 OverloadingResult OverloadResult =
11610 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
11611
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011612 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011613 RParenLoc, ExecConfig, &CandidateSet,
11614 &Best, OverloadResult,
11615 AllowTypoCorrection);
11616}
11617
John McCall4c4c1df2010-01-26 03:27:55 +000011618static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +000011619 return Functions.size() > 1 ||
11620 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
11621}
11622
Douglas Gregor084d8552009-03-13 23:49:33 +000011623/// \brief Create a unary operation that may resolve to an overloaded
11624/// operator.
11625///
11626/// \param OpLoc The location of the operator itself (e.g., '*').
11627///
Craig Toppera92ffb02015-12-10 08:51:49 +000011628/// \param Opc The UnaryOperatorKind that describes this operator.
Douglas Gregor084d8552009-03-13 23:49:33 +000011629///
James Dennett18348b62012-06-22 08:52:37 +000011630/// \param Fns The set of non-member functions that will be
Douglas Gregor084d8552009-03-13 23:49:33 +000011631/// considered by overload resolution. The caller needs to build this
11632/// set based on the context using, e.g.,
11633/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11634/// set should not contain any member functions; those will be added
11635/// by CreateOverloadedUnaryOp().
11636///
James Dennett91738ff2012-06-22 10:32:46 +000011637/// \param Input The input argument.
John McCalldadc5752010-08-24 06:29:42 +000011638ExprResult
Craig Toppera92ffb02015-12-10 08:51:49 +000011639Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
John McCall4c4c1df2010-01-26 03:27:55 +000011640 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +000011641 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +000011642 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
11643 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
11644 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011645 // TODO: provide better source location info.
11646 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +000011647
John McCall4124c492011-10-17 18:40:02 +000011648 if (checkPlaceholderForOverload(*this, Input))
11649 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011650
Craig Topperc3ec1492014-05-26 06:22:03 +000011651 Expr *Args[2] = { Input, nullptr };
Douglas Gregor084d8552009-03-13 23:49:33 +000011652 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +000011653
Douglas Gregor084d8552009-03-13 23:49:33 +000011654 // For post-increment and post-decrement, add the implicit '0' as
11655 // the second argument, so that we know this is a post-increment or
11656 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +000011657 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +000011658 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +000011659 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
11660 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +000011661 NumArgs = 2;
11662 }
11663
Richard Smithe54c3072013-05-05 15:51:06 +000011664 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
11665
Douglas Gregor084d8552009-03-13 23:49:33 +000011666 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +000011667 if (Fns.empty())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011668 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
11669 VK_RValue, OK_Ordinary, OpLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011670
Craig Topperc3ec1492014-05-26 06:22:03 +000011671 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +000011672 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000011673 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000011674 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000011675 /*ADL*/ true, IsOverloaded(Fns),
11676 Fns.begin(), Fns.end());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011677 return new (Context)
11678 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
11679 VK_RValue, OpLoc, false);
Douglas Gregor084d8552009-03-13 23:49:33 +000011680 }
11681
11682 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000011683 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
Douglas Gregor084d8552009-03-13 23:49:33 +000011684
11685 // Add the candidates from the given function set.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011686 AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000011687
11688 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000011689 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000011690
John McCall4c4c1df2010-01-26 03:27:55 +000011691 // Add candidates from ADL.
Richard Smith100b24a2014-04-17 01:52:14 +000011692 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
Craig Topperc3ec1492014-05-26 06:22:03 +000011693 /*ExplicitTemplateArgs*/nullptr,
11694 CandidateSet);
John McCall4c4c1df2010-01-26 03:27:55 +000011695
Douglas Gregor084d8552009-03-13 23:49:33 +000011696 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011697 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000011698
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011699 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11700
Douglas Gregor084d8552009-03-13 23:49:33 +000011701 // Perform overload resolution.
11702 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011703 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +000011704 case OR_Success: {
11705 // We found a built-in operator or an overloaded operator.
11706 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +000011707
Douglas Gregor084d8552009-03-13 23:49:33 +000011708 if (FnDecl) {
11709 // We matched an overloaded operator. Build a call to that
11710 // operator.
Mike Stump11289f42009-09-09 15:08:12 +000011711
Douglas Gregor084d8552009-03-13 23:49:33 +000011712 // Convert the arguments.
11713 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Craig Topperc3ec1492014-05-26 06:22:03 +000011714 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000011715
John Wiegley01296292011-04-08 18:41:53 +000011716 ExprResult InputRes =
Craig Topperc3ec1492014-05-26 06:22:03 +000011717 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000011718 Best->FoundDecl, Method);
11719 if (InputRes.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000011720 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011721 Input = InputRes.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000011722 } else {
11723 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000011724 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +000011725 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000011726 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +000011727 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011728 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +000011729 Input);
Douglas Gregore6600372009-12-23 17:40:29 +000011730 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000011731 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011732 Input = InputInit.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000011733 }
11734
Douglas Gregor084d8552009-03-13 23:49:33 +000011735 // Build the actual expression node.
Nick Lewycky134af912013-02-07 05:08:22 +000011736 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011737 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011738 if (FnExpr.isInvalid())
11739 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +000011740
Richard Smithc1564702013-11-15 02:58:23 +000011741 // Determine the result type.
Alp Toker314cc812014-01-25 16:55:45 +000011742 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000011743 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11744 ResultTy = ResultTy.getNonLValueExprType(Context);
11745
Eli Friedman030eee42009-11-18 03:58:17 +000011746 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +000011747 CallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011748 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
Lang Hames5de91cc2012-10-02 04:45:10 +000011749 ResultTy, VK, OpLoc, false);
John McCall4fa0d5f2010-05-06 18:15:07 +000011750
Alp Toker314cc812014-01-25 16:55:45 +000011751 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
Anders Carlssonf64a3da2009-10-13 21:19:37 +000011752 return ExprError();
11753
John McCallb268a282010-08-23 23:25:46 +000011754 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +000011755 } else {
11756 // We matched a built-in operator. Convert the arguments, then
11757 // break out so that we will build the appropriate built-in
11758 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000011759 ExprResult InputRes =
11760 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
11761 Best->Conversions[0], AA_Passing);
11762 if (InputRes.isInvalid())
11763 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011764 Input = InputRes.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000011765 break;
Douglas Gregor084d8552009-03-13 23:49:33 +000011766 }
John Wiegley01296292011-04-08 18:41:53 +000011767 }
11768
11769 case OR_No_Viable_Function:
Richard Smith998a5912011-06-05 22:42:48 +000011770 // This is an erroneous use of an operator which can be overloaded by
11771 // a non-member function. Check for non-member operators which were
11772 // defined too late to be candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011773 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
Richard Smith998a5912011-06-05 22:42:48 +000011774 // FIXME: Recover by calling the found function.
11775 return ExprError();
11776
John Wiegley01296292011-04-08 18:41:53 +000011777 // No viable function; fall through to handling this as a
11778 // built-in operator, which will produce an error message for us.
11779 break;
11780
11781 case OR_Ambiguous:
11782 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
11783 << UnaryOperator::getOpcodeStr(Opc)
11784 << Input->getType()
11785 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000011786 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
John Wiegley01296292011-04-08 18:41:53 +000011787 UnaryOperator::getOpcodeStr(Opc), OpLoc);
11788 return ExprError();
11789
11790 case OR_Deleted:
11791 Diag(OpLoc, diag::err_ovl_deleted_oper)
11792 << Best->Function->isDeleted()
11793 << UnaryOperator::getOpcodeStr(Opc)
11794 << getDeletedOrUnavailableSuffix(Best->Function)
11795 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000011796 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000011797 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011798 return ExprError();
11799 }
Douglas Gregor084d8552009-03-13 23:49:33 +000011800
11801 // Either we found no viable overloaded operator or we matched a
11802 // built-in operator. In either case, fall through to trying to
11803 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +000011804 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +000011805}
11806
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011807/// \brief Create a binary operation that may resolve to an overloaded
11808/// operator.
11809///
11810/// \param OpLoc The location of the operator itself (e.g., '+').
11811///
Craig Toppera92ffb02015-12-10 08:51:49 +000011812/// \param Opc The BinaryOperatorKind that describes this operator.
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011813///
James Dennett18348b62012-06-22 08:52:37 +000011814/// \param Fns The set of non-member functions that will be
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011815/// considered by overload resolution. The caller needs to build this
11816/// set based on the context using, e.g.,
11817/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11818/// set should not contain any member functions; those will be added
11819/// by CreateOverloadedBinOp().
11820///
11821/// \param LHS Left-hand argument.
11822/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +000011823ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011824Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Craig Toppera92ffb02015-12-10 08:51:49 +000011825 BinaryOperatorKind Opc,
John McCall4c4c1df2010-01-26 03:27:55 +000011826 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011827 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011828 Expr *Args[2] = { LHS, RHS };
Craig Topperc3ec1492014-05-26 06:22:03 +000011829 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011830
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011831 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
11832 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
11833
11834 // If either side is type-dependent, create an appropriate dependent
11835 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +000011836 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +000011837 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011838 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +000011839 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +000011840 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011841 return new (Context) BinaryOperator(
11842 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
11843 OpLoc, FPFeatures.fp_contract);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011844
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011845 return new (Context) CompoundAssignOperator(
11846 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
11847 Context.DependentTy, Context.DependentTy, OpLoc,
11848 FPFeatures.fp_contract);
Douglas Gregor5287f092009-11-05 00:51:44 +000011849 }
John McCall4c4c1df2010-01-26 03:27:55 +000011850
11851 // FIXME: save results of ADL from here?
Craig Topperc3ec1492014-05-26 06:22:03 +000011852 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011853 // TODO: provide better source location info in DNLoc component.
11854 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +000011855 UnresolvedLookupExpr *Fn
Douglas Gregor0da1d432011-02-28 20:01:57 +000011856 = UnresolvedLookupExpr::Create(Context, NamingClass,
11857 NestedNameSpecifierLoc(), OpNameInfo,
11858 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000011859 Fns.begin(), Fns.end());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011860 return new (Context)
11861 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
11862 VK_RValue, OpLoc, FPFeatures.fp_contract);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011863 }
11864
John McCall4124c492011-10-17 18:40:02 +000011865 // Always do placeholder-like conversions on the RHS.
11866 if (checkPlaceholderForOverload(*this, Args[1]))
11867 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011868
John McCall526ab472011-10-25 17:37:35 +000011869 // Do placeholder-like conversion on the LHS; note that we should
11870 // not get here with a PseudoObject LHS.
11871 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall4124c492011-10-17 18:40:02 +000011872 if (checkPlaceholderForOverload(*this, Args[0]))
11873 return ExprError();
11874
Sebastian Redl6a96bf72009-11-18 23:10:33 +000011875 // If this is the assignment operator, we only perform overload resolution
11876 // if the left-hand side is a class or enumeration type. This is actually
11877 // a hack. The standard requires that we do overload resolution between the
11878 // various built-in candidates, but as DR507 points out, this can lead to
11879 // problems. So we do it this way, which pretty much follows what GCC does.
11880 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +000011881 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +000011882 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011883
John McCalle26a8722010-12-04 08:14:53 +000011884 // If this is the .* operator, which is not overloadable, just
11885 // create a built-in binary operator.
11886 if (Opc == BO_PtrMemD)
11887 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11888
Douglas Gregor084d8552009-03-13 23:49:33 +000011889 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000011890 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011891
11892 // Add the candidates from the given function set.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011893 AddFunctionCandidates(Fns, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011894
11895 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000011896 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011897
Richard Smith0daabd72014-09-23 20:31:39 +000011898 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
11899 // performed for an assignment operator (nor for operator[] nor operator->,
11900 // which don't get here).
11901 if (Opc != BO_Assign)
11902 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
11903 /*ExplicitTemplateArgs*/ nullptr,
11904 CandidateSet);
John McCall4c4c1df2010-01-26 03:27:55 +000011905
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011906 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011907 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011908
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011909 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11910
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011911 // Perform overload resolution.
11912 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011913 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +000011914 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011915 // We found a built-in operator or an overloaded operator.
11916 FunctionDecl *FnDecl = Best->Function;
11917
11918 if (FnDecl) {
11919 // We matched an overloaded operator. Build a call to that
11920 // operator.
11921
11922 // Convert the arguments.
11923 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +000011924 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +000011925 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000011926
Chandler Carruth8e543b32010-12-12 08:17:55 +000011927 ExprResult Arg1 =
11928 PerformCopyInitialization(
11929 InitializedEntity::InitializeParameter(Context,
11930 FnDecl->getParamDecl(0)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011931 SourceLocation(), Args[1]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011932 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011933 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011934
John Wiegley01296292011-04-08 18:41:53 +000011935 ExprResult Arg0 =
Craig Topperc3ec1492014-05-26 06:22:03 +000011936 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000011937 Best->FoundDecl, Method);
11938 if (Arg0.isInvalid())
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011939 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011940 Args[0] = Arg0.getAs<Expr>();
11941 Args[1] = RHS = Arg1.getAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011942 } else {
11943 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +000011944 ExprResult Arg0 = PerformCopyInitialization(
11945 InitializedEntity::InitializeParameter(Context,
11946 FnDecl->getParamDecl(0)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011947 SourceLocation(), Args[0]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011948 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011949 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011950
Chandler Carruth8e543b32010-12-12 08:17:55 +000011951 ExprResult Arg1 =
11952 PerformCopyInitialization(
11953 InitializedEntity::InitializeParameter(Context,
11954 FnDecl->getParamDecl(1)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011955 SourceLocation(), Args[1]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011956 if (Arg1.isInvalid())
11957 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011958 Args[0] = LHS = Arg0.getAs<Expr>();
11959 Args[1] = RHS = Arg1.getAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011960 }
11961
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011962 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011963 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000011964 Best->FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011965 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011966 if (FnExpr.isInvalid())
11967 return ExprError();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011968
Richard Smithc1564702013-11-15 02:58:23 +000011969 // Determine the result type.
Alp Toker314cc812014-01-25 16:55:45 +000011970 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000011971 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11972 ResultTy = ResultTy.getNonLValueExprType(Context);
11973
John McCallb268a282010-08-23 23:25:46 +000011974 CXXOperatorCallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011975 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
Lang Hames5de91cc2012-10-02 04:45:10 +000011976 Args, ResultTy, VK, OpLoc,
11977 FPFeatures.fp_contract);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011978
Alp Toker314cc812014-01-25 16:55:45 +000011979 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000011980 FnDecl))
11981 return ExprError();
11982
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000011983 ArrayRef<const Expr *> ArgsArray(Args, 2);
11984 // Cut off the implicit 'this'.
11985 if (isa<CXXMethodDecl>(FnDecl))
11986 ArgsArray = ArgsArray.slice(1);
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011987
11988 // Check for a self move.
11989 if (Op == OO_Equal)
11990 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
11991
Douglas Gregorb4866e82015-06-19 18:13:19 +000011992 checkCall(FnDecl, nullptr, ArgsArray, isa<CXXMethodDecl>(FnDecl), OpLoc,
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000011993 TheCall->getSourceRange(), VariadicDoesNotApply);
11994
John McCallb268a282010-08-23 23:25:46 +000011995 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011996 } else {
11997 // We matched a built-in operator. Convert the arguments, then
11998 // break out so that we will build the appropriate built-in
11999 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000012000 ExprResult ArgsRes0 =
12001 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
12002 Best->Conversions[0], AA_Passing);
12003 if (ArgsRes0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012004 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012005 Args[0] = ArgsRes0.get();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012006
John Wiegley01296292011-04-08 18:41:53 +000012007 ExprResult ArgsRes1 =
12008 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
12009 Best->Conversions[1], AA_Passing);
12010 if (ArgsRes1.isInvalid())
12011 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012012 Args[1] = ArgsRes1.get();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012013 break;
12014 }
12015 }
12016
Douglas Gregor66950a32009-09-30 21:46:01 +000012017 case OR_No_Viable_Function: {
12018 // C++ [over.match.oper]p9:
12019 // If the operator is the operator , [...] and there are no
12020 // viable functions, then the operator is assumed to be the
12021 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +000012022 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +000012023 break;
12024
Chandler Carruth8e543b32010-12-12 08:17:55 +000012025 // For class as left operand for assignment or compound assigment
12026 // operator do not fall through to handling in built-in, but report that
12027 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +000012028 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012029 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +000012030 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +000012031 Diag(OpLoc, diag::err_ovl_no_viable_oper)
12032 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +000012033 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Eli Friedmana31efa02013-08-28 20:35:35 +000012034 if (Args[0]->getType()->isIncompleteType()) {
12035 Diag(OpLoc, diag::note_assign_lhs_incomplete)
12036 << Args[0]->getType()
12037 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12038 }
Douglas Gregor66950a32009-09-30 21:46:01 +000012039 } else {
Richard Smith998a5912011-06-05 22:42:48 +000012040 // This is an erroneous use of an operator which can be overloaded by
12041 // a non-member function. Check for non-member operators which were
12042 // defined too late to be candidates.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012043 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smith998a5912011-06-05 22:42:48 +000012044 // FIXME: Recover by calling the found function.
12045 return ExprError();
12046
Douglas Gregor66950a32009-09-30 21:46:01 +000012047 // No viable function; try to create a built-in operation, which will
12048 // produce an error. Then, show the non-viable candidates.
12049 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +000012050 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012051 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +000012052 "C++ binary operator overloading is missing candidates!");
12053 if (Result.isInvalid())
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012054 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012055 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012056 return Result;
Douglas Gregor66950a32009-09-30 21:46:01 +000012057 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012058
12059 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000012060 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012061 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +000012062 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +000012063 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012064 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012065 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012066 return ExprError();
12067
12068 case OR_Deleted:
Douglas Gregor74f7d502012-02-15 19:33:52 +000012069 if (isImplicitlyDeleted(Best->Function)) {
12070 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12071 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
Richard Smithde1a4872012-12-28 12:23:24 +000012072 << Context.getRecordType(Method->getParent())
12073 << getSpecialMember(Method);
Richard Smith6f1e2c62012-04-02 20:59:25 +000012074
Richard Smithde1a4872012-12-28 12:23:24 +000012075 // The user probably meant to call this special member. Just
12076 // explain why it's deleted.
12077 NoteDeletedFunction(Method);
12078 return ExprError();
Douglas Gregor74f7d502012-02-15 19:33:52 +000012079 } else {
12080 Diag(OpLoc, diag::err_ovl_deleted_oper)
12081 << Best->Function->isDeleted()
12082 << BinaryOperator::getOpcodeStr(Opc)
12083 << getDeletedOrUnavailableSuffix(Best->Function)
12084 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12085 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012086 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000012087 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012088 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +000012089 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012090
Douglas Gregor66950a32009-09-30 21:46:01 +000012091 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +000012092 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012093}
12094
John McCalldadc5752010-08-24 06:29:42 +000012095ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +000012096Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
12097 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +000012098 Expr *Base, Expr *Idx) {
12099 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +000012100 DeclarationName OpName =
12101 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
12102
12103 // If either side is type-dependent, create an appropriate dependent
12104 // expression.
12105 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12106
Craig Topperc3ec1492014-05-26 06:22:03 +000012107 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000012108 // CHECKME: no 'operator' keyword?
12109 DeclarationNameInfo OpNameInfo(OpName, LLoc);
12110 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +000012111 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000012112 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000012113 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000012114 /*ADL*/ true, /*Overloaded*/ false,
12115 UnresolvedSetIterator(),
12116 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +000012117 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +000012118
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012119 return new (Context)
12120 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
12121 Context.DependentTy, VK_RValue, RLoc, false);
Sebastian Redladba46e2009-10-29 20:17:01 +000012122 }
12123
John McCall4124c492011-10-17 18:40:02 +000012124 // Handle placeholders on both operands.
12125 if (checkPlaceholderForOverload(*this, Args[0]))
12126 return ExprError();
12127 if (checkPlaceholderForOverload(*this, Args[1]))
12128 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012129
Sebastian Redladba46e2009-10-29 20:17:01 +000012130 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000012131 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
Sebastian Redladba46e2009-10-29 20:17:01 +000012132
12133 // Subscript can only be overloaded as a member function.
12134
12135 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000012136 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000012137
12138 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000012139 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000012140
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012141 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12142
Sebastian Redladba46e2009-10-29 20:17:01 +000012143 // Perform overload resolution.
12144 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012145 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +000012146 case OR_Success: {
12147 // We found a built-in operator or an overloaded operator.
12148 FunctionDecl *FnDecl = Best->Function;
12149
12150 if (FnDecl) {
12151 // We matched an overloaded operator. Build a call to that
12152 // operator.
12153
John McCalla0296f72010-03-19 07:35:19 +000012154 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall58cc69d2010-01-27 01:50:18 +000012155
Sebastian Redladba46e2009-10-29 20:17:01 +000012156 // Convert the arguments.
12157 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley01296292011-04-08 18:41:53 +000012158 ExprResult Arg0 =
Craig Topperc3ec1492014-05-26 06:22:03 +000012159 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012160 Best->FoundDecl, Method);
12161 if (Arg0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000012162 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012163 Args[0] = Arg0.get();
Sebastian Redladba46e2009-10-29 20:17:01 +000012164
Anders Carlssona68e51e2010-01-29 18:37:50 +000012165 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000012166 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +000012167 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000012168 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +000012169 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012170 SourceLocation(),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012171 Args[1]);
Anders Carlssona68e51e2010-01-29 18:37:50 +000012172 if (InputInit.isInvalid())
12173 return ExprError();
12174
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012175 Args[1] = InputInit.getAs<Expr>();
Anders Carlssona68e51e2010-01-29 18:37:50 +000012176
Sebastian Redladba46e2009-10-29 20:17:01 +000012177 // Build the actual expression node.
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012178 DeclarationNameInfo OpLocInfo(OpName, LLoc);
12179 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012180 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000012181 Best->FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012182 HadMultipleCandidates,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012183 OpLocInfo.getLoc(),
12184 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000012185 if (FnExpr.isInvalid())
12186 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000012187
Richard Smithc1564702013-11-15 02:58:23 +000012188 // Determine the result type
Alp Toker314cc812014-01-25 16:55:45 +000012189 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000012190 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12191 ResultTy = ResultTy.getNonLValueExprType(Context);
12192
John McCallb268a282010-08-23 23:25:46 +000012193 CXXOperatorCallExpr *TheCall =
12194 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012195 FnExpr.get(), Args,
Lang Hames5de91cc2012-10-02 04:45:10 +000012196 ResultTy, VK, RLoc,
12197 false);
Sebastian Redladba46e2009-10-29 20:17:01 +000012198
Alp Toker314cc812014-01-25 16:55:45 +000012199 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
Sebastian Redladba46e2009-10-29 20:17:01 +000012200 return ExprError();
12201
John McCallb268a282010-08-23 23:25:46 +000012202 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +000012203 } else {
12204 // We matched a built-in operator. Convert the arguments, then
12205 // break out so that we will build the appropriate built-in
12206 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000012207 ExprResult ArgsRes0 =
12208 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
12209 Best->Conversions[0], AA_Passing);
12210 if (ArgsRes0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000012211 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012212 Args[0] = ArgsRes0.get();
John Wiegley01296292011-04-08 18:41:53 +000012213
12214 ExprResult ArgsRes1 =
12215 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
12216 Best->Conversions[1], AA_Passing);
12217 if (ArgsRes1.isInvalid())
12218 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012219 Args[1] = ArgsRes1.get();
Sebastian Redladba46e2009-10-29 20:17:01 +000012220
12221 break;
12222 }
12223 }
12224
12225 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +000012226 if (CandidateSet.empty())
12227 Diag(LLoc, diag::err_ovl_no_oper)
12228 << Args[0]->getType() << /*subscript*/ 0
12229 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12230 else
12231 Diag(LLoc, diag::err_ovl_no_viable_subscript)
12232 << Args[0]->getType()
12233 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012234 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012235 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +000012236 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000012237 }
12238
12239 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000012240 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012241 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +000012242 << Args[0]->getType() << Args[1]->getType()
12243 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012244 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012245 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000012246 return ExprError();
12247
12248 case OR_Deleted:
12249 Diag(LLoc, diag::err_ovl_deleted_oper)
12250 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012251 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +000012252 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012253 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012254 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000012255 return ExprError();
12256 }
12257
12258 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +000012259 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000012260}
12261
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012262/// BuildCallToMemberFunction - Build a call to a member
12263/// function. MemExpr is the expression that refers to the member
12264/// function (and includes the object parameter), Args/NumArgs are the
12265/// arguments to the function call (not including the object
12266/// parameter). The caller needs to validate that the member
John McCall0009fcc2011-04-26 20:42:42 +000012267/// expression refers to a non-static member function or an overloaded
12268/// member function.
John McCalldadc5752010-08-24 06:29:42 +000012269ExprResult
Mike Stump11289f42009-09-09 15:08:12 +000012270Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012271 SourceLocation LParenLoc,
12272 MultiExprArg Args,
12273 SourceLocation RParenLoc) {
John McCall0009fcc2011-04-26 20:42:42 +000012274 assert(MemExprE->getType() == Context.BoundMemberTy ||
12275 MemExprE->getType() == Context.OverloadTy);
12276
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012277 // Dig out the member expression. This holds both the object
12278 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +000012279 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012280
John McCall0009fcc2011-04-26 20:42:42 +000012281 // Determine whether this is a call to a pointer-to-member function.
12282 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
12283 assert(op->getType() == Context.BoundMemberTy);
12284 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
12285
12286 QualType fnType =
12287 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
12288
12289 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
12290 QualType resultType = proto->getCallResultType(Context);
Alp Toker314cc812014-01-25 16:55:45 +000012291 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
John McCall0009fcc2011-04-26 20:42:42 +000012292
12293 // Check that the object type isn't more qualified than the
12294 // member function we're calling.
12295 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
12296
12297 QualType objectType = op->getLHS()->getType();
12298 if (op->getOpcode() == BO_PtrMemI)
12299 objectType = objectType->castAs<PointerType>()->getPointeeType();
12300 Qualifiers objectQuals = objectType.getQualifiers();
12301
12302 Qualifiers difference = objectQuals - funcQuals;
12303 difference.removeObjCGCAttr();
12304 difference.removeAddressSpace();
12305 if (difference) {
12306 std::string qualsString = difference.getAsString();
12307 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
12308 << fnType.getUnqualifiedType()
12309 << qualsString
12310 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
12311 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +000012312
John McCall0009fcc2011-04-26 20:42:42 +000012313 CXXMemberCallExpr *call
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012314 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall0009fcc2011-04-26 20:42:42 +000012315 resultType, valueKind, RParenLoc);
12316
Alp Toker314cc812014-01-25 16:55:45 +000012317 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
Craig Topperc3ec1492014-05-26 06:22:03 +000012318 call, nullptr))
John McCall0009fcc2011-04-26 20:42:42 +000012319 return ExprError();
12320
Craig Topperc3ec1492014-05-26 06:22:03 +000012321 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
John McCall0009fcc2011-04-26 20:42:42 +000012322 return ExprError();
12323
Richard Trieu9be9c682013-06-22 02:30:38 +000012324 if (CheckOtherCall(call, proto))
12325 return ExprError();
12326
John McCall0009fcc2011-04-26 20:42:42 +000012327 return MaybeBindToTemporary(call);
12328 }
12329
David Majnemerced8bdf2015-02-25 17:36:15 +000012330 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
12331 return new (Context)
12332 CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc);
12333
John McCall4124c492011-10-17 18:40:02 +000012334 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012335 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000012336 return ExprError();
12337
John McCall10eae182009-11-30 22:42:35 +000012338 MemberExpr *MemExpr;
Craig Topperc3ec1492014-05-26 06:22:03 +000012339 CXXMethodDecl *Method = nullptr;
12340 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
12341 NestedNameSpecifier *Qualifier = nullptr;
John McCall10eae182009-11-30 22:42:35 +000012342 if (isa<MemberExpr>(NakedMemExpr)) {
12343 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +000012344 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +000012345 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +000012346 Qualifier = MemExpr->getQualifier();
John McCall4124c492011-10-17 18:40:02 +000012347 UnbridgedCasts.restore();
John McCall10eae182009-11-30 22:42:35 +000012348 } else {
12349 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +000012350 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012351
John McCall6e9f8f62009-12-03 04:06:58 +000012352 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +000012353 Expr::Classification ObjectClassification
12354 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
12355 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +000012356
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012357 // Add overload candidates
Richard Smith100b24a2014-04-17 01:52:14 +000012358 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
12359 OverloadCandidateSet::CSK_Normal);
Mike Stump11289f42009-09-09 15:08:12 +000012360
John McCall2d74de92009-12-01 22:10:20 +000012361 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000012362 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCall2d74de92009-12-01 22:10:20 +000012363 if (UnresExpr->hasExplicitTemplateArgs()) {
12364 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12365 TemplateArgs = &TemplateArgsBuffer;
12366 }
12367
John McCall10eae182009-11-30 22:42:35 +000012368 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
12369 E = UnresExpr->decls_end(); I != E; ++I) {
12370
John McCall6e9f8f62009-12-03 04:06:58 +000012371 NamedDecl *Func = *I;
12372 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
12373 if (isa<UsingShadowDecl>(Func))
12374 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
12375
Douglas Gregor02824322011-01-26 19:30:28 +000012376
Francois Pichet64225792011-01-18 05:04:39 +000012377 // Microsoft supports direct constructor calls.
David Blaikiebbafb8a2012-03-11 07:00:24 +000012378 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012379 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012380 Args, CandidateSet);
Francois Pichet64225792011-01-18 05:04:39 +000012381 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +000012382 // If explicit template arguments were provided, we can't call a
12383 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +000012384 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +000012385 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012386
John McCalla0296f72010-03-19 07:35:19 +000012387 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012388 ObjectClassification, Args, CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +000012389 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000012390 } else {
John McCall10eae182009-11-30 22:42:35 +000012391 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +000012392 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012393 ObjectType, ObjectClassification,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012394 Args, CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000012395 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000012396 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000012397 }
Mike Stump11289f42009-09-09 15:08:12 +000012398
John McCall10eae182009-11-30 22:42:35 +000012399 DeclarationName DeclName = UnresExpr->getMemberName();
12400
John McCall4124c492011-10-17 18:40:02 +000012401 UnbridgedCasts.restore();
12402
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012403 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012404 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +000012405 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012406 case OR_Success:
12407 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +000012408 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +000012409 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000012410 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
12411 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000012412 // If FoundDecl is different from Method (such as if one is a template
12413 // and the other a specialization), make sure DiagnoseUseOfDecl is
12414 // called on both.
12415 // FIXME: This would be more comprehensively addressed by modifying
12416 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
12417 // being used.
12418 if (Method != FoundDecl.getDecl() &&
12419 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
12420 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012421 break;
12422
12423 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +000012424 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012425 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000012426 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012427 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012428 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000012429 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012430
12431 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +000012432 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000012433 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012434 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012435 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000012436 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000012437
12438 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +000012439 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +000012440 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012441 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012442 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012443 << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012444 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000012445 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000012446 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012447 }
12448
John McCall16df1e52010-03-30 21:47:33 +000012449 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +000012450
John McCall2d74de92009-12-01 22:10:20 +000012451 // If overload resolution picked a static member, build a
12452 // non-member call based on that function.
12453 if (Method->isStatic()) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012454 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
12455 RParenLoc);
John McCall2d74de92009-12-01 22:10:20 +000012456 }
12457
John McCall10eae182009-11-30 22:42:35 +000012458 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012459 }
12460
Alp Toker314cc812014-01-25 16:55:45 +000012461 QualType ResultType = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000012462 ExprValueKind VK = Expr::getValueKindForType(ResultType);
12463 ResultType = ResultType.getNonLValueExprType(Context);
12464
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012465 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012466 CXXMemberCallExpr *TheCall =
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012467 new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall7decc9e2010-11-18 06:31:45 +000012468 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012469
Anders Carlssonc4859ba2009-10-10 00:06:20 +000012470 // Check for a valid return type.
Alp Toker314cc812014-01-25 16:55:45 +000012471 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +000012472 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +000012473 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012474
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012475 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +000012476 // We only need to do this if there was actually an overload; otherwise
12477 // it was done at lookup.
John Wiegley01296292011-04-08 18:41:53 +000012478 if (!Method->isStatic()) {
12479 ExprResult ObjectArg =
12480 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
12481 FoundDecl, Method);
12482 if (ObjectArg.isInvalid())
12483 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012484 MemExpr->setBase(ObjectArg.get());
John Wiegley01296292011-04-08 18:41:53 +000012485 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012486
12487 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +000012488 const FunctionProtoType *Proto =
12489 Method->getType()->getAs<FunctionProtoType>();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012490 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012491 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +000012492 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012493
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012494 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000012495
Richard Smith55ce3522012-06-25 20:30:08 +000012496 if (CheckFunctionCall(Method, TheCall, Proto))
John McCall2d74de92009-12-01 22:10:20 +000012497 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +000012498
George Burgess IVaea6ade2015-09-25 17:53:16 +000012499 // In the case the method to call was not selected by the overloading
12500 // resolution process, we still need to handle the enable_if attribute. Do
George Burgess IV0d546532016-11-10 21:47:12 +000012501 // that here, so it will not hide previous -- and more relevant -- errors.
George Burgess IVaea6ade2015-09-25 17:53:16 +000012502 if (isa<MemberExpr>(NakedMemExpr)) {
12503 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
12504 Diag(MemExprE->getLocStart(),
12505 diag::err_ovl_no_viable_member_function_in_call)
12506 << Method << Method->getSourceRange();
12507 Diag(Method->getLocation(),
12508 diag::note_ovl_candidate_disabled_by_enable_if_attr)
12509 << Attr->getCond()->getSourceRange() << Attr->getMessage();
12510 return ExprError();
12511 }
12512 }
12513
Anders Carlsson47061ee2011-05-06 14:25:31 +000012514 if ((isa<CXXConstructorDecl>(CurContext) ||
12515 isa<CXXDestructorDecl>(CurContext)) &&
12516 TheCall->getMethodDecl()->isPure()) {
12517 const CXXMethodDecl *MD = TheCall->getMethodDecl();
12518
Davide Italianoccb37382015-07-14 23:36:10 +000012519 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
12520 MemExpr->performsVirtualDispatch(getLangOpts())) {
12521 Diag(MemExpr->getLocStart(),
Anders Carlsson47061ee2011-05-06 14:25:31 +000012522 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
12523 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
12524 << MD->getParent()->getDeclName();
12525
12526 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Davide Italianoccb37382015-07-14 23:36:10 +000012527 if (getLangOpts().AppleKext)
12528 Diag(MemExpr->getLocStart(),
12529 diag::note_pure_qualified_call_kext)
12530 << MD->getParent()->getDeclName()
12531 << MD->getDeclName();
Chandler Carruth59259262011-06-27 08:31:58 +000012532 }
Anders Carlsson47061ee2011-05-06 14:25:31 +000012533 }
Nico Weber5a9259c2016-01-15 21:45:31 +000012534
12535 if (CXXDestructorDecl *DD =
12536 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
12537 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
Justin Lebard35f7062016-07-12 23:23:01 +000012538 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
Nico Weber5a9259c2016-01-15 21:45:31 +000012539 CheckVirtualDtorCall(DD, MemExpr->getLocStart(), /*IsDelete=*/false,
12540 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
12541 MemExpr->getMemberLoc());
12542 }
12543
John McCallb268a282010-08-23 23:25:46 +000012544 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012545}
12546
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012547/// BuildCallToObjectOfClassType - Build a call to an object of class
12548/// type (C++ [over.call.object]), which can end up invoking an
12549/// overloaded function call operator (@c operator()) or performing a
12550/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +000012551ExprResult
John Wiegley01296292011-04-08 18:41:53 +000012552Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregorb0846b02008-12-06 00:22:45 +000012553 SourceLocation LParenLoc,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012554 MultiExprArg Args,
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012555 SourceLocation RParenLoc) {
John McCall4124c492011-10-17 18:40:02 +000012556 if (checkPlaceholderForOverload(*this, Obj))
12557 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012558 ExprResult Object = Obj;
John McCall4124c492011-10-17 18:40:02 +000012559
12560 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012561 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000012562 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012563
Nico Weberb58e51c2014-11-19 05:21:39 +000012564 assert(Object.get()->getType()->isRecordType() &&
12565 "Requires object type argument");
John Wiegley01296292011-04-08 18:41:53 +000012566 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +000012567
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012568 // C++ [over.call.object]p1:
12569 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +000012570 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012571 // candidate functions includes at least the function call
12572 // operators of T. The function call operators of T are obtained by
12573 // ordinary lookup of the name operator() in the context of
12574 // (E).operator().
Richard Smith100b24a2014-04-17 01:52:14 +000012575 OverloadCandidateSet CandidateSet(LParenLoc,
12576 OverloadCandidateSet::CSK_Operator);
Douglas Gregor91f84212008-12-11 16:49:14 +000012577 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +000012578
John Wiegley01296292011-04-08 18:41:53 +000012579 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012580 diag::err_incomplete_object_call, Object.get()))
Douglas Gregorc473cbb2009-11-15 07:48:03 +000012581 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012582
John McCall27b18f82009-11-17 02:14:36 +000012583 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
12584 LookupQualifiedName(R, Record->getDecl());
12585 R.suppressDiagnostics();
12586
Douglas Gregorc473cbb2009-11-15 07:48:03 +000012587 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +000012588 Oper != OperEnd; ++Oper) {
John Wiegley01296292011-04-08 18:41:53 +000012589 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012590 Object.get()->Classify(Context),
12591 Args, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +000012592 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +000012593 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012594
Douglas Gregorab7897a2008-11-19 22:57:39 +000012595 // C++ [over.call.object]p2:
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012596 // In addition, for each (non-explicit in C++0x) conversion function
12597 // declared in T of the form
Douglas Gregorab7897a2008-11-19 22:57:39 +000012598 //
12599 // operator conversion-type-id () cv-qualifier;
12600 //
12601 // where cv-qualifier is the same cv-qualification as, or a
12602 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +000012603 // denotes the type "pointer to function of (P1,...,Pn) returning
12604 // R", or the type "reference to pointer to function of
12605 // (P1,...,Pn) returning R", or the type "reference to function
12606 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +000012607 // is also considered as a candidate function. Similarly,
12608 // surrogate call functions are added to the set of candidate
12609 // functions for each conversion function declared in an
12610 // accessible base class provided the function is not hidden
12611 // within T by another intervening declaration.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +000012612 const auto &Conversions =
12613 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
12614 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +000012615 NamedDecl *D = *I;
12616 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
12617 if (isa<UsingShadowDecl>(D))
12618 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012619
Douglas Gregor74ba25c2009-10-21 06:18:39 +000012620 // Skip over templated conversion functions; they aren't
12621 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +000012622 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +000012623 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +000012624
John McCall6e9f8f62009-12-03 04:06:58 +000012625 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012626 if (!Conv->isExplicit()) {
12627 // Strip the reference type (if any) and then the pointer type (if
12628 // any) to get down to what might be a function type.
12629 QualType ConvType = Conv->getConversionType().getNonReferenceType();
12630 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
12631 ConvType = ConvPtrType->getPointeeType();
John McCalld14a8642009-11-21 08:51:07 +000012632
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012633 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
12634 {
12635 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012636 Object.get(), Args, CandidateSet);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012637 }
12638 }
Douglas Gregorab7897a2008-11-19 22:57:39 +000012639 }
Mike Stump11289f42009-09-09 15:08:12 +000012640
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012641 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12642
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012643 // Perform overload resolution.
12644 OverloadCandidateSet::iterator Best;
John Wiegley01296292011-04-08 18:41:53 +000012645 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall5c32be02010-08-24 20:38:10 +000012646 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012647 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +000012648 // Overload resolution succeeded; we'll build the appropriate call
12649 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012650 break;
12651
12652 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +000012653 if (CandidateSet.empty())
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012654 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley01296292011-04-08 18:41:53 +000012655 << Object.get()->getType() << /*call*/ 1
12656 << Object.get()->getSourceRange();
John McCall02374852010-01-07 02:04:15 +000012657 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012658 Diag(Object.get()->getLocStart(),
John McCall02374852010-01-07 02:04:15 +000012659 diag::err_ovl_no_viable_object_call)
John Wiegley01296292011-04-08 18:41:53 +000012660 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012661 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012662 break;
12663
12664 case OR_Ambiguous:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012665 Diag(Object.get()->getLocStart(),
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012666 diag::err_ovl_ambiguous_object_call)
John Wiegley01296292011-04-08 18:41:53 +000012667 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012668 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012669 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000012670
12671 case OR_Deleted:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012672 Diag(Object.get()->getLocStart(),
Douglas Gregor171c45a2009-02-18 21:56:37 +000012673 diag::err_ovl_deleted_object_call)
12674 << Best->Function->isDeleted()
John Wiegley01296292011-04-08 18:41:53 +000012675 << Object.get()->getType()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012676 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley01296292011-04-08 18:41:53 +000012677 << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012678 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000012679 break;
Mike Stump11289f42009-09-09 15:08:12 +000012680 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012681
Douglas Gregorb412e172010-07-25 18:17:45 +000012682 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012683 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012684
John McCall4124c492011-10-17 18:40:02 +000012685 UnbridgedCasts.restore();
12686
Craig Topperc3ec1492014-05-26 06:22:03 +000012687 if (Best->Function == nullptr) {
Douglas Gregorab7897a2008-11-19 22:57:39 +000012688 // Since there is no function declaration, this is one of the
12689 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +000012690 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +000012691 = cast<CXXConversionDecl>(
12692 Best->Conversions[0].UserDefined.ConversionFunction);
12693
Craig Topperc3ec1492014-05-26 06:22:03 +000012694 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
12695 Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000012696 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
12697 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000012698 assert(Conv == Best->FoundDecl.getDecl() &&
12699 "Found Decl & conversion-to-functionptr should be same, right?!");
Douglas Gregorab7897a2008-11-19 22:57:39 +000012700 // We selected one of the surrogate functions that converts the
12701 // object parameter to a function pointer. Perform the conversion
12702 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012703
Fariborz Jahanian774cf792009-09-28 18:35:46 +000012704 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +000012705 // and then call it.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012706 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
12707 Conv, HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +000012708 if (Call.isInvalid())
12709 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +000012710 // Record usage of conversion in an implicit cast.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012711 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
12712 CK_UserDefinedConversion, Call.get(),
12713 nullptr, VK_RValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012714
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012715 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +000012716 }
12717
Craig Topperc3ec1492014-05-26 06:22:03 +000012718 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
John McCall49ec2e62010-01-28 01:54:34 +000012719
Douglas Gregorab7897a2008-11-19 22:57:39 +000012720 // We found an overloaded operator(). Build a CXXOperatorCallExpr
12721 // that calls this method, using Object for the implicit object
12722 // parameter and passing along the remaining arguments.
12723 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Nico Weber1fefe412012-11-09 06:06:14 +000012724
12725 // An error diagnostic has already been printed when parsing the declaration.
Nico Weber9512d3f2012-11-09 08:38:04 +000012726 if (Method->isInvalidDecl())
Nico Weber1fefe412012-11-09 06:06:14 +000012727 return ExprError();
12728
Chandler Carruth8e543b32010-12-12 08:17:55 +000012729 const FunctionProtoType *Proto =
12730 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012731
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012732 unsigned NumParams = Proto->getNumParams();
Mike Stump11289f42009-09-09 15:08:12 +000012733
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012734 DeclarationNameInfo OpLocInfo(
12735 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
12736 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Nick Lewycky134af912013-02-07 05:08:22 +000012737 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012738 HadMultipleCandidates,
12739 OpLocInfo.getLoc(),
12740 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000012741 if (NewFn.isInvalid())
12742 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012743
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012744 // Build the full argument list for the method call (the implicit object
12745 // parameter is placed at the beginning of the list).
Ahmed Charlesaf94d562014-03-09 11:34:25 +000012746 std::unique_ptr<Expr * []> MethodArgs(new Expr *[Args.size() + 1]);
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012747 MethodArgs[0] = Object.get();
12748 std::copy(Args.begin(), Args.end(), &MethodArgs[1]);
12749
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012750 // Once we've built TheCall, all of the expressions are properly
12751 // owned.
Alp Toker314cc812014-01-25 16:55:45 +000012752 QualType ResultTy = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000012753 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12754 ResultTy = ResultTy.getNonLValueExprType(Context);
12755
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012756 CXXOperatorCallExpr *TheCall = new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012757 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(),
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012758 llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1),
12759 ResultTy, VK, RParenLoc, false);
12760 MethodArgs.reset();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012761
Alp Toker314cc812014-01-25 16:55:45 +000012762 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
Anders Carlsson3d5829c2009-10-13 21:49:31 +000012763 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012764
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012765 // We may have default arguments. If so, we need to allocate more
12766 // slots in the call for them.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012767 if (Args.size() < NumParams)
12768 TheCall->setNumArgs(Context, NumParams + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012769
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000012770 bool IsError = false;
12771
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012772 // Initialize the implicit object parameter.
John Wiegley01296292011-04-08 18:41:53 +000012773 ExprResult ObjRes =
Craig Topperc3ec1492014-05-26 06:22:03 +000012774 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012775 Best->FoundDecl, Method);
12776 if (ObjRes.isInvalid())
12777 IsError = true;
12778 else
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012779 Object = ObjRes;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012780 TheCall->setArg(0, Object.get());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000012781
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012782 // Check the argument types.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012783 for (unsigned i = 0; i != NumParams; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012784 Expr *Arg;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012785 if (i < Args.size()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012786 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +000012787
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012788 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012789
John McCalldadc5752010-08-24 06:29:42 +000012790 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012791 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000012792 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012793 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +000012794 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012795
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012796 IsError |= InputInit.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012797 Arg = InputInit.getAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012798 } else {
John McCalldadc5752010-08-24 06:29:42 +000012799 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +000012800 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
12801 if (DefArg.isInvalid()) {
12802 IsError = true;
12803 break;
12804 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012805
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012806 Arg = DefArg.getAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012807 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012808
12809 TheCall->setArg(i + 1, Arg);
12810 }
12811
12812 // If this is a variadic call, handle args passed through "...".
12813 if (Proto->isVariadic()) {
12814 // Promote the arguments (C99 6.5.2.2p7).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012815 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
Craig Topperc3ec1492014-05-26 06:22:03 +000012816 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
12817 nullptr);
John Wiegley01296292011-04-08 18:41:53 +000012818 IsError |= Arg.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012819 TheCall->setArg(i + 1, Arg.get());
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012820 }
12821 }
12822
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000012823 if (IsError) return true;
12824
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012825 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000012826
Richard Smith55ce3522012-06-25 20:30:08 +000012827 if (CheckFunctionCall(Method, TheCall, Proto))
Anders Carlssonbc4c1072009-08-16 01:56:34 +000012828 return true;
12829
John McCalle172be52010-08-24 06:09:16 +000012830 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012831}
12832
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012833/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +000012834/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012835/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +000012836ExprResult
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000012837Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
12838 bool *NoArrowOperatorFound) {
Chandler Carruth8e543b32010-12-12 08:17:55 +000012839 assert(Base->getType()->isRecordType() &&
12840 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +000012841
John McCall4124c492011-10-17 18:40:02 +000012842 if (checkPlaceholderForOverload(*this, Base))
12843 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012844
John McCallbc077cf2010-02-08 23:07:23 +000012845 SourceLocation Loc = Base->getExprLoc();
12846
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012847 // C++ [over.ref]p1:
12848 //
12849 // [...] An expression x->m is interpreted as (x.operator->())->m
12850 // for a class object x of type T if T::operator->() exists and if
12851 // the operator is selected as the best match function by the
12852 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +000012853 DeclarationName OpName =
12854 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
Richard Smith100b24a2014-04-17 01:52:14 +000012855 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
Ted Kremenekc23c7e62009-07-29 21:53:49 +000012856 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +000012857
John McCallbc077cf2010-02-08 23:07:23 +000012858 if (RequireCompleteType(Loc, Base->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012859 diag::err_typecheck_incomplete_tag, Base))
Eli Friedman132e70b2009-11-18 01:28:03 +000012860 return ExprError();
12861
John McCall27b18f82009-11-17 02:14:36 +000012862 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
12863 LookupQualifiedName(R, BaseRecord->getDecl());
12864 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +000012865
12866 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +000012867 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +000012868 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +000012869 None, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +000012870 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012871
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012872 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12873
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012874 // Perform overload resolution.
12875 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012876 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012877 case OR_Success:
12878 // Overload resolution succeeded; we'll build the call below.
12879 break;
12880
12881 case OR_No_Viable_Function:
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012882 if (CandidateSet.empty()) {
12883 QualType BaseType = Base->getType();
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000012884 if (NoArrowOperatorFound) {
12885 // Report this specific error to the caller instead of emitting a
12886 // diagnostic, as requested.
12887 *NoArrowOperatorFound = true;
12888 return ExprError();
12889 }
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000012890 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
12891 << BaseType << Base->getSourceRange();
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012892 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000012893 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012894 << FixItHint::CreateReplacement(OpLoc, ".");
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012895 }
12896 } else
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012897 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +000012898 << "operator->" << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012899 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012900 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012901
12902 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000012903 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
12904 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012905 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012906 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000012907
12908 case OR_Deleted:
12909 Diag(OpLoc, diag::err_ovl_deleted_oper)
12910 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012911 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012912 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012913 << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012914 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012915 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012916 }
12917
Craig Topperc3ec1492014-05-26 06:22:03 +000012918 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
John McCalla0296f72010-03-19 07:35:19 +000012919
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012920 // Convert the object parameter.
12921 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000012922 ExprResult BaseResult =
Craig Topperc3ec1492014-05-26 06:22:03 +000012923 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012924 Best->FoundDecl, Method);
12925 if (BaseResult.isInvalid())
Douglas Gregord8061562009-08-06 03:17:00 +000012926 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012927 Base = BaseResult.get();
Douglas Gregor9ecea262008-11-21 03:04:22 +000012928
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012929 // Build the operator call.
Nick Lewycky134af912013-02-07 05:08:22 +000012930 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012931 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000012932 if (FnExpr.isInvalid())
12933 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012934
Alp Toker314cc812014-01-25 16:55:45 +000012935 QualType ResultTy = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000012936 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12937 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +000012938 CXXOperatorCallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012939 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
Lang Hames5de91cc2012-10-02 04:45:10 +000012940 Base, ResultTy, VK, OpLoc, false);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000012941
Alp Toker314cc812014-01-25 16:55:45 +000012942 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000012943 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +000012944
12945 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012946}
12947
Richard Smithbcc22fc2012-03-09 08:00:36 +000012948/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
12949/// a literal operator described by the provided lookup results.
12950ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
12951 DeclarationNameInfo &SuffixInfo,
12952 ArrayRef<Expr*> Args,
12953 SourceLocation LitEndLoc,
12954 TemplateArgumentListInfo *TemplateArgs) {
12955 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smithc67fdd42012-03-07 08:35:16 +000012956
Richard Smith100b24a2014-04-17 01:52:14 +000012957 OverloadCandidateSet CandidateSet(UDSuffixLoc,
12958 OverloadCandidateSet::CSK_Normal);
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000012959 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
12960 /*SuppressUserConversions=*/true);
Richard Smithc67fdd42012-03-07 08:35:16 +000012961
Richard Smithbcc22fc2012-03-09 08:00:36 +000012962 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12963
Richard Smithbcc22fc2012-03-09 08:00:36 +000012964 // Perform overload resolution. This will usually be trivial, but might need
12965 // to perform substitutions for a literal operator template.
12966 OverloadCandidateSet::iterator Best;
12967 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
12968 case OR_Success:
12969 case OR_Deleted:
12970 break;
12971
12972 case OR_No_Viable_Function:
12973 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
12974 << R.getLookupName();
12975 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12976 return ExprError();
12977
12978 case OR_Ambiguous:
12979 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
12980 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
12981 return ExprError();
Richard Smithc67fdd42012-03-07 08:35:16 +000012982 }
12983
Richard Smithbcc22fc2012-03-09 08:00:36 +000012984 FunctionDecl *FD = Best->Function;
Nick Lewycky134af912013-02-07 05:08:22 +000012985 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
12986 HadMultipleCandidates,
Richard Smithbcc22fc2012-03-09 08:00:36 +000012987 SuffixInfo.getLoc(),
12988 SuffixInfo.getInfo());
12989 if (Fn.isInvalid())
12990 return true;
Richard Smithc67fdd42012-03-07 08:35:16 +000012991
12992 // Check the argument types. This should almost always be a no-op, except
12993 // that array-to-pointer decay is applied to string literals.
Richard Smithc67fdd42012-03-07 08:35:16 +000012994 Expr *ConvArgs[2];
Richard Smithe54c3072013-05-05 15:51:06 +000012995 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Richard Smithc67fdd42012-03-07 08:35:16 +000012996 ExprResult InputInit = PerformCopyInitialization(
12997 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
12998 SourceLocation(), Args[ArgIdx]);
12999 if (InputInit.isInvalid())
13000 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013001 ConvArgs[ArgIdx] = InputInit.get();
Richard Smithc67fdd42012-03-07 08:35:16 +000013002 }
13003
Alp Toker314cc812014-01-25 16:55:45 +000013004 QualType ResultTy = FD->getReturnType();
Richard Smithc67fdd42012-03-07 08:35:16 +000013005 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13006 ResultTy = ResultTy.getNonLValueExprType(Context);
13007
Richard Smithc67fdd42012-03-07 08:35:16 +000013008 UserDefinedLiteral *UDL =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013009 new (Context) UserDefinedLiteral(Context, Fn.get(),
Benjamin Kramerc215e762012-08-24 11:54:20 +000013010 llvm::makeArrayRef(ConvArgs, Args.size()),
Richard Smithc67fdd42012-03-07 08:35:16 +000013011 ResultTy, VK, LitEndLoc, UDSuffixLoc);
13012
Alp Toker314cc812014-01-25 16:55:45 +000013013 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
Richard Smithc67fdd42012-03-07 08:35:16 +000013014 return ExprError();
13015
Craig Topperc3ec1492014-05-26 06:22:03 +000013016 if (CheckFunctionCall(FD, UDL, nullptr))
Richard Smithc67fdd42012-03-07 08:35:16 +000013017 return ExprError();
13018
13019 return MaybeBindToTemporary(UDL);
13020}
13021
Sam Panzer0f384432012-08-21 00:52:01 +000013022/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
13023/// given LookupResult is non-empty, it is assumed to describe a member which
13024/// will be invoked. Otherwise, the function will be found via argument
13025/// dependent lookup.
13026/// CallExpr is set to a valid expression and FRS_Success returned on success,
13027/// otherwise CallExpr is set to ExprError() and some non-success value
13028/// is returned.
13029Sema::ForRangeStatus
Richard Smith9f690bd2015-10-27 06:02:45 +000013030Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
13031 SourceLocation RangeLoc,
Sam Panzer0f384432012-08-21 00:52:01 +000013032 const DeclarationNameInfo &NameInfo,
13033 LookupResult &MemberLookup,
13034 OverloadCandidateSet *CandidateSet,
13035 Expr *Range, ExprResult *CallExpr) {
Richard Smith9f690bd2015-10-27 06:02:45 +000013036 Scope *S = nullptr;
13037
Sam Panzer0f384432012-08-21 00:52:01 +000013038 CandidateSet->clear();
13039 if (!MemberLookup.empty()) {
13040 ExprResult MemberRef =
13041 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
13042 /*IsPtr=*/false, CXXScopeSpec(),
13043 /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +000013044 /*FirstQualifierInScope=*/nullptr,
Sam Panzer0f384432012-08-21 00:52:01 +000013045 MemberLookup,
Aaron Ballman6924dcd2015-09-01 14:49:24 +000013046 /*TemplateArgs=*/nullptr, S);
Sam Panzer0f384432012-08-21 00:52:01 +000013047 if (MemberRef.isInvalid()) {
13048 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000013049 return FRS_DiagnosticIssued;
13050 }
Craig Topperc3ec1492014-05-26 06:22:03 +000013051 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
Sam Panzer0f384432012-08-21 00:52:01 +000013052 if (CallExpr->isInvalid()) {
13053 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000013054 return FRS_DiagnosticIssued;
13055 }
13056 } else {
13057 UnresolvedSet<0> FoundNames;
Sam Panzer0f384432012-08-21 00:52:01 +000013058 UnresolvedLookupExpr *Fn =
Craig Topperc3ec1492014-05-26 06:22:03 +000013059 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
Sam Panzer0f384432012-08-21 00:52:01 +000013060 NestedNameSpecifierLoc(), NameInfo,
13061 /*NeedsADL=*/true, /*Overloaded=*/false,
Richard Smithb6626742012-10-18 17:56:02 +000013062 FoundNames.begin(), FoundNames.end());
Sam Panzer0f384432012-08-21 00:52:01 +000013063
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000013064 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
Sam Panzer0f384432012-08-21 00:52:01 +000013065 CandidateSet, CallExpr);
13066 if (CandidateSet->empty() || CandidateSetError) {
13067 *CallExpr = ExprError();
13068 return FRS_NoViableFunction;
13069 }
13070 OverloadCandidateSet::iterator Best;
13071 OverloadingResult OverloadResult =
13072 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
13073
13074 if (OverloadResult == OR_No_Viable_Function) {
13075 *CallExpr = ExprError();
13076 return FRS_NoViableFunction;
13077 }
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000013078 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
Craig Topperc3ec1492014-05-26 06:22:03 +000013079 Loc, nullptr, CandidateSet, &Best,
Sam Panzer0f384432012-08-21 00:52:01 +000013080 OverloadResult,
13081 /*AllowTypoCorrection=*/false);
13082 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
13083 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000013084 return FRS_DiagnosticIssued;
13085 }
13086 }
13087 return FRS_Success;
13088}
13089
13090
Douglas Gregorcd695e52008-11-10 20:40:00 +000013091/// FixOverloadedFunctionReference - E is an expression that refers to
13092/// a C++ overloaded function (possibly with some parentheses and
13093/// perhaps a '&' around it). We have resolved the overloaded function
13094/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +000013095/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +000013096Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +000013097 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +000013098 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000013099 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
13100 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000013101 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000013102 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013103
Douglas Gregor51c538b2009-11-20 19:42:02 +000013104 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013105 }
13106
Douglas Gregor51c538b2009-11-20 19:42:02 +000013107 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000013108 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
13109 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013110 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +000013111 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +000013112 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +000013113 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +000013114 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000013115 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013116
13117 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +000013118 ICE->getCastKind(),
Craig Topperc3ec1492014-05-26 06:22:03 +000013119 SubExpr, nullptr,
John McCall2536c6d2010-08-25 10:28:54 +000013120 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013121 }
13122
Aaron Ballmanff7bd8b2016-09-02 13:45:40 +000013123 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
13124 if (!GSE->isResultDependent()) {
13125 Expr *SubExpr =
13126 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
13127 if (SubExpr == GSE->getResultExpr())
13128 return GSE;
13129
13130 // Replace the resulting type information before rebuilding the generic
13131 // selection expression.
Aaron Ballman8b871d92016-09-02 18:31:31 +000013132 ArrayRef<Expr *> A = GSE->getAssocExprs();
13133 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
Aaron Ballmanff7bd8b2016-09-02 13:45:40 +000013134 unsigned ResultIdx = GSE->getResultIndex();
13135 AssocExprs[ResultIdx] = SubExpr;
13136
13137 return new (Context) GenericSelectionExpr(
13138 Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
13139 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
13140 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
13141 ResultIdx);
13142 }
13143 // Rather than fall through to the unreachable, return the original generic
13144 // selection expression.
13145 return GSE;
13146 }
13147
Douglas Gregor51c538b2009-11-20 19:42:02 +000013148 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +000013149 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +000013150 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +000013151 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13152 if (Method->isStatic()) {
13153 // Do nothing: static member functions aren't any different
13154 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +000013155 } else {
Alp Toker028ed912013-12-06 17:56:43 +000013156 // Fix the subexpression, which really has to be an
John McCalle66edc12009-11-24 19:00:30 +000013157 // UnresolvedLookupExpr holding an overloaded member function
13158 // or template.
John McCall16df1e52010-03-30 21:47:33 +000013159 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13160 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +000013161 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000013162 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +000013163
John McCalld14a8642009-11-21 08:51:07 +000013164 assert(isa<DeclRefExpr>(SubExpr)
13165 && "fixed to something other than a decl ref");
13166 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
13167 && "fixed to a member ref with no nested name qualifier");
13168
13169 // We have taken the address of a pointer to member
13170 // function. Perform the computation here so that we get the
13171 // appropriate pointer to member type.
13172 QualType ClassType
13173 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
13174 QualType MemPtrType
13175 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
David Majnemer02d57cc2016-06-30 03:02:03 +000013176 // Under the MS ABI, lock down the inheritance model now.
13177 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13178 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
John McCalld14a8642009-11-21 08:51:07 +000013179
John McCall7decc9e2010-11-18 06:31:45 +000013180 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
13181 VK_RValue, OK_Ordinary,
13182 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +000013183 }
13184 }
John McCall16df1e52010-03-30 21:47:33 +000013185 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13186 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000013187 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000013188 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013189
John McCalle3027922010-08-25 11:45:40 +000013190 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +000013191 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +000013192 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +000013193 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013194 }
John McCalld14a8642009-11-21 08:51:07 +000013195
Richard Smith84a0b6d2016-10-18 23:39:12 +000013196 // C++ [except.spec]p17:
13197 // An exception-specification is considered to be needed when:
13198 // - in an expression the function is the unique lookup result or the
13199 // selected member of a set of overloaded functions
13200 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13201 ResolveExceptionSpec(E->getExprLoc(), FPT);
13202
John McCalld14a8642009-11-21 08:51:07 +000013203 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +000013204 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000013205 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCalle66edc12009-11-24 19:00:30 +000013206 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +000013207 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
13208 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +000013209 }
13210
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013211 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13212 ULE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000013213 ULE->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013214 Fn,
John McCall113bee02012-03-10 09:33:50 +000013215 /*enclosing*/ false, // FIXME?
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013216 ULE->getNameLoc(),
13217 Fn->getType(),
13218 VK_LValue,
13219 Found.getDecl(),
13220 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000013221 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013222 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
13223 return DRE;
John McCalld14a8642009-11-21 08:51:07 +000013224 }
13225
John McCall10eae182009-11-30 22:42:35 +000013226 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +000013227 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000013228 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCall2d74de92009-12-01 22:10:20 +000013229 if (MemExpr->hasExplicitTemplateArgs()) {
13230 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
13231 TemplateArgs = &TemplateArgsBuffer;
13232 }
John McCall6b51f282009-11-23 01:53:49 +000013233
John McCall2d74de92009-12-01 22:10:20 +000013234 Expr *Base;
13235
John McCall7decc9e2010-11-18 06:31:45 +000013236 // If we're filling in a static method where we used to have an
13237 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +000013238 if (MemExpr->isImplicitAccess()) {
13239 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013240 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13241 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000013242 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013243 Fn,
John McCall113bee02012-03-10 09:33:50 +000013244 /*enclosing*/ false,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013245 MemExpr->getMemberLoc(),
13246 Fn->getType(),
13247 VK_LValue,
13248 Found.getDecl(),
13249 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000013250 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013251 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
13252 return DRE;
Douglas Gregorb15af892010-01-07 23:12:05 +000013253 } else {
13254 SourceLocation Loc = MemExpr->getMemberLoc();
13255 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +000013256 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman73a04092012-01-07 04:59:52 +000013257 CheckCXXThisCapture(Loc);
Douglas Gregorb15af892010-01-07 23:12:05 +000013258 Base = new (Context) CXXThisExpr(Loc,
13259 MemExpr->getBaseType(),
13260 /*isImplicit=*/true);
13261 }
John McCall2d74de92009-12-01 22:10:20 +000013262 } else
John McCallc3007a22010-10-26 07:05:15 +000013263 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +000013264
John McCall4adb38c2011-04-27 00:36:17 +000013265 ExprValueKind valueKind;
13266 QualType type;
13267 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13268 valueKind = VK_LValue;
13269 type = Fn->getType();
13270 } else {
13271 valueKind = VK_RValue;
Yunzhong Gaoeba323a2015-05-01 02:04:32 +000013272 type = Context.BoundMemberTy;
13273 }
13274
13275 MemberExpr *ME = MemberExpr::Create(
13276 Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
13277 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
13278 MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
13279 OK_Ordinary);
13280 ME->setHadMultipleCandidates(true);
13281 MarkMemberReferenced(ME);
13282 return ME;
Douglas Gregor51c538b2009-11-20 19:42:02 +000013283 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013284
John McCallc3007a22010-10-26 07:05:15 +000013285 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregorcd695e52008-11-10 20:40:00 +000013286}
13287
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013288ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +000013289 DeclAccessPair Found,
13290 FunctionDecl *Fn) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000013291 return FixOverloadedFunctionReference(E.get(), Found, Fn);
Douglas Gregor3e1e5272009-12-09 23:02:17 +000013292}