blob: b760cdcd34e57d72181deea979d1f699a52177e8 [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"
George Burgess IV177399e2017-01-09 04:12:14 +000032#include "llvm/ADT/Optional.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000033#include "llvm/ADT/STLExtras.h"
Douglas Gregor58e008d2008-11-13 20:12:29 +000034#include "llvm/ADT/SmallPtrSet.h"
Richard Smith9ca64612012-05-07 09:03:25 +000035#include "llvm/ADT/SmallString.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000036#include <algorithm>
David Blaikie8ad22e62014-05-01 23:01:41 +000037#include <cstdlib>
Douglas Gregor5251f1b2008-10-21 16:13:35 +000038
Richard Smith17c00b42014-11-12 01:24:00 +000039using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000040using namespace sema;
Douglas Gregor5251f1b2008-10-21 16:13:35 +000041
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000042static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) {
George Burgess IV21081362016-07-24 23:12:40 +000043 return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
44 return P->hasAttr<PassObjectSizeAttr>();
45 });
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000046}
47
Nick Lewycky134af912013-02-07 05:08:22 +000048/// A convenience routine for creating a decayed reference to a function.
John Wiegley01296292011-04-08 18:41:53 +000049static ExprResult
Nick Lewycky134af912013-02-07 05:08:22 +000050CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
Akira Hatanaka22461672017-07-13 06:08:27 +000051 const Expr *Base, bool HadMultipleCandidates,
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000052 SourceLocation Loc = SourceLocation(),
Douglas Gregore9d62932011-07-15 16:25:15 +000053 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
Richard Smith22262ab2013-05-04 06:44:46 +000054 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000055 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000056 // If FoundDecl is different from Fn (such as if one is a template
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000057 // and the other a specialization), make sure DiagnoseUseOfDecl is
Faisal Valid6676412013-06-15 11:54:37 +000058 // called on both.
59 // FIXME: This would be more comprehensively addressed by modifying
60 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
61 // being used.
62 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
Richard Smith22262ab2013-05-04 06:44:46 +000063 return ExprError();
Richard Smith5f4b3882016-10-19 00:14:23 +000064 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
65 S.ResolveExceptionSpec(Loc, FPT);
John McCall113bee02012-03-10 09:33:50 +000066 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000067 VK_LValue, Loc, LocInfo);
68 if (HadMultipleCandidates)
69 DRE->setHadMultipleCandidates(true);
Nick Lewycky134af912013-02-07 05:08:22 +000070
Akira Hatanaka22461672017-07-13 06:08:27 +000071 S.MarkDeclRefReferenced(DRE, Base);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000072 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
73 CK_FunctionToPointerDecay);
John McCall7decc9e2010-11-18 06:31:45 +000074}
75
John McCall5c32be02010-08-24 20:38:10 +000076static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
77 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +000078 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +000079 bool CStyle,
80 bool AllowObjCWritebackConversion);
Sam Panzer04390a62012-08-16 02:38:47 +000081
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000082static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +000083 QualType &ToType,
84 bool InOverloadResolution,
85 StandardConversionSequence &SCS,
86 bool CStyle);
John McCall5c32be02010-08-24 20:38:10 +000087static OverloadingResult
88IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
89 UserDefinedConversionSequence& User,
90 OverloadCandidateSet& Conversions,
Douglas Gregor4b60a152013-11-07 22:34:54 +000091 bool AllowExplicit,
92 bool AllowObjCConversionOnExplicit);
John McCall5c32be02010-08-24 20:38:10 +000093
94
95static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +000096CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +000097 const StandardConversionSequence& SCS1,
98 const StandardConversionSequence& SCS2);
99
100static ImplicitConversionSequence::CompareKind
101CompareQualificationConversions(Sema &S,
102 const StandardConversionSequence& SCS1,
103 const StandardConversionSequence& SCS2);
104
105static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +0000106CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +0000107 const StandardConversionSequence& SCS1,
108 const StandardConversionSequence& SCS2);
109
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000110/// GetConversionRank - Retrieve the implicit conversion rank
111/// corresponding to the given implicit conversion kind.
Richard Smith17c00b42014-11-12 01:24:00 +0000112ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000113 static const ImplicitConversionRank
114 Rank[(int)ICK_Num_Conversion_Kinds] = {
115 ICR_Exact_Match,
116 ICR_Exact_Match,
117 ICR_Exact_Match,
118 ICR_Exact_Match,
119 ICR_Exact_Match,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000120 ICR_Exact_Match,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000121 ICR_Promotion,
122 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000123 ICR_Promotion,
124 ICR_Conversion,
125 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000126 ICR_Conversion,
127 ICR_Conversion,
128 ICR_Conversion,
129 ICR_Conversion,
130 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000131 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000132 ICR_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000133 ICR_Conversion,
Egor Churaevc217f372017-03-21 12:55:55 +0000134 ICR_OCL_Scalar_Widening,
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000135 ICR_Complex_Real_Conversion,
136 ICR_Conversion,
John McCall31168b02011-06-15 23:02:42 +0000137 ICR_Conversion,
George Burgess IV45461812015-10-11 20:13:20 +0000138 ICR_Writeback_Conversion,
139 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
140 // it was omitted by the patch that added
141 // ICK_Zero_Event_Conversion
George Burgess IV2099b542016-09-02 22:59:57 +0000142 ICR_C_Conversion,
143 ICR_C_Conversion_Extension
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000144 };
145 return Rank[(int)Kind];
146}
147
148/// GetImplicitConversionName - Return the name of this kind of
149/// implicit conversion.
Richard Smith17c00b42014-11-12 01:24:00 +0000150static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopescfca1f02009-12-23 17:49:57 +0000151 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000152 "No conversion",
153 "Lvalue-to-rvalue",
154 "Array-to-pointer",
155 "Function-to-pointer",
Richard Smith3c4f8d22016-10-16 17:54:23 +0000156 "Function pointer conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000157 "Qualification",
158 "Integral promotion",
159 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000160 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000161 "Integral conversion",
162 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000163 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000164 "Floating-integral conversion",
165 "Pointer conversion",
166 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000167 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000168 "Compatible-types conversion",
Douglas Gregor46188682010-05-18 22:42:18 +0000169 "Derived-to-base conversion",
170 "Vector conversion",
171 "Vector splat",
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000172 "Complex-real conversion",
173 "Block Pointer conversion",
Sylvestre Ledru55635ce2014-11-17 19:41:49 +0000174 "Transparent Union Conversion",
George Burgess IV45461812015-10-11 20:13:20 +0000175 "Writeback conversion",
176 "OpenCL Zero Event Conversion",
George Burgess IV2099b542016-09-02 22:59:57 +0000177 "C specific type conversion",
178 "Incompatible pointer conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000179 };
180 return Name[Kind];
181}
182
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000183/// StandardConversionSequence - Set the standard conversion
184/// sequence to the identity conversion.
185void StandardConversionSequence::setAsIdentityConversion() {
186 First = ICK_Identity;
187 Second = ICK_Identity;
188 Third = ICK_Identity;
Douglas Gregore489a7d2010-02-28 18:30:25 +0000189 DeprecatedStringLiteralToCharPtr = false;
John McCall31168b02011-06-15 23:02:42 +0000190 QualificationIncludesObjCLifetime = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000191 ReferenceBinding = false;
192 DirectBinding = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +0000193 IsLvalueReference = true;
194 BindsToFunctionLvalue = false;
195 BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +0000196 BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +0000197 ObjCLifetimeConversionBinding = false;
Craig Topperc3ec1492014-05-26 06:22:03 +0000198 CopyConstructor = nullptr;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000199}
200
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000201/// getRank - Retrieve the rank of this standard conversion sequence
202/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
203/// implicit conversions.
204ImplicitConversionRank StandardConversionSequence::getRank() const {
205 ImplicitConversionRank Rank = ICR_Exact_Match;
206 if (GetConversionRank(First) > Rank)
207 Rank = GetConversionRank(First);
208 if (GetConversionRank(Second) > Rank)
209 Rank = GetConversionRank(Second);
210 if (GetConversionRank(Third) > Rank)
211 Rank = GetConversionRank(Third);
212 return Rank;
213}
214
215/// isPointerConversionToBool - Determines whether this conversion is
216/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump11289f42009-09-09 15:08:12 +0000217/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000218/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000219bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000220 // Note that FromType has not necessarily been transformed by the
221 // array-to-pointer or function-to-pointer implicit conversions, so
222 // check for their presence as well as checking whether FromType is
223 // a pointer.
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000224 if (getToType(1)->isBooleanType() &&
John McCall6d1116a2010-06-11 10:04:22 +0000225 (getFromType()->isPointerType() ||
226 getFromType()->isObjCObjectPointerType() ||
227 getFromType()->isBlockPointerType() ||
Anders Carlsson7da7cc52010-11-05 00:12:09 +0000228 getFromType()->isNullPtrType() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000229 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
230 return true;
231
232 return false;
233}
234
Douglas Gregor5c407d92008-10-23 00:40:37 +0000235/// isPointerConversionToVoidPointer - Determines whether this
236/// conversion is a conversion of a pointer to a void pointer. This is
237/// used as part of the ranking of standard conversion sequences (C++
238/// 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000239bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000240StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000241isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall0d1da222010-01-12 00:44:57 +0000242 QualType FromType = getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000243 QualType ToType = getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +0000244
245 // Note that FromType has not necessarily been transformed by the
246 // array-to-pointer implicit conversion, so check for its presence
247 // and redo the conversion to get a pointer.
248 if (First == ICK_Array_To_Pointer)
249 FromType = Context.getArrayDecayedType(FromType);
250
Douglas Gregor5d3d3fa2011-04-15 20:45:44 +0000251 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000252 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000253 return ToPtrType->getPointeeType()->isVoidType();
254
255 return false;
256}
257
Richard Smith66e05fe2012-01-18 05:21:49 +0000258/// Skip any implicit casts which could be either part of a narrowing conversion
259/// or after one in an implicit conversion.
260static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
261 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
262 switch (ICE->getCastKind()) {
263 case CK_NoOp:
264 case CK_IntegralCast:
265 case CK_IntegralToBoolean:
266 case CK_IntegralToFloating:
George Burgess IVdf1ed002016-01-13 01:52:39 +0000267 case CK_BooleanToSignedIntegral:
Richard Smith66e05fe2012-01-18 05:21:49 +0000268 case CK_FloatingToIntegral:
269 case CK_FloatingToBoolean:
270 case CK_FloatingCast:
271 Converted = ICE->getSubExpr();
272 continue;
273
274 default:
275 return Converted;
276 }
277 }
278
279 return Converted;
280}
281
282/// Check if this standard conversion sequence represents a narrowing
283/// conversion, according to C++11 [dcl.init.list]p7.
284///
285/// \param Ctx The AST context.
286/// \param Converted The result of applying this standard conversion sequence.
287/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
288/// value of the expression prior to the narrowing conversion.
Richard Smith5614ca72012-03-23 23:55:39 +0000289/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
290/// type of the expression prior to the narrowing conversion.
Richard Smith66e05fe2012-01-18 05:21:49 +0000291NarrowingKind
Richard Smithf8379a02012-01-18 23:55:52 +0000292StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
293 const Expr *Converted,
Richard Smith5614ca72012-03-23 23:55:39 +0000294 APValue &ConstantValue,
295 QualType &ConstantType) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000296 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
Richard Smith66e05fe2012-01-18 05:21:49 +0000297
298 // C++11 [dcl.init.list]p7:
299 // A narrowing conversion is an implicit conversion ...
300 QualType FromType = getToType(0);
301 QualType ToType = getToType(1);
Richard Smithed638862016-03-28 06:08:37 +0000302
303 // A conversion to an enumeration type is narrowing if the conversion to
304 // the underlying type is narrowing. This only arises for expressions of
305 // the form 'Enum{init}'.
306 if (auto *ET = ToType->getAs<EnumType>())
307 ToType = ET->getDecl()->getIntegerType();
308
Richard Smith66e05fe2012-01-18 05:21:49 +0000309 switch (Second) {
Richard Smith64ecacf2015-02-19 00:39:05 +0000310 // 'bool' is an integral type; dispatch to the right place to handle it.
311 case ICK_Boolean_Conversion:
312 if (FromType->isRealFloatingType())
313 goto FloatingIntegralConversion;
314 if (FromType->isIntegralOrUnscopedEnumerationType())
315 goto IntegralConversion;
316 // Boolean conversions can be from pointers and pointers to members
317 // [conv.bool], and those aren't considered narrowing conversions.
318 return NK_Not_Narrowing;
319
Richard Smith66e05fe2012-01-18 05:21:49 +0000320 // -- from a floating-point type to an integer type, or
321 //
322 // -- from an integer type or unscoped enumeration type to a floating-point
323 // type, except where the source is a constant expression and the actual
324 // value after conversion will fit into the target type and will produce
325 // the original value when converted back to the original type, or
326 case ICK_Floating_Integral:
Richard Smith64ecacf2015-02-19 00:39:05 +0000327 FloatingIntegralConversion:
Richard Smith66e05fe2012-01-18 05:21:49 +0000328 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
329 return NK_Type_Narrowing;
330 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
331 llvm::APSInt IntConstantValue;
332 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
Simon Pilgrimf9409872017-06-01 18:13:02 +0000333 assert(Initializer && "Unknown conversion expression");
Richard Smith52e624f2016-12-21 21:42:57 +0000334
335 // If it's value-dependent, we can't tell whether it's narrowing.
336 if (Initializer->isValueDependent())
337 return NK_Dependent_Narrowing;
338
Simon Pilgrimf9409872017-06-01 18:13:02 +0000339 if (Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
Richard Smith66e05fe2012-01-18 05:21:49 +0000340 // Convert the integer to the floating type.
341 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
342 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
343 llvm::APFloat::rmNearestTiesToEven);
344 // And back.
345 llvm::APSInt ConvertedValue = IntConstantValue;
346 bool ignored;
347 Result.convertToInteger(ConvertedValue,
348 llvm::APFloat::rmTowardZero, &ignored);
349 // If the resulting value is different, this was a narrowing conversion.
350 if (IntConstantValue != ConvertedValue) {
351 ConstantValue = APValue(IntConstantValue);
Richard Smith5614ca72012-03-23 23:55:39 +0000352 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000353 return NK_Constant_Narrowing;
354 }
355 } else {
356 // Variables are always narrowings.
357 return NK_Variable_Narrowing;
358 }
359 }
360 return NK_Not_Narrowing;
361
362 // -- from long double to double or float, or from double to float, except
363 // where the source is a constant expression and the actual value after
364 // conversion is within the range of values that can be represented (even
365 // if it cannot be represented exactly), or
366 case ICK_Floating_Conversion:
367 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
368 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
369 // FromType is larger than ToType.
370 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
Richard Smith52e624f2016-12-21 21:42:57 +0000371
372 // If it's value-dependent, we can't tell whether it's narrowing.
373 if (Initializer->isValueDependent())
374 return NK_Dependent_Narrowing;
375
Richard Smith66e05fe2012-01-18 05:21:49 +0000376 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
377 // Constant!
378 assert(ConstantValue.isFloat());
379 llvm::APFloat FloatVal = ConstantValue.getFloat();
380 // Convert the source value into the target type.
381 bool ignored;
382 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
383 Ctx.getFloatTypeSemantics(ToType),
384 llvm::APFloat::rmNearestTiesToEven, &ignored);
385 // If there was no overflow, the source value is within the range of
386 // values that can be represented.
Richard Smith5614ca72012-03-23 23:55:39 +0000387 if (ConvertStatus & llvm::APFloat::opOverflow) {
388 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000389 return NK_Constant_Narrowing;
Richard Smith5614ca72012-03-23 23:55:39 +0000390 }
Richard Smith66e05fe2012-01-18 05:21:49 +0000391 } else {
392 return NK_Variable_Narrowing;
393 }
394 }
395 return NK_Not_Narrowing;
396
397 // -- from an integer type or unscoped enumeration type to an integer type
398 // that cannot represent all the values of the original type, except where
399 // the source is a constant expression and the actual value after
400 // conversion will fit into the target type and will produce the original
401 // value when converted back to the original type.
Richard Smith64ecacf2015-02-19 00:39:05 +0000402 case ICK_Integral_Conversion:
403 IntegralConversion: {
Richard Smith66e05fe2012-01-18 05:21:49 +0000404 assert(FromType->isIntegralOrUnscopedEnumerationType());
405 assert(ToType->isIntegralOrUnscopedEnumerationType());
406 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
407 const unsigned FromWidth = Ctx.getIntWidth(FromType);
408 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
409 const unsigned ToWidth = Ctx.getIntWidth(ToType);
410
411 if (FromWidth > ToWidth ||
Richard Smith25a80d42012-06-13 01:07:41 +0000412 (FromWidth == ToWidth && FromSigned != ToSigned) ||
413 (FromSigned && !ToSigned)) {
Richard Smith66e05fe2012-01-18 05:21:49 +0000414 // Not all values of FromType can be represented in ToType.
415 llvm::APSInt InitializerValue;
416 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
Richard Smith52e624f2016-12-21 21:42:57 +0000417
418 // If it's value-dependent, we can't tell whether it's narrowing.
419 if (Initializer->isValueDependent())
420 return NK_Dependent_Narrowing;
421
Richard Smith25a80d42012-06-13 01:07:41 +0000422 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
423 // Such conversions on variables are always narrowing.
424 return NK_Variable_Narrowing;
Richard Smith72cd8ea2012-06-19 21:28:35 +0000425 }
426 bool Narrowing = false;
427 if (FromWidth < ToWidth) {
Richard Smith25a80d42012-06-13 01:07:41 +0000428 // Negative -> unsigned is narrowing. Otherwise, more bits is never
429 // narrowing.
430 if (InitializerValue.isSigned() && InitializerValue.isNegative())
Richard Smith72cd8ea2012-06-19 21:28:35 +0000431 Narrowing = true;
Richard Smith25a80d42012-06-13 01:07:41 +0000432 } else {
Richard Smith66e05fe2012-01-18 05:21:49 +0000433 // Add a bit to the InitializerValue so we don't have to worry about
434 // signed vs. unsigned comparisons.
435 InitializerValue = InitializerValue.extend(
436 InitializerValue.getBitWidth() + 1);
437 // Convert the initializer to and from the target width and signed-ness.
438 llvm::APSInt ConvertedValue = InitializerValue;
439 ConvertedValue = ConvertedValue.trunc(ToWidth);
440 ConvertedValue.setIsSigned(ToSigned);
441 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
442 ConvertedValue.setIsSigned(InitializerValue.isSigned());
443 // If the result is different, this was a narrowing conversion.
Richard Smith72cd8ea2012-06-19 21:28:35 +0000444 if (ConvertedValue != InitializerValue)
445 Narrowing = true;
446 }
447 if (Narrowing) {
448 ConstantType = Initializer->getType();
449 ConstantValue = APValue(InitializerValue);
450 return NK_Constant_Narrowing;
Richard Smith66e05fe2012-01-18 05:21:49 +0000451 }
452 }
453 return NK_Not_Narrowing;
454 }
455
456 default:
457 // Other kinds of conversions are not narrowings.
458 return NK_Not_Narrowing;
459 }
460}
461
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000462/// dump - Print this standard conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000463/// error. Useful for debugging overloading issues.
Yaron Kerencdae9412016-01-29 19:38:18 +0000464LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000465 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000466 bool PrintedSomething = false;
467 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000468 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000469 PrintedSomething = true;
470 }
471
472 if (Second != 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(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000477
478 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000479 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000480 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000481 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000482 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000483 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000484 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000485 PrintedSomething = true;
486 }
487
488 if (Third != ICK_Identity) {
489 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000490 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000491 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000492 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000493 PrintedSomething = true;
494 }
495
496 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000497 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000498 }
499}
500
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000501/// dump - Print this user-defined conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000502/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000503void UserDefinedConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000504 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000505 if (Before.First || Before.Second || Before.Third) {
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000506 Before.dump();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000507 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000508 }
Sebastian Redl72ef7bc2011-11-01 15:53:09 +0000509 if (ConversionFunction)
510 OS << '\'' << *ConversionFunction << '\'';
511 else
512 OS << "aggregate initialization";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000513 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000514 OS << " -> ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000515 After.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000516 }
517}
518
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000519/// dump - Print this implicit conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000520/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000521void ImplicitConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000522 raw_ostream &OS = llvm::errs();
Richard Smitha93f1022013-09-06 22:30:28 +0000523 if (isStdInitializerListElement())
524 OS << "Worst std::initializer_list element conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000525 switch (ConversionKind) {
526 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000527 OS << "Standard conversion: ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000528 Standard.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000529 break;
530 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000531 OS << "User-defined conversion: ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000532 UserDefined.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000533 break;
534 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000535 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000536 break;
John McCall0d1da222010-01-12 00:44:57 +0000537 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000538 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000539 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000540 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000541 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000542 break;
543 }
544
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000545 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000546}
547
John McCall0d1da222010-01-12 00:44:57 +0000548void AmbiguousConversionSequence::construct() {
549 new (&conversions()) ConversionSet();
550}
551
552void AmbiguousConversionSequence::destruct() {
553 conversions().~ConversionSet();
554}
555
556void
557AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
558 FromTypePtr = O.FromTypePtr;
559 ToTypePtr = O.ToTypePtr;
560 new (&conversions()) ConversionSet(O.conversions());
561}
562
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000563namespace {
Larisse Voufo98b20f12013-07-19 23:00:19 +0000564 // Structure used by DeductionFailureInfo to store
Richard Smith44ecdbd2013-01-31 05:19:49 +0000565 // template argument information.
566 struct DFIArguments {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000567 TemplateArgument FirstArg;
568 TemplateArgument SecondArg;
569 };
Larisse Voufo98b20f12013-07-19 23:00:19 +0000570 // Structure used by DeductionFailureInfo to store
Richard Smith44ecdbd2013-01-31 05:19:49 +0000571 // template parameter and template argument information.
572 struct DFIParamWithArguments : DFIArguments {
573 TemplateParameter Param;
574 };
Richard Smith9b534542015-12-31 02:02:54 +0000575 // Structure used by DeductionFailureInfo to store template argument
576 // information and the index of the problematic call argument.
577 struct DFIDeducedMismatchArgs : DFIArguments {
578 TemplateArgumentList *TemplateArgs;
579 unsigned CallArgIndex;
580 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000581}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000582
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000583/// \brief Convert from Sema's representation of template deduction information
584/// to the form used in overload-candidate information.
Richard Smith17c00b42014-11-12 01:24:00 +0000585DeductionFailureInfo
586clang::MakeDeductionFailureInfo(ASTContext &Context,
587 Sema::TemplateDeductionResult TDK,
588 TemplateDeductionInfo &Info) {
Larisse Voufo98b20f12013-07-19 23:00:19 +0000589 DeductionFailureInfo Result;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000590 Result.Result = static_cast<unsigned>(TDK);
Richard Smith9ca64612012-05-07 09:03:25 +0000591 Result.HasDiagnostic = false;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000592 switch (TDK) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000593 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000594 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000595 case Sema::TDK_TooManyArguments:
596 case Sema::TDK_TooFewArguments:
Richard Smith9b534542015-12-31 02:02:54 +0000597 case Sema::TDK_MiscellaneousDeductionFailure:
Artem Belevich13e9b4d2016-12-07 19:27:16 +0000598 case Sema::TDK_CUDATargetMismatch:
Richard Smith9b534542015-12-31 02:02:54 +0000599 Result.Data = nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000600 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000601
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000602 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000603 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000604 Result.Data = Info.Param.getOpaqueValue();
605 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000606
Richard Smithc92d2062017-01-05 23:02:44 +0000607 case Sema::TDK_DeducedMismatch:
608 case Sema::TDK_DeducedMismatchNested: {
Richard Smith9b534542015-12-31 02:02:54 +0000609 // FIXME: Should allocate from normal heap so that we can free this later.
610 auto *Saved = new (Context) DFIDeducedMismatchArgs;
611 Saved->FirstArg = Info.FirstArg;
612 Saved->SecondArg = Info.SecondArg;
613 Saved->TemplateArgs = Info.take();
614 Saved->CallArgIndex = Info.CallArgIndex;
615 Result.Data = Saved;
616 break;
617 }
618
Richard Smith44ecdbd2013-01-31 05:19:49 +0000619 case Sema::TDK_NonDeducedMismatch: {
620 // FIXME: Should allocate from normal heap so that we can free this later.
621 DFIArguments *Saved = new (Context) DFIArguments;
622 Saved->FirstArg = Info.FirstArg;
623 Saved->SecondArg = Info.SecondArg;
624 Result.Data = Saved;
625 break;
626 }
627
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000628 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000629 case Sema::TDK_Underqualified: {
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000630 // FIXME: Should allocate from normal heap so that we can free this later.
631 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000632 Saved->Param = Info.Param;
633 Saved->FirstArg = Info.FirstArg;
634 Saved->SecondArg = Info.SecondArg;
635 Result.Data = Saved;
636 break;
637 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000638
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000639 case Sema::TDK_SubstitutionFailure:
Douglas Gregord09efd42010-05-08 20:07:26 +0000640 Result.Data = Info.take();
Richard Smith9ca64612012-05-07 09:03:25 +0000641 if (Info.hasSFINAEDiagnostic()) {
642 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
643 SourceLocation(), PartialDiagnostic::NullDiagnostic());
644 Info.takeSFINAEDiagnostic(*Diag);
645 Result.HasDiagnostic = true;
646 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000647 break;
Richard Smith6eedfe72017-01-09 08:01:21 +0000648
649 case Sema::TDK_Success:
650 case Sema::TDK_NonDependentConversionFailure:
651 llvm_unreachable("not a deduction failure");
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000652 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000653
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000654 return Result;
655}
John McCall0d1da222010-01-12 00:44:57 +0000656
Larisse Voufo98b20f12013-07-19 23:00:19 +0000657void DeductionFailureInfo::Destroy() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000658 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
659 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000660 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000661 case Sema::TDK_InstantiationDepth:
662 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000663 case Sema::TDK_TooManyArguments:
664 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000665 case Sema::TDK_InvalidExplicitArguments:
Artem Belevich13e9b4d2016-12-07 19:27:16 +0000666 case Sema::TDK_CUDATargetMismatch:
Richard Smith6eedfe72017-01-09 08:01:21 +0000667 case Sema::TDK_NonDependentConversionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000668 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000669
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000670 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000671 case Sema::TDK_Underqualified:
Richard Smith9b534542015-12-31 02:02:54 +0000672 case Sema::TDK_DeducedMismatch:
Richard Smithc92d2062017-01-05 23:02:44 +0000673 case Sema::TDK_DeducedMismatchNested:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000674 case Sema::TDK_NonDeducedMismatch:
Douglas Gregorb02d6b32010-05-08 20:20:05 +0000675 // FIXME: Destroy the data?
Craig Topperc3ec1492014-05-26 06:22:03 +0000676 Data = nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000677 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000678
679 case Sema::TDK_SubstitutionFailure:
Richard Smith9ca64612012-05-07 09:03:25 +0000680 // FIXME: Destroy the template argument list?
Craig Topperc3ec1492014-05-26 06:22:03 +0000681 Data = nullptr;
Richard Smith9ca64612012-05-07 09:03:25 +0000682 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
683 Diag->~PartialDiagnosticAt();
684 HasDiagnostic = false;
685 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000686 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000687
Douglas Gregor461761d2010-05-08 18:20:53 +0000688 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000689 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000690 break;
691 }
692}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000693
Larisse Voufo98b20f12013-07-19 23:00:19 +0000694PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
Richard Smith9ca64612012-05-07 09:03:25 +0000695 if (HasDiagnostic)
696 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
Craig Topperc3ec1492014-05-26 06:22:03 +0000697 return nullptr;
Richard Smith9ca64612012-05-07 09:03:25 +0000698}
699
Larisse Voufo98b20f12013-07-19 23:00:19 +0000700TemplateParameter DeductionFailureInfo::getTemplateParameter() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000701 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
702 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000703 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000704 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000705 case Sema::TDK_TooManyArguments:
706 case Sema::TDK_TooFewArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000707 case Sema::TDK_SubstitutionFailure:
Richard Smith9b534542015-12-31 02:02:54 +0000708 case Sema::TDK_DeducedMismatch:
Richard Smithc92d2062017-01-05 23:02:44 +0000709 case Sema::TDK_DeducedMismatchNested:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000710 case Sema::TDK_NonDeducedMismatch:
Artem Belevich13e9b4d2016-12-07 19:27:16 +0000711 case Sema::TDK_CUDATargetMismatch:
Richard Smith6eedfe72017-01-09 08:01:21 +0000712 case Sema::TDK_NonDependentConversionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000713 return TemplateParameter();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000714
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000715 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000716 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000717 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000718
719 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000720 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000721 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000722
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000723 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000724 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000725 break;
726 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000727
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000728 return TemplateParameter();
729}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000730
Larisse Voufo98b20f12013-07-19 23:00:19 +0000731TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
Douglas Gregord09efd42010-05-08 20:07:26 +0000732 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
Richard Smith44ecdbd2013-01-31 05:19:49 +0000733 case Sema::TDK_Success:
734 case Sema::TDK_Invalid:
735 case Sema::TDK_InstantiationDepth:
736 case Sema::TDK_TooManyArguments:
737 case Sema::TDK_TooFewArguments:
738 case Sema::TDK_Incomplete:
739 case Sema::TDK_InvalidExplicitArguments:
740 case Sema::TDK_Inconsistent:
741 case Sema::TDK_Underqualified:
742 case Sema::TDK_NonDeducedMismatch:
Artem Belevich13e9b4d2016-12-07 19:27:16 +0000743 case Sema::TDK_CUDATargetMismatch:
Richard Smith6eedfe72017-01-09 08:01:21 +0000744 case Sema::TDK_NonDependentConversionFailure:
Craig Topperc3ec1492014-05-26 06:22:03 +0000745 return nullptr;
Douglas Gregord09efd42010-05-08 20:07:26 +0000746
Richard Smith9b534542015-12-31 02:02:54 +0000747 case Sema::TDK_DeducedMismatch:
Richard Smithc92d2062017-01-05 23:02:44 +0000748 case Sema::TDK_DeducedMismatchNested:
Richard Smith9b534542015-12-31 02:02:54 +0000749 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
750
Richard Smith44ecdbd2013-01-31 05:19:49 +0000751 case Sema::TDK_SubstitutionFailure:
752 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000753
Richard Smith44ecdbd2013-01-31 05:19:49 +0000754 // Unhandled
755 case Sema::TDK_MiscellaneousDeductionFailure:
756 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000757 }
758
Craig Topperc3ec1492014-05-26 06:22:03 +0000759 return nullptr;
Douglas Gregord09efd42010-05-08 20:07:26 +0000760}
761
Larisse Voufo98b20f12013-07-19 23:00:19 +0000762const TemplateArgument *DeductionFailureInfo::getFirstArg() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000763 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
764 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000765 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000766 case Sema::TDK_InstantiationDepth:
767 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000768 case Sema::TDK_TooManyArguments:
769 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000770 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000771 case Sema::TDK_SubstitutionFailure:
Artem Belevich13e9b4d2016-12-07 19:27:16 +0000772 case Sema::TDK_CUDATargetMismatch:
Richard Smith6eedfe72017-01-09 08:01:21 +0000773 case Sema::TDK_NonDependentConversionFailure:
Craig Topperc3ec1492014-05-26 06:22:03 +0000774 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000775
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000776 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000777 case Sema::TDK_Underqualified:
Richard Smith9b534542015-12-31 02:02:54 +0000778 case Sema::TDK_DeducedMismatch:
Richard Smithc92d2062017-01-05 23:02:44 +0000779 case Sema::TDK_DeducedMismatchNested:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000780 case Sema::TDK_NonDeducedMismatch:
781 return &static_cast<DFIArguments*>(Data)->FirstArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000782
Douglas Gregor461761d2010-05-08 18:20:53 +0000783 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000784 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000785 break;
786 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000787
Craig Topperc3ec1492014-05-26 06:22:03 +0000788 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000789}
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000790
Larisse Voufo98b20f12013-07-19 23:00:19 +0000791const TemplateArgument *DeductionFailureInfo::getSecondArg() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000792 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
793 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000794 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000795 case Sema::TDK_InstantiationDepth:
796 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000797 case Sema::TDK_TooManyArguments:
798 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000799 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000800 case Sema::TDK_SubstitutionFailure:
Artem Belevich13e9b4d2016-12-07 19:27:16 +0000801 case Sema::TDK_CUDATargetMismatch:
Richard Smith6eedfe72017-01-09 08:01:21 +0000802 case Sema::TDK_NonDependentConversionFailure:
Craig Topperc3ec1492014-05-26 06:22:03 +0000803 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000804
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000805 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000806 case Sema::TDK_Underqualified:
Richard Smith9b534542015-12-31 02:02:54 +0000807 case Sema::TDK_DeducedMismatch:
Richard Smithc92d2062017-01-05 23:02:44 +0000808 case Sema::TDK_DeducedMismatchNested:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000809 case Sema::TDK_NonDeducedMismatch:
810 return &static_cast<DFIArguments*>(Data)->SecondArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000811
Douglas Gregor461761d2010-05-08 18:20:53 +0000812 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000813 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000814 break;
815 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000816
Craig Topperc3ec1492014-05-26 06:22:03 +0000817 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000818}
819
Richard Smith9b534542015-12-31 02:02:54 +0000820llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
Richard Smithc92d2062017-01-05 23:02:44 +0000821 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
822 case Sema::TDK_DeducedMismatch:
823 case Sema::TDK_DeducedMismatchNested:
Richard Smith9b534542015-12-31 02:02:54 +0000824 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
825
Richard Smithc92d2062017-01-05 23:02:44 +0000826 default:
827 return llvm::None;
828 }
Richard Smith9b534542015-12-31 02:02:54 +0000829}
830
Benjamin Kramer97e59492012-10-09 15:52:25 +0000831void OverloadCandidateSet::destroyCandidates() {
Richard Smith0bf93aa2012-07-18 23:52:59 +0000832 for (iterator i = begin(), e = end(); i != e; ++i) {
Richard Smith6eedfe72017-01-09 08:01:21 +0000833 for (auto &C : i->Conversions)
834 C.~ImplicitConversionSequence();
Richard Smith0bf93aa2012-07-18 23:52:59 +0000835 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
836 i->DeductionFailure.Destroy();
837 }
Benjamin Kramer97e59492012-10-09 15:52:25 +0000838}
839
Richard Smith67ef14f2017-09-26 18:37:55 +0000840void OverloadCandidateSet::clear(CandidateSetKind CSK) {
Benjamin Kramer97e59492012-10-09 15:52:25 +0000841 destroyCandidates();
George Burgess IV177399e2017-01-09 04:12:14 +0000842 SlabAllocator.Reset();
843 NumInlineBytesUsed = 0;
Benjamin Kramerfb761ff2012-01-14 16:31:55 +0000844 Candidates.clear();
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000845 Functions.clear();
Richard Smith67ef14f2017-09-26 18:37:55 +0000846 Kind = CSK;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000847}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000848
John McCall4124c492011-10-17 18:40:02 +0000849namespace {
850 class UnbridgedCastsSet {
851 struct Entry {
852 Expr **Addr;
853 Expr *Saved;
854 };
855 SmallVector<Entry, 2> Entries;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +0000856
John McCall4124c492011-10-17 18:40:02 +0000857 public:
858 void save(Sema &S, Expr *&E) {
859 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
860 Entry entry = { &E, E };
861 Entries.push_back(entry);
862 E = S.stripARCUnbridgedCast(E);
863 }
864
865 void restore() {
866 for (SmallVectorImpl<Entry>::iterator
Simon Pilgrimfb9662a2017-06-01 18:17:18 +0000867 i = Entries.begin(), e = Entries.end(); i != e; ++i)
John McCall4124c492011-10-17 18:40:02 +0000868 *i->Addr = i->Saved;
869 }
870 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000871}
John McCall4124c492011-10-17 18:40:02 +0000872
873/// checkPlaceholderForOverload - Do any interesting placeholder-like
874/// preprocessing on the given expression.
875///
876/// \param unbridgedCasts a collection to which to add unbridged casts;
877/// without this, they will be immediately diagnosed as errors
878///
879/// Return true on unrecoverable error.
Craig Topperc3ec1492014-05-26 06:22:03 +0000880static bool
881checkPlaceholderForOverload(Sema &S, Expr *&E,
882 UnbridgedCastsSet *unbridgedCasts = nullptr) {
John McCall4124c492011-10-17 18:40:02 +0000883 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
884 // We can't handle overloaded expressions here because overload
885 // resolution might reasonably tweak them.
886 if (placeholder->getKind() == BuiltinType::Overload) return false;
887
888 // If the context potentially accepts unbridged ARC casts, strip
889 // the unbridged cast and add it to the collection for later restoration.
890 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
891 unbridgedCasts) {
892 unbridgedCasts->save(S, E);
893 return false;
894 }
895
896 // Go ahead and check everything else.
897 ExprResult result = S.CheckPlaceholderExpr(E);
898 if (result.isInvalid())
899 return true;
900
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000901 E = result.get();
John McCall4124c492011-10-17 18:40:02 +0000902 return false;
903 }
904
905 // Nothing to do.
906 return false;
907}
908
909/// checkArgPlaceholdersForOverload - Check a set of call operands for
910/// placeholders.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000911static bool checkArgPlaceholdersForOverload(Sema &S,
912 MultiExprArg Args,
John McCall4124c492011-10-17 18:40:02 +0000913 UnbridgedCastsSet &unbridged) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000914 for (unsigned i = 0, e = Args.size(); i != e; ++i)
915 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
John McCall4124c492011-10-17 18:40:02 +0000916 return true;
917
918 return false;
919}
920
George Burgess IV2d82b092017-04-06 00:23:31 +0000921/// Determine whether the given New declaration is an overload of the
922/// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if
923/// New and Old cannot be overloaded, e.g., if New has the same signature as
924/// some function in Old (C++ 1.3.10) or if the Old declarations aren't
925/// functions (or function templates) at all. When it does return Ovl_Match or
926/// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be
927/// overloaded with. This decl may be a UsingShadowDecl on top of the underlying
928/// declaration.
929///
930/// Example: Given the following input:
931///
932/// void f(int, float); // #1
933/// void f(int, int); // #2
934/// int f(int, int); // #3
935///
936/// When we process #1, there is no previous declaration of "f", so IsOverload
937/// will not be used.
938///
939/// When we process #2, Old contains only the FunctionDecl for #1. By comparing
940/// the parameter types, we see that #1 and #2 are overloaded (since they have
941/// different signatures), so this routine returns Ovl_Overload; MatchedDecl is
942/// unchanged.
943///
944/// When we process #3, Old is an overload set containing #1 and #2. We compare
945/// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then
946/// #3 to #2. Since the signatures of #3 and #2 are identical (return types of
947/// functions are not part of the signature), IsOverload returns Ovl_Match and
948/// MatchedDecl will be set to point to the FunctionDecl for #2.
949///
950/// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class
951/// by a using declaration. The rules for whether to hide shadow declarations
952/// ignore some properties which otherwise figure into a function template's
953/// signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000954Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000955Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
956 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000957 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000958 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000959 NamedDecl *OldD = *I;
960
961 bool OldIsUsingDecl = false;
962 if (isa<UsingShadowDecl>(OldD)) {
963 OldIsUsingDecl = true;
964
965 // We can always introduce two using declarations into the same
966 // context, even if they have identical signatures.
967 if (NewIsUsingDecl) continue;
968
969 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
970 }
971
Richard Smithf091e122015-09-15 01:28:55 +0000972 // A using-declaration does not conflict with another declaration
973 // if one of them is hidden.
974 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
975 continue;
976
John McCalle9cccd82010-06-16 08:42:20 +0000977 // If either declaration was introduced by a using declaration,
978 // we'll need to use slightly different rules for matching.
979 // Essentially, these rules are the normal rules, except that
980 // function templates hide function templates with different
981 // return types or template parameter lists.
982 bool UseMemberUsingDeclRules =
John McCallc70fca62013-04-03 21:19:47 +0000983 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
984 !New->getFriendObjectKind();
John McCalle9cccd82010-06-16 08:42:20 +0000985
Alp Tokera2794f92014-01-22 07:29:52 +0000986 if (FunctionDecl *OldF = OldD->getAsFunction()) {
John McCalle9cccd82010-06-16 08:42:20 +0000987 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
988 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
989 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
990 continue;
991 }
992
Alp Tokera2794f92014-01-22 07:29:52 +0000993 if (!isa<FunctionTemplateDecl>(OldD) &&
994 !shouldLinkPossiblyHiddenDecl(*I, New))
Rafael Espindola5bddd6a2013-04-15 12:49:13 +0000995 continue;
996
John McCalldaa3d6b2009-12-09 03:35:25 +0000997 Match = *I;
998 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000999 }
Richard Smith151c4562016-12-20 21:35:28 +00001000 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +00001001 // We can overload with these, which can show up when doing
1002 // redeclaration checks for UsingDecls.
1003 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalla8987a2942010-11-10 03:01:53 +00001004 } else if (isa<TagDecl>(OldD)) {
1005 // We can always overload with tags by hiding them.
Richard Smithd8a9e372016-12-18 21:39:37 +00001006 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +00001007 // Optimistically assume that an unresolved using decl will
1008 // overload; if it doesn't, we'll have to diagnose during
1009 // template instantiation.
Richard Smithd8a9e372016-12-18 21:39:37 +00001010 //
1011 // Exception: if the scope is dependent and this is not a class
1012 // member, the using declaration can only introduce an enumerator.
1013 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1014 Match = *I;
1015 return Ovl_NonFunction;
1016 }
John McCall84d87672009-12-10 09:41:52 +00001017 } else {
John McCall1f82f242009-11-18 22:49:29 +00001018 // (C++ 13p1):
1019 // Only function declarations can be overloaded; object and type
1020 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +00001021 Match = *I;
1022 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +00001023 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001024 }
John McCall1f82f242009-11-18 22:49:29 +00001025
John McCalldaa3d6b2009-12-09 03:35:25 +00001026 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +00001027}
1028
Richard Smithac974a32013-06-30 09:48:50 +00001029bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
Justin Lebarba122ab2016-03-30 23:30:21 +00001030 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
Richard Smithac974a32013-06-30 09:48:50 +00001031 // C++ [basic.start.main]p2: This function shall not be overloaded.
1032 if (New->isMain())
Rafael Espindola576127d2012-12-28 14:21:58 +00001033 return false;
Rafael Espindola7cf35ef2013-01-12 01:47:40 +00001034
David Majnemerc729b0b2013-09-16 22:44:20 +00001035 // MSVCRT user defined entry points cannot be overloaded.
1036 if (New->isMSVCRTEntryPoint())
1037 return false;
1038
John McCall1f82f242009-11-18 22:49:29 +00001039 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1040 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1041
1042 // C++ [temp.fct]p2:
1043 // A function template can be overloaded with other function templates
1044 // and with normal (non-template) functions.
Craig Topperc3ec1492014-05-26 06:22:03 +00001045 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
John McCall1f82f242009-11-18 22:49:29 +00001046 return true;
1047
1048 // Is the function New an overload of the function Old?
Richard Smithac974a32013-06-30 09:48:50 +00001049 QualType OldQType = Context.getCanonicalType(Old->getType());
1050 QualType NewQType = Context.getCanonicalType(New->getType());
John McCall1f82f242009-11-18 22:49:29 +00001051
1052 // Compare the signatures (C++ 1.3.10) of the two functions to
1053 // determine whether they are overloads. If we find any mismatch
1054 // in the signature, they are overloads.
1055
1056 // If either of these functions is a K&R-style function (no
1057 // prototype), then we consider them to have matching signatures.
1058 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1059 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1060 return false;
1061
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001062 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1063 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
John McCall1f82f242009-11-18 22:49:29 +00001064
1065 // The signature of a function includes the types of its
1066 // parameters (C++ 1.3.10), which includes the presence or absence
1067 // of the ellipsis; see C++ DR 357).
1068 if (OldQType != NewQType &&
Alp Toker9cacbab2014-01-20 20:26:09 +00001069 (OldType->getNumParams() != NewType->getNumParams() ||
John McCall1f82f242009-11-18 22:49:29 +00001070 OldType->isVariadic() != NewType->isVariadic() ||
Alp Toker9cacbab2014-01-20 20:26:09 +00001071 !FunctionParamTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +00001072 return true;
1073
1074 // C++ [temp.over.link]p4:
1075 // The signature of a function template consists of its function
1076 // signature, its return type and its template parameter list. The names
1077 // of the template parameters are significant only for establishing the
1078 // relationship between the template parameters and the rest of the
1079 // signature.
1080 //
1081 // We check the return type and template parameter lists for function
1082 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +00001083 //
1084 // However, we don't consider either of these when deciding whether
1085 // a member introduced by a shadow declaration is hidden.
Justin Lebar39fd5292016-03-30 20:41:05 +00001086 if (!UseMemberUsingDeclRules && NewTemplate &&
Richard Smithac974a32013-06-30 09:48:50 +00001087 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1088 OldTemplate->getTemplateParameters(),
1089 false, TPL_TemplateMatch) ||
Alp Toker314cc812014-01-25 16:55:45 +00001090 OldType->getReturnType() != NewType->getReturnType()))
John McCall1f82f242009-11-18 22:49:29 +00001091 return true;
1092
1093 // If the function is a class member, its signature includes the
Douglas Gregorb2f8aa92011-01-26 17:47:49 +00001094 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall1f82f242009-11-18 22:49:29 +00001095 //
1096 // As part of this, also check whether one of the member functions
1097 // is static, in which case they are not overloads (C++
1098 // 13.1p2). While not part of the definition of the signature,
1099 // this check is important to determine whether these functions
1100 // can be overloaded.
Richard Smith574f4f62013-01-14 05:37:29 +00001101 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1102 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
John McCall1f82f242009-11-18 22:49:29 +00001103 if (OldMethod && NewMethod &&
Richard Smith574f4f62013-01-14 05:37:29 +00001104 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1105 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
Justin Lebar39fd5292016-03-30 20:41:05 +00001106 if (!UseMemberUsingDeclRules &&
Richard Smith574f4f62013-01-14 05:37:29 +00001107 (OldMethod->getRefQualifier() == RQ_None ||
1108 NewMethod->getRefQualifier() == RQ_None)) {
1109 // C++0x [over.load]p2:
1110 // - Member function declarations with the same name and the same
1111 // parameter-type-list as well as member function template
1112 // declarations with the same name, the same parameter-type-list, and
1113 // the same template parameter lists cannot be overloaded if any of
1114 // them, but not all, have a ref-qualifier (8.3.5).
Richard Smithac974a32013-06-30 09:48:50 +00001115 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
Richard Smith574f4f62013-01-14 05:37:29 +00001116 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
Richard Smithac974a32013-06-30 09:48:50 +00001117 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
Richard Smith574f4f62013-01-14 05:37:29 +00001118 }
1119 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001120 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001121
Richard Smith574f4f62013-01-14 05:37:29 +00001122 // We may not have applied the implicit const for a constexpr member
1123 // function yet (because we haven't yet resolved whether this is a static
1124 // or non-static member function). Add it now, on the assumption that this
1125 // is a redeclaration of OldMethod.
David Majnemer42350df2013-11-03 23:51:28 +00001126 unsigned OldQuals = OldMethod->getTypeQualifiers();
Richard Smith574f4f62013-01-14 05:37:29 +00001127 unsigned NewQuals = NewMethod->getTypeQualifiers();
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001128 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
Richard Smithe83b1d32013-06-25 18:46:26 +00001129 !isa<CXXConstructorDecl>(NewMethod))
Richard Smith574f4f62013-01-14 05:37:29 +00001130 NewQuals |= Qualifiers::Const;
David Majnemer42350df2013-11-03 23:51:28 +00001131
1132 // We do not allow overloading based off of '__restrict'.
1133 OldQuals &= ~Qualifiers::Restrict;
1134 NewQuals &= ~Qualifiers::Restrict;
1135 if (OldQuals != NewQuals)
Richard Smith574f4f62013-01-14 05:37:29 +00001136 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001137 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001138
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001139 // Though pass_object_size is placed on parameters and takes an argument, we
1140 // consider it to be a function-level modifier for the sake of function
1141 // identity. Either the function has one or more parameters with
1142 // pass_object_size or it doesn't.
1143 if (functionHasPassObjectSizeParams(New) !=
1144 functionHasPassObjectSizeParams(Old))
1145 return true;
1146
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001147 // enable_if attributes are an order-sensitive part of the signature.
1148 for (specific_attr_iterator<EnableIfAttr>
1149 NewI = New->specific_attr_begin<EnableIfAttr>(),
1150 NewE = New->specific_attr_end<EnableIfAttr>(),
1151 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1152 OldE = Old->specific_attr_end<EnableIfAttr>();
1153 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1154 if (NewI == NewE || OldI == OldE)
1155 return true;
1156 llvm::FoldingSetNodeID NewID, OldID;
1157 NewI->getCond()->Profile(NewID, Context, true);
1158 OldI->getCond()->Profile(OldID, Context, true);
Nick Lewyckyd950ae72014-01-21 01:30:30 +00001159 if (NewID != OldID)
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001160 return true;
1161 }
1162
Justin Lebarba122ab2016-03-30 23:30:21 +00001163 if (getLangOpts().CUDA && ConsiderCudaAttrs) {
Justin Lebare060feb2016-10-03 16:48:23 +00001164 // Don't allow overloading of destructors. (In theory we could, but it
1165 // would be a giant change to clang.)
1166 if (isa<CXXDestructorDecl>(New))
1167 return false;
1168
Artem Belevich94a55e82015-09-22 17:22:59 +00001169 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1170 OldTarget = IdentifyCUDATarget(Old);
Artem Belevich13e9b4d2016-12-07 19:27:16 +00001171 if (NewTarget == CFT_InvalidTarget)
Artem Belevich94a55e82015-09-22 17:22:59 +00001172 return false;
1173
1174 assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target.");
1175
Justin Lebar53b000af2016-10-03 16:48:27 +00001176 // Allow overloading of functions with same signature and different CUDA
1177 // target attributes.
Artem Belevich94a55e82015-09-22 17:22:59 +00001178 return NewTarget != OldTarget;
1179 }
1180
John McCall1f82f242009-11-18 22:49:29 +00001181 // The signatures match; this is not an overload.
1182 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001183}
1184
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00001185/// \brief Checks availability of the function depending on the current
1186/// function context. Inside an unavailable function, unavailability is ignored.
1187///
1188/// \returns true if \arg FD is unavailable and current context is inside
1189/// an available function, false otherwise.
1190bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
Duncan P. N. Exon Smith85363922016-03-08 10:28:52 +00001191 if (!FD->isUnavailable())
1192 return false;
1193
1194 // Walk up the context of the caller.
1195 Decl *C = cast<Decl>(CurContext);
1196 do {
1197 if (C->isUnavailable())
1198 return false;
1199 } while ((C = cast_or_null<Decl>(C->getDeclContext())));
1200 return true;
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00001201}
1202
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001203/// \brief Tries a user-defined conversion from From to ToType.
1204///
1205/// Produces an implicit conversion sequence for when a standard conversion
1206/// is not an option. See TryImplicitConversion for more information.
1207static ImplicitConversionSequence
1208TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1209 bool SuppressUserConversions,
1210 bool AllowExplicit,
1211 bool InOverloadResolution,
1212 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001213 bool AllowObjCWritebackConversion,
1214 bool AllowObjCConversionOnExplicit) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001215 ImplicitConversionSequence ICS;
1216
1217 if (SuppressUserConversions) {
1218 // We're not in the case above, so there is no conversion that
1219 // we can perform.
1220 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1221 return ICS;
1222 }
1223
1224 // Attempt user-defined conversion.
Richard Smith100b24a2014-04-17 01:52:14 +00001225 OverloadCandidateSet Conversions(From->getExprLoc(),
1226 OverloadCandidateSet::CSK_Normal);
Richard Smith48372b62015-01-27 03:30:40 +00001227 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1228 Conversions, AllowExplicit,
1229 AllowObjCConversionOnExplicit)) {
1230 case OR_Success:
1231 case OR_Deleted:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001232 ICS.setUserDefined();
1233 // C++ [over.ics.user]p4:
1234 // A conversion of an expression of class type to the same class
1235 // type is given Exact Match rank, and a conversion of an
1236 // expression of class type to a base class of that type is
1237 // given Conversion rank, in spite of the fact that a copy
1238 // constructor (i.e., a user-defined conversion function) is
1239 // called for those cases.
1240 if (CXXConstructorDecl *Constructor
1241 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1242 QualType FromCanon
1243 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1244 QualType ToCanon
1245 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1246 if (Constructor->isCopyConstructor() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00001247 (FromCanon == ToCanon ||
1248 S.IsDerivedFrom(From->getLocStart(), FromCanon, ToCanon))) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001249 // Turn this into a "standard" conversion sequence, so that it
1250 // gets ranked with standard conversion sequences.
Richard Smithc2bebe92016-05-11 20:37:46 +00001251 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001252 ICS.setStandard();
1253 ICS.Standard.setAsIdentityConversion();
1254 ICS.Standard.setFromType(From->getType());
1255 ICS.Standard.setAllToTypes(ToType);
1256 ICS.Standard.CopyConstructor = Constructor;
Richard Smithc2bebe92016-05-11 20:37:46 +00001257 ICS.Standard.FoundCopyConstructor = Found;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001258 if (ToCanon != FromCanon)
1259 ICS.Standard.Second = ICK_Derived_To_Base;
1260 }
1261 }
Richard Smith48372b62015-01-27 03:30:40 +00001262 break;
1263
1264 case OR_Ambiguous:
Richard Smith1bbaba82015-01-27 23:23:39 +00001265 ICS.setAmbiguous();
1266 ICS.Ambiguous.setFromType(From->getType());
1267 ICS.Ambiguous.setToType(ToType);
1268 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1269 Cand != Conversions.end(); ++Cand)
1270 if (Cand->Viable)
Richard Smithc2bebe92016-05-11 20:37:46 +00001271 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
Richard Smith1bbaba82015-01-27 23:23:39 +00001272 break;
Richard Smith48372b62015-01-27 03:30:40 +00001273
1274 // Fall through.
1275 case OR_No_Viable_Function:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001276 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Richard Smith48372b62015-01-27 03:30:40 +00001277 break;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001278 }
1279
1280 return ICS;
1281}
1282
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001283/// TryImplicitConversion - Attempt to perform an implicit conversion
1284/// from the given expression (Expr) to the given type (ToType). This
1285/// function returns an implicit conversion sequence that can be used
1286/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001287///
1288/// void f(float f);
1289/// void g(int i) { f(i); }
1290///
1291/// this routine would produce an implicit conversion sequence to
1292/// describe the initialization of f from i, which will be a standard
1293/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1294/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1295//
1296/// Note that this routine only determines how the conversion can be
1297/// performed; it does not actually perform the conversion. As such,
1298/// it will not produce any diagnostics if no conversion is available,
1299/// but will instead return an implicit conversion sequence of kind
1300/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +00001301///
1302/// If @p SuppressUserConversions, then user-defined conversions are
1303/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +00001304/// If @p AllowExplicit, then explicit user-defined conversions are
1305/// permitted.
John McCall31168b02011-06-15 23:02:42 +00001306///
1307/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1308/// writeback conversion, which allows __autoreleasing id* parameters to
1309/// be initialized with __strong id* or __weak id* arguments.
John McCall5c32be02010-08-24 20:38:10 +00001310static ImplicitConversionSequence
1311TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1312 bool SuppressUserConversions,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001313 bool AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001314 bool InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001315 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001316 bool AllowObjCWritebackConversion,
1317 bool AllowObjCConversionOnExplicit) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001318 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +00001319 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001320 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall0d1da222010-01-12 00:44:57 +00001321 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +00001322 return ICS;
1323 }
1324
David Blaikiebbafb8a2012-03-11 07:00:24 +00001325 if (!S.getLangOpts().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +00001326 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +00001327 return ICS;
1328 }
1329
Douglas Gregor836a7e82010-08-11 02:15:33 +00001330 // C++ [over.ics.user]p4:
1331 // A conversion of an expression of class type to the same class
1332 // type is given Exact Match rank, and a conversion of an
1333 // expression of class type to a base class of that type is
1334 // given Conversion rank, in spite of the fact that a copy/move
1335 // constructor (i.e., a user-defined conversion function) is
1336 // called for those cases.
1337 QualType FromType = From->getType();
1338 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00001339 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00001340 S.IsDerivedFrom(From->getLocStart(), FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001341 ICS.setStandard();
1342 ICS.Standard.setAsIdentityConversion();
1343 ICS.Standard.setFromType(FromType);
1344 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001345
Douglas Gregor5ab11652010-04-17 22:01:05 +00001346 // We don't actually check at this point whether there is a valid
1347 // copy/move constructor, since overloading just assumes that it
1348 // exists. When we actually perform initialization, we'll find the
1349 // appropriate constructor to copy the returned object, if needed.
Craig Topperc3ec1492014-05-26 06:22:03 +00001350 ICS.Standard.CopyConstructor = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001351
Douglas Gregor5ab11652010-04-17 22:01:05 +00001352 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +00001353 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +00001354 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001355
Douglas Gregor836a7e82010-08-11 02:15:33 +00001356 return ICS;
1357 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001358
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001359 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1360 AllowExplicit, InOverloadResolution, CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001361 AllowObjCWritebackConversion,
1362 AllowObjCConversionOnExplicit);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001363}
1364
John McCall31168b02011-06-15 23:02:42 +00001365ImplicitConversionSequence
1366Sema::TryImplicitConversion(Expr *From, QualType ToType,
1367 bool SuppressUserConversions,
1368 bool AllowExplicit,
1369 bool InOverloadResolution,
1370 bool CStyle,
1371 bool AllowObjCWritebackConversion) {
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00001372 return ::TryImplicitConversion(*this, From, ToType,
Richard Smith17c00b42014-11-12 01:24:00 +00001373 SuppressUserConversions, AllowExplicit,
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00001374 InOverloadResolution, CStyle,
Richard Smith17c00b42014-11-12 01:24:00 +00001375 AllowObjCWritebackConversion,
1376 /*AllowObjCConversionOnExplicit=*/false);
John McCall5c32be02010-08-24 20:38:10 +00001377}
1378
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001379/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley01296292011-04-08 18:41:53 +00001380/// expression From to the type ToType. Returns the
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001381/// converted expression. Flavor is the kind of conversion we're
1382/// performing, used in the error message. If @p AllowExplicit,
1383/// explicit user-defined conversions are permitted.
John Wiegley01296292011-04-08 18:41:53 +00001384ExprResult
1385Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redlcc152642011-10-16 18:19:06 +00001386 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001387 ImplicitConversionSequence ICS;
Sebastian Redlcc152642011-10-16 18:19:06 +00001388 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001389}
1390
John Wiegley01296292011-04-08 18:41:53 +00001391ExprResult
1392Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001393 AssignmentAction Action, bool AllowExplicit,
Sebastian Redlcc152642011-10-16 18:19:06 +00001394 ImplicitConversionSequence& ICS) {
John McCall526ab472011-10-25 17:37:35 +00001395 if (checkPlaceholderForOverload(*this, From))
1396 return ExprError();
1397
John McCall31168b02011-06-15 23:02:42 +00001398 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1399 bool AllowObjCWritebackConversion
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00001400 = getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001401 (Action == AA_Passing || Action == AA_Sending);
Fariborz Jahanian381edf52013-12-16 22:54:37 +00001402 if (getLangOpts().ObjC1)
1403 CheckObjCBridgeRelatedConversions(From->getLocStart(),
1404 ToType, From->getType(), From);
Richard Smith17c00b42014-11-12 01:24:00 +00001405 ICS = ::TryImplicitConversion(*this, From, ToType,
1406 /*SuppressUserConversions=*/false,
1407 AllowExplicit,
1408 /*InOverloadResolution=*/false,
1409 /*CStyle=*/false,
1410 AllowObjCWritebackConversion,
1411 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001412 return PerformImplicitConversion(From, ToType, ICS, Action);
1413}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001414
1415/// \brief Determine whether the conversion from FromType to ToType is a valid
Richard Smith3c4f8d22016-10-16 17:54:23 +00001416/// conversion that strips "noexcept" or "noreturn" off the nested function
1417/// type.
1418bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
Chandler Carruth53e61b02011-06-18 01:19:03 +00001419 QualType &ResultTy) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001420 if (Context.hasSameUnqualifiedType(FromType, ToType))
1421 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001422
John McCall991eb4b2010-12-21 00:44:39 +00001423 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
Richard Smith3c4f8d22016-10-16 17:54:23 +00001424 // or F(t noexcept) -> F(t)
John McCall991eb4b2010-12-21 00:44:39 +00001425 // where F adds one of the following at most once:
1426 // - a pointer
1427 // - a member pointer
1428 // - a block pointer
Richard Smitheb7ef2e2016-10-20 21:53:09 +00001429 // Changes here need matching changes in FindCompositePointerType.
John McCall991eb4b2010-12-21 00:44:39 +00001430 CanQualType CanTo = Context.getCanonicalType(ToType);
1431 CanQualType CanFrom = Context.getCanonicalType(FromType);
1432 Type::TypeClass TyClass = CanTo->getTypeClass();
1433 if (TyClass != CanFrom->getTypeClass()) return false;
1434 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1435 if (TyClass == Type::Pointer) {
1436 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1437 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1438 } else if (TyClass == Type::BlockPointer) {
1439 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1440 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1441 } else if (TyClass == Type::MemberPointer) {
Richard Smitheb7ef2e2016-10-20 21:53:09 +00001442 auto ToMPT = CanTo.getAs<MemberPointerType>();
1443 auto FromMPT = CanFrom.getAs<MemberPointerType>();
1444 // A function pointer conversion cannot change the class of the function.
1445 if (ToMPT->getClass() != FromMPT->getClass())
1446 return false;
1447 CanTo = ToMPT->getPointeeType();
1448 CanFrom = FromMPT->getPointeeType();
John McCall991eb4b2010-12-21 00:44:39 +00001449 } else {
1450 return false;
1451 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001452
John McCall991eb4b2010-12-21 00:44:39 +00001453 TyClass = CanTo->getTypeClass();
1454 if (TyClass != CanFrom->getTypeClass()) return false;
1455 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1456 return false;
1457 }
1458
Richard Smith3c4f8d22016-10-16 17:54:23 +00001459 const auto *FromFn = cast<FunctionType>(CanFrom);
1460 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
John McCall991eb4b2010-12-21 00:44:39 +00001461
Richard Smith6f427402016-10-20 00:01:36 +00001462 const auto *ToFn = cast<FunctionType>(CanTo);
Richard Smith3c4f8d22016-10-16 17:54:23 +00001463 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1464
1465 bool Changed = false;
1466
1467 // Drop 'noreturn' if not present in target type.
1468 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1469 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1470 Changed = true;
1471 }
1472
1473 // Drop 'noexcept' if not present in target type.
1474 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
Richard Smith6f427402016-10-20 00:01:36 +00001475 const auto *ToFPT = cast<FunctionProtoType>(ToFn);
Richard Smith3c4f8d22016-10-16 17:54:23 +00001476 if (FromFPT->isNothrow(Context) && !ToFPT->isNothrow(Context)) {
1477 FromFn = cast<FunctionType>(
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00001478 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1479 EST_None)
Richard Smith3c4f8d22016-10-16 17:54:23 +00001480 .getTypePtr());
1481 Changed = true;
1482 }
Akira Hatanaka98a49332017-09-22 00:41:05 +00001483
1484 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1485 // only if the ExtParameterInfo lists of the two function prototypes can be
1486 // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1487 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
1488 bool CanUseToFPT, CanUseFromFPT;
1489 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1490 CanUseFromFPT, NewParamInfos) &&
1491 CanUseToFPT && !CanUseFromFPT) {
1492 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1493 ExtInfo.ExtParameterInfos =
1494 NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1495 QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1496 FromFPT->getParamTypes(), ExtInfo);
1497 FromFn = QT->getAs<FunctionType>();
1498 Changed = true;
1499 }
Richard Smith3c4f8d22016-10-16 17:54:23 +00001500 }
1501
1502 if (!Changed)
1503 return false;
1504
John McCall991eb4b2010-12-21 00:44:39 +00001505 assert(QualType(FromFn, 0).isCanonical());
1506 if (QualType(FromFn, 0) != CanTo) return false;
1507
1508 ResultTy = ToType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001509 return true;
1510}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001511
Douglas Gregor46188682010-05-18 22:42:18 +00001512/// \brief Determine whether the conversion from FromType to ToType is a valid
1513/// vector conversion.
1514///
1515/// \param ICK Will be set to the vector conversion kind, if this is a vector
1516/// conversion.
John McCall9b595db2014-02-04 23:58:19 +00001517static bool IsVectorConversion(Sema &S, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001518 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregor46188682010-05-18 22:42:18 +00001519 // We need at least one of these types to be a vector type to have a vector
1520 // conversion.
1521 if (!ToType->isVectorType() && !FromType->isVectorType())
1522 return false;
1523
1524 // Identical types require no conversions.
John McCall9b595db2014-02-04 23:58:19 +00001525 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor46188682010-05-18 22:42:18 +00001526 return false;
1527
1528 // There are no conversions between extended vector types, only identity.
1529 if (ToType->isExtVectorType()) {
1530 // There are no conversions between extended vector types other than the
1531 // identity conversion.
1532 if (FromType->isExtVectorType())
1533 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001534
Douglas Gregor46188682010-05-18 22:42:18 +00001535 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +00001536 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +00001537 ICK = ICK_Vector_Splat;
1538 return true;
1539 }
1540 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001541
1542 // We can perform the conversion between vector types in the following cases:
1543 // 1)vector types are equivalent AltiVec and GCC vector types
1544 // 2)lax vector conversions are permitted and the vector types are of the
1545 // same size
1546 if (ToType->isVectorType() && FromType->isVectorType()) {
John McCall9b595db2014-02-04 23:58:19 +00001547 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1548 S.isLaxVectorConversion(FromType, ToType)) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001549 ICK = ICK_Vector_Conversion;
1550 return true;
1551 }
Douglas Gregor46188682010-05-18 22:42:18 +00001552 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001553
Douglas Gregor46188682010-05-18 22:42:18 +00001554 return false;
1555}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001556
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001557static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1558 bool InOverloadResolution,
1559 StandardConversionSequence &SCS,
1560 bool CStyle);
George Burgess IV45461812015-10-11 20:13:20 +00001561
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001562/// IsStandardConversion - Determines whether there is a standard
1563/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1564/// expression From to the type ToType. Standard conversion sequences
1565/// only consider non-class types; for conversions that involve class
1566/// types, use TryImplicitConversion. If a conversion exists, SCS will
1567/// contain the standard conversion sequence required to perform this
1568/// conversion and this routine will return true. Otherwise, this
1569/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +00001570static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1571 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +00001572 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +00001573 bool CStyle,
1574 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001575 QualType FromType = From->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001576
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001577 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +00001578 SCS.setAsIdentityConversion();
Douglas Gregor47d3f272008-12-19 17:40:08 +00001579 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +00001580 SCS.setFromType(FromType);
Craig Topperc3ec1492014-05-26 06:22:03 +00001581 SCS.CopyConstructor = nullptr;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001582
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001583 // There are no standard conversions for class types in C++, so
George Burgess IV45461812015-10-11 20:13:20 +00001584 // abort early. When overloading in C, however, we do permit them.
1585 if (S.getLangOpts().CPlusPlus &&
1586 (FromType->isRecordType() || ToType->isRecordType()))
1587 return false;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001588
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001589 // The first conversion can be an lvalue-to-rvalue conversion,
1590 // array-to-pointer conversion, or function-to-pointer conversion
1591 // (C++ 4p1).
1592
John McCall5c32be02010-08-24 20:38:10 +00001593 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001594 DeclAccessPair AccessPair;
1595 if (FunctionDecl *Fn
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001596 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall5c32be02010-08-24 20:38:10 +00001597 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001598 // We were able to resolve the address of the overloaded function,
1599 // so we can convert to the type of that function.
1600 FromType = Fn->getType();
Ehsan Akhgaric3ad3ba2014-07-22 20:20:14 +00001601 SCS.setFromType(FromType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00001602
1603 // we can sometimes resolve &foo<int> regardless of ToType, so check
1604 // if the type matches (identity) or we are converting to bool
1605 if (!S.Context.hasSameUnqualifiedType(
1606 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1607 QualType resultTy;
1608 // if the function type matches except for [[noreturn]], it's ok
Richard Smith3c4f8d22016-10-16 17:54:23 +00001609 if (!S.IsFunctionConversion(FromType,
Douglas Gregorb491ed32011-02-19 21:32:49 +00001610 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00001611 // otherwise, only a boolean conversion is standard
1612 if (!ToType->isBooleanType())
1613 return false;
Douglas Gregor980fb162010-04-29 18:24:40 +00001614 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001615
Chandler Carruthffce2452011-03-29 08:08:18 +00001616 // Check if the "from" expression is taking the address of an overloaded
1617 // function and recompute the FromType accordingly. Take advantage of the
1618 // fact that non-static member functions *must* have such an address-of
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00001619 // expression.
Chandler Carruthffce2452011-03-29 08:08:18 +00001620 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1621 if (Method && !Method->isStatic()) {
1622 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1623 "Non-unary operator on non-static member address");
1624 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1625 == UO_AddrOf &&
1626 "Non-address-of operator on non-static member address");
1627 const Type *ClassType
1628 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1629 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruth7750f762011-03-29 18:38:10 +00001630 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1631 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1632 UO_AddrOf &&
Chandler Carruthffce2452011-03-29 08:08:18 +00001633 "Non-address-of operator for overloaded function expression");
1634 FromType = S.Context.getPointerType(FromType);
1635 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001636
Douglas Gregor980fb162010-04-29 18:24:40 +00001637 // Check that we've computed the proper type after overload resolution.
Richard Smith9095e5b2016-11-01 01:31:23 +00001638 // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't
1639 // be calling it from within an NDEBUG block.
Chandler Carruthffce2452011-03-29 08:08:18 +00001640 assert(S.Context.hasSameType(
1641 FromType,
1642 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001643 } else {
1644 return false;
1645 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001646 }
John McCall154a2fd2011-08-30 00:57:29 +00001647 // Lvalue-to-rvalue conversion (C++11 4.1):
1648 // A glvalue (3.10) of a non-function, non-array type T can
1649 // be converted to a prvalue.
1650 bool argIsLValue = From->isGLValue();
John McCall086a4642010-11-24 05:12:34 +00001651 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001652 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001653 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001654 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001655
Douglas Gregorc79862f2012-04-12 17:51:55 +00001656 // C11 6.3.2.1p2:
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00001657 // ... if the lvalue has atomic type, the value has the non-atomic version
Douglas Gregorc79862f2012-04-12 17:51:55 +00001658 // of the type of the lvalue ...
1659 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1660 FromType = Atomic->getValueType();
1661
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001662 // If T is a non-class type, the type of the rvalue is the
1663 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001664 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1665 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001666 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001667 } else if (FromType->isArrayType()) {
1668 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001669 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001670
1671 // An lvalue or rvalue of type "array of N T" or "array of unknown
1672 // bound of T" can be converted to an rvalue of type "pointer to
1673 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001674 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001675
John McCall5c32be02010-08-24 20:38:10 +00001676 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00001677 // This conversion is deprecated in C++03 (D.4)
Douglas Gregore489a7d2010-02-28 18:30:25 +00001678 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001679
1680 // For the purpose of ranking in overload resolution
1681 // (13.3.3.1.1), this conversion is considered an
1682 // array-to-pointer conversion followed by a qualification
1683 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001684 SCS.Second = ICK_Identity;
1685 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001686 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001687 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001688 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001689 }
John McCall086a4642010-11-24 05:12:34 +00001690 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001691 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001692 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001693
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001694 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1695 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1696 if (!S.checkAddressOfFunctionIsAvailable(FD))
1697 return false;
1698
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001699 // An lvalue of function type T can be converted to an rvalue of
1700 // type "pointer to T." The result is a pointer to the
1701 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001702 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001703 } else {
1704 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001705 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001706 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001707 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001708
1709 // The second conversion can be an integral promotion, floating
1710 // point promotion, integral conversion, floating point conversion,
1711 // floating-integral conversion, pointer conversion,
1712 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001713 // For overloading in C, this can also be a "compatible-type"
1714 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001715 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001716 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001717 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001718 // The unqualified versions of the types are the same: there's no
1719 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001720 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001721 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001722 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001723 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001724 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001725 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001726 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001727 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001728 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001729 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001730 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001731 SCS.Second = ICK_Complex_Promotion;
1732 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001733 } else if (ToType->isBooleanType() &&
1734 (FromType->isArithmeticType() ||
1735 FromType->isAnyPointerType() ||
1736 FromType->isBlockPointerType() ||
1737 FromType->isMemberPointerType() ||
1738 FromType->isNullPtrType())) {
1739 // Boolean conversions (C++ 4.12).
1740 SCS.Second = ICK_Boolean_Conversion;
1741 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001742 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001743 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001744 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001745 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001746 FromType = ToType.getUnqualifiedType();
Richard Smithb8a98242013-05-10 20:29:50 +00001747 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001748 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001749 SCS.Second = ICK_Complex_Conversion;
1750 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001751 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1752 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001753 // Complex-real conversions (C99 6.3.1.7)
1754 SCS.Second = ICK_Complex_Real;
1755 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001756 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001757 // FIXME: disable conversions between long double and __float128 if
1758 // their representation is different until there is back end support
1759 // We of course allow this conversion if long double is really double.
1760 if (&S.Context.getFloatTypeSemantics(FromType) !=
1761 &S.Context.getFloatTypeSemantics(ToType)) {
1762 bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1763 ToType == S.Context.LongDoubleTy) ||
1764 (FromType == S.Context.LongDoubleTy &&
1765 ToType == S.Context.Float128Ty));
1766 if (Float128AndLongDouble &&
1767 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) !=
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001768 &llvm::APFloat::IEEEdouble()))
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001769 return false;
1770 }
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001771 // Floating point conversions (C++ 4.8).
1772 SCS.Second = ICK_Floating_Conversion;
1773 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001774 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001775 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001776 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001777 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001778 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001779 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001780 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001781 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCall31168b02011-06-15 23:02:42 +00001782 SCS.Second = ICK_Block_Pointer_Conversion;
1783 } else if (AllowObjCWritebackConversion &&
1784 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1785 SCS.Second = ICK_Writeback_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001786 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1787 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001788 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001789 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001790 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregoraec25842011-04-26 23:16:46 +00001791 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001792 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall5c32be02010-08-24 20:38:10 +00001793 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001794 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001795 SCS.Second = ICK_Pointer_Member;
John McCall9b595db2014-02-04 23:58:19 +00001796 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001797 SCS.Second = SecondICK;
1798 FromType = ToType.getUnqualifiedType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001799 } else if (!S.getLangOpts().CPlusPlus &&
John McCall5c32be02010-08-24 20:38:10 +00001800 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001801 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001802 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001803 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001804 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1805 InOverloadResolution,
1806 SCS, CStyle)) {
1807 SCS.Second = ICK_TransparentUnionConversion;
1808 FromType = ToType;
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001809 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1810 CStyle)) {
1811 // tryAtomicConversion has updated the standard conversion sequence
Douglas Gregorc79862f2012-04-12 17:51:55 +00001812 // appropriately.
1813 return true;
George Burgess IV45461812015-10-11 20:13:20 +00001814 } else if (ToType->isEventT() &&
Guy Benyei259f9f42013-02-07 16:05:33 +00001815 From->isIntegerConstantExpr(S.getASTContext()) &&
George Burgess IV45461812015-10-11 20:13:20 +00001816 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
Guy Benyei259f9f42013-02-07 16:05:33 +00001817 SCS.Second = ICK_Zero_Event_Conversion;
1818 FromType = ToType;
Egor Churaev89831422016-12-23 14:55:49 +00001819 } else if (ToType->isQueueT() &&
1820 From->isIntegerConstantExpr(S.getASTContext()) &&
1821 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1822 SCS.Second = ICK_Zero_Queue_Conversion;
1823 FromType = ToType;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001824 } else {
1825 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001826 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001827 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001828 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001829
Richard Smitheb7ef2e2016-10-20 21:53:09 +00001830 // The third conversion can be a function pointer conversion or a
1831 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
John McCall31168b02011-06-15 23:02:42 +00001832 bool ObjCLifetimeConversion;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00001833 if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1834 // Function pointer conversions (removing 'noexcept') including removal of
1835 // 'noreturn' (Clang extension).
1836 SCS.Third = ICK_Function_Conversion;
1837 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1838 ObjCLifetimeConversion)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001839 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001840 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001841 FromType = ToType;
1842 } else {
1843 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001844 SCS.Third = ICK_Identity;
Richard Smith9c37e662016-10-20 17:57:33 +00001845 }
Richard Smitheb7ef2e2016-10-20 21:53:09 +00001846
1847 // C++ [over.best.ics]p6:
1848 // [...] Any difference in top-level cv-qualification is
1849 // subsumed by the initialization itself and does not constitute
1850 // a conversion. [...]
1851 QualType CanonFrom = S.Context.getCanonicalType(FromType);
1852 QualType CanonTo = S.Context.getCanonicalType(ToType);
1853 if (CanonFrom.getLocalUnqualifiedType()
1854 == CanonTo.getLocalUnqualifiedType() &&
1855 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1856 FromType = ToType;
1857 CanonFrom = CanonTo;
1858 }
1859
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001860 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001861
George Burgess IV45461812015-10-11 20:13:20 +00001862 if (CanonFrom == CanonTo)
1863 return true;
1864
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001865 // If we have not converted the argument type to the parameter type,
George Burgess IV45461812015-10-11 20:13:20 +00001866 // this is a bad conversion sequence, unless we're resolving an overload in C.
1867 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001868 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001869
George Burgess IV45461812015-10-11 20:13:20 +00001870 ExprResult ER = ExprResult{From};
George Burgess IV2099b542016-09-02 22:59:57 +00001871 Sema::AssignConvertType Conv =
1872 S.CheckSingleAssignmentConstraints(ToType, ER,
1873 /*Diagnose=*/false,
1874 /*DiagnoseCFAudited=*/false,
1875 /*ConvertRHS=*/false);
George Burgess IV6098fd12016-09-03 00:28:25 +00001876 ImplicitConversionKind SecondConv;
George Burgess IV2099b542016-09-02 22:59:57 +00001877 switch (Conv) {
1878 case Sema::Compatible:
George Burgess IV6098fd12016-09-03 00:28:25 +00001879 SecondConv = ICK_C_Only_Conversion;
George Burgess IV2099b542016-09-02 22:59:57 +00001880 break;
1881 // For our purposes, discarding qualifiers is just as bad as using an
1882 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
1883 // qualifiers, as well.
1884 case Sema::CompatiblePointerDiscardsQualifiers:
1885 case Sema::IncompatiblePointer:
1886 case Sema::IncompatiblePointerSign:
George Burgess IV6098fd12016-09-03 00:28:25 +00001887 SecondConv = ICK_Incompatible_Pointer_Conversion;
George Burgess IV2099b542016-09-02 22:59:57 +00001888 break;
1889 default:
George Burgess IV45461812015-10-11 20:13:20 +00001890 return false;
George Burgess IV2099b542016-09-02 22:59:57 +00001891 }
George Burgess IV45461812015-10-11 20:13:20 +00001892
George Burgess IV6098fd12016-09-03 00:28:25 +00001893 // First can only be an lvalue conversion, so we pretend that this was the
1894 // second conversion. First should already be valid from earlier in the
1895 // function.
1896 SCS.Second = SecondConv;
1897 SCS.setToType(1, ToType);
1898
1899 // Third is Identity, because Second should rank us worse than any other
1900 // conversion. This could also be ICK_Qualification, but it's simpler to just
1901 // lump everything in with the second conversion, and we don't gain anything
1902 // from making this ICK_Qualification.
1903 SCS.Third = ICK_Identity;
1904 SCS.setToType(2, ToType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001905 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001906}
George Burgess IV2099b542016-09-02 22:59:57 +00001907
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001908static bool
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00001909IsTransparentUnionStandardConversion(Sema &S, Expr* From,
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001910 QualType &ToType,
1911 bool InOverloadResolution,
1912 StandardConversionSequence &SCS,
1913 bool CStyle) {
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00001914
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001915 const RecordType *UT = ToType->getAsUnionType();
1916 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1917 return false;
1918 // The field to initialize within the transparent union.
1919 RecordDecl *UD = UT->getDecl();
1920 // It's compatible if the expression matches any of the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001921 for (const auto *it : UD->fields()) {
John McCall31168b02011-06-15 23:02:42 +00001922 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1923 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001924 ToType = it->getType();
1925 return true;
1926 }
1927 }
1928 return false;
1929}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001930
1931/// IsIntegralPromotion - Determines whether the conversion from the
1932/// expression From (whose potentially-adjusted type is FromType) to
1933/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1934/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001935bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001936 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001937 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001938 if (!To) {
1939 return false;
1940 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001941
1942 // An rvalue of type char, signed char, unsigned char, short int, or
1943 // unsigned short int can be converted to an rvalue of type int if
1944 // int can represent all the values of the source type; otherwise,
1945 // the source rvalue can be converted to an rvalue of type unsigned
1946 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001947 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1948 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001949 if (// We can promote any signed, promotable integer type to an int
1950 (FromType->isSignedIntegerType() ||
1951 // We can promote any unsigned integer type whose size is
1952 // less than int to an int.
Benjamin Kramer5ff67472016-04-11 08:26:13 +00001953 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001954 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001955 }
1956
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001957 return To->getKind() == BuiltinType::UInt;
1958 }
1959
Richard Smithb9c5a602012-09-13 21:18:54 +00001960 // C++11 [conv.prom]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001961 // A prvalue of an unscoped enumeration type whose underlying type is not
1962 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1963 // following types that can represent all the values of the enumeration
1964 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1965 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001966 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001967 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001968 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001969 // with lowest integer conversion rank (4.13) greater than the rank of long
1970 // long in which all the values of the enumeration can be represented. If
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001971 // there are two such extended types, the signed one is chosen.
Richard Smithb9c5a602012-09-13 21:18:54 +00001972 // C++11 [conv.prom]p4:
1973 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1974 // can be converted to a prvalue of its underlying type. Moreover, if
1975 // integral promotion can be applied to its underlying type, a prvalue of an
1976 // unscoped enumeration type whose underlying type is fixed can also be
1977 // converted to a prvalue of the promoted underlying type.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001978 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1979 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1980 // provided for a scoped enumeration.
1981 if (FromEnumType->getDecl()->isScoped())
1982 return false;
1983
Richard Smithb9c5a602012-09-13 21:18:54 +00001984 // We can perform an integral promotion to the underlying type of the enum,
Richard Smithac8c1752015-03-28 00:31:40 +00001985 // even if that's not the promoted type. Note that the check for promoting
1986 // the underlying type is based on the type alone, and does not consider
1987 // the bitfield-ness of the actual source expression.
Richard Smithb9c5a602012-09-13 21:18:54 +00001988 if (FromEnumType->getDecl()->isFixed()) {
1989 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1990 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
Richard Smithac8c1752015-03-28 00:31:40 +00001991 IsIntegralPromotion(nullptr, Underlying, ToType);
Richard Smithb9c5a602012-09-13 21:18:54 +00001992 }
1993
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001994 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001995 if (ToType->isIntegerType() &&
Richard Smithdb0ac552015-12-18 22:40:25 +00001996 isCompleteType(From->getLocStart(), FromType))
Richard Smith88f4bba2015-03-26 00:16:07 +00001997 return Context.hasSameUnqualifiedType(
1998 ToType, FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001999 }
John McCall56774992009-12-09 09:09:27 +00002000
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00002001 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002002 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2003 // to an rvalue a prvalue of the first of the following types that can
2004 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00002005 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002006 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00002007 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002008 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00002009 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002010 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00002011 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002012 // Determine whether the type we're converting from is signed or
2013 // unsigned.
David Majnemerfa01a582011-07-22 21:09:04 +00002014 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002015 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002016
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002017 // The types we'll try to promote to, in the appropriate
2018 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00002019 QualType PromoteTypes[6] = {
2020 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00002021 Context.LongTy, Context.UnsignedLongTy ,
2022 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002023 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00002024 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002025 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2026 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00002027 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002028 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2029 // We found the type that we can promote to. If this is the
2030 // type we wanted, we have a promotion. Otherwise, no
2031 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002032 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002033 }
2034 }
2035 }
2036
2037 // An rvalue for an integral bit-field (9.6) can be converted to an
2038 // rvalue of type int if int can represent all the values of the
2039 // bit-field; otherwise, it can be converted to unsigned int if
2040 // unsigned int can represent all the values of the bit-field. If
2041 // the bit-field is larger yet, no integral promotion applies to
2042 // it. If the bit-field has an enumerated type, it is treated as any
2043 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00002044 // FIXME: We should delay checking of bit-fields until we actually perform the
2045 // conversion.
Richard Smith88f4bba2015-03-26 00:16:07 +00002046 if (From) {
John McCalld25db7e2013-05-06 21:39:12 +00002047 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
Richard Smith88f4bba2015-03-26 00:16:07 +00002048 llvm::APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00002049 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00002050 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
Richard Smith88f4bba2015-03-26 00:16:07 +00002051 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
Douglas Gregor71235ec2009-05-02 02:18:30 +00002052 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00002053
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00002054 // Are we promoting to an int from a bitfield that fits in an int?
2055 if (BitWidth < ToSize ||
2056 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
2057 return To->getKind() == BuiltinType::Int;
2058 }
Mike Stump11289f42009-09-09 15:08:12 +00002059
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00002060 // Are we promoting to an unsigned int from an unsigned bitfield
2061 // that fits into an unsigned int?
2062 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
2063 return To->getKind() == BuiltinType::UInt;
2064 }
Mike Stump11289f42009-09-09 15:08:12 +00002065
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00002066 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002067 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002068 }
Richard Smith88f4bba2015-03-26 00:16:07 +00002069 }
Mike Stump11289f42009-09-09 15:08:12 +00002070
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002071 // An rvalue of type bool can be converted to an rvalue of type int,
2072 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002073 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002074 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002075 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002076
2077 return false;
2078}
2079
2080/// IsFloatingPointPromotion - Determines whether the conversion from
2081/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2082/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00002083bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00002084 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2085 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002086 /// An rvalue of type float can be converted to an rvalue of type
2087 /// double. (C++ 4.6p1).
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002088 if (FromBuiltin->getKind() == BuiltinType::Float &&
2089 ToBuiltin->getKind() == BuiltinType::Double)
2090 return true;
2091
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002092 // C99 6.3.1.5p1:
2093 // When a float is promoted to double or long double, or a
2094 // double is promoted to long double [...].
David Blaikiebbafb8a2012-03-11 07:00:24 +00002095 if (!getLangOpts().CPlusPlus &&
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002096 (FromBuiltin->getKind() == BuiltinType::Float ||
2097 FromBuiltin->getKind() == BuiltinType::Double) &&
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002098 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2099 ToBuiltin->getKind() == BuiltinType::Float128))
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002100 return true;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002101
2102 // Half can be promoted to float.
Joey Goulydd7f4562013-01-23 11:56:20 +00002103 if (!getLangOpts().NativeHalfType &&
2104 FromBuiltin->getKind() == BuiltinType::Half &&
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002105 ToBuiltin->getKind() == BuiltinType::Float)
2106 return true;
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002107 }
2108
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002109 return false;
2110}
2111
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002112/// \brief Determine if a conversion is a complex promotion.
2113///
2114/// A complex promotion is defined as a complex -> complex conversion
2115/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00002116/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002117bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00002118 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002119 if (!FromComplex)
2120 return false;
2121
John McCall9dd450b2009-09-21 23:43:11 +00002122 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002123 if (!ToComplex)
2124 return false;
2125
2126 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00002127 ToComplex->getElementType()) ||
Craig Topperc3ec1492014-05-26 06:22:03 +00002128 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00002129 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002130}
2131
Douglas Gregor237f96c2008-11-26 23:31:11 +00002132/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2133/// the pointer type FromPtr to a pointer to type ToPointee, with the
2134/// same type qualifiers as FromPtr has on its pointee type. ToType,
2135/// if non-empty, will be a pointer to ToType that may or may not have
2136/// the right set of qualifiers on its pointee.
John McCall31168b02011-06-15 23:02:42 +00002137///
Mike Stump11289f42009-09-09 15:08:12 +00002138static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002139BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002140 QualType ToPointee, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002141 ASTContext &Context,
2142 bool StripObjCLifetime = false) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002143 assert((FromPtr->getTypeClass() == Type::Pointer ||
2144 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2145 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002146
John McCall31168b02011-06-15 23:02:42 +00002147 /// Conversions to 'id' subsume cv-qualifier conversions.
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002148 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00002149 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002150
2151 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002152 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00002153 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00002154 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00002155
John McCall31168b02011-06-15 23:02:42 +00002156 if (StripObjCLifetime)
2157 Quals.removeObjCLifetime();
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002158
Mike Stump11289f42009-09-09 15:08:12 +00002159 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002160 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00002161 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00002162 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00002163 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002164
2165 // Build a pointer to ToPointee. It has the right qualifiers
2166 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002167 if (isa<ObjCObjectPointerType>(ToType))
2168 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00002169 return Context.getPointerType(ToPointee);
2170 }
2171
2172 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002173 QualType QualifiedCanonToPointee
2174 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002175
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002176 if (isa<ObjCObjectPointerType>(ToType))
2177 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2178 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002179}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002180
Mike Stump11289f42009-09-09 15:08:12 +00002181static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00002182 bool InOverloadResolution,
2183 ASTContext &Context) {
2184 // Handle value-dependent integral null pointer constants correctly.
2185 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2186 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00002187 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00002188 return !InOverloadResolution;
2189
Douglas Gregor56751b52009-09-25 04:25:58 +00002190 return Expr->isNullPointerConstant(Context,
2191 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2192 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00002193}
Mike Stump11289f42009-09-09 15:08:12 +00002194
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002195/// IsPointerConversion - Determines whether the conversion of the
2196/// expression From, which has the (possibly adjusted) type FromType,
2197/// can be converted to the type ToType via a pointer conversion (C++
2198/// 4.10). If so, returns true and places the converted type (that
2199/// might differ from ToType in its cv-qualifiers at some level) into
2200/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00002201///
Douglas Gregora29dc052008-11-27 01:19:21 +00002202/// This routine also supports conversions to and from block pointers
2203/// and conversions with Objective-C's 'id', 'id<protocols...>', and
2204/// pointers to interfaces. FIXME: Once we've determined the
2205/// appropriate overloading rules for Objective-C, we may want to
2206/// split the Objective-C checks into a different routine; however,
2207/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00002208/// conversions, so for now they live here. IncompatibleObjC will be
2209/// set if the conversion is an allowed Objective-C conversion that
2210/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002211bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00002212 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00002213 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00002214 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00002215 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00002216 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2217 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00002218 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00002219
Mike Stump11289f42009-09-09 15:08:12 +00002220 // Conversion from a null pointer constant to any Objective-C pointer type.
2221 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002222 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00002223 ConvertedType = ToType;
2224 return true;
2225 }
2226
Douglas Gregor231d1c62008-11-27 00:15:41 +00002227 // Blocks: Block pointers can be converted to void*.
2228 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002229 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00002230 ConvertedType = ToType;
2231 return true;
2232 }
2233 // Blocks: A null pointer constant can be converted to a block
2234 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00002235 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002236 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00002237 ConvertedType = ToType;
2238 return true;
2239 }
2240
Sebastian Redl576fd422009-05-10 18:38:11 +00002241 // If the left-hand-side is nullptr_t, the right side can be a null
2242 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00002243 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002244 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00002245 ConvertedType = ToType;
2246 return true;
2247 }
2248
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002249 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002250 if (!ToTypePtr)
2251 return false;
2252
2253 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00002254 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002255 ConvertedType = ToType;
2256 return true;
2257 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002258
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002259 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002260 // , including objective-c pointers.
2261 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00002262 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002263 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002264 ConvertedType = BuildSimilarlyQualifiedPointerType(
2265 FromType->getAs<ObjCObjectPointerType>(),
2266 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002267 ToType, Context);
2268 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002269 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002270 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002271 if (!FromTypePtr)
2272 return false;
2273
2274 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002275
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002276 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-08-18 21:25:30 +00002277 // pointer conversion, so don't do all of the work below.
2278 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2279 return false;
2280
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002281 // An rvalue of type "pointer to cv T," where T is an object type,
2282 // can be converted to an rvalue of type "pointer to cv void" (C++
2283 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00002284 if (FromPointeeType->isIncompleteOrObjectType() &&
2285 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002286 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002287 ToPointeeType,
John McCall31168b02011-06-15 23:02:42 +00002288 ToType, Context,
2289 /*StripObjCLifetime=*/true);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002290 return true;
2291 }
2292
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002293 // MSVC allows implicit function to void* type conversion.
David Majnemer6bf02822015-10-31 08:42:14 +00002294 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002295 ToPointeeType->isVoidType()) {
2296 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2297 ToPointeeType,
2298 ToType, Context);
2299 return true;
2300 }
2301
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002302 // When we're overloading in C, we allow a special kind of pointer
2303 // conversion for compatible-but-not-identical pointee types.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002304 if (!getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002305 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002306 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002307 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00002308 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002309 return true;
2310 }
2311
Douglas Gregor5c407d92008-10-23 00:40:37 +00002312 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002313 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00002314 // An rvalue of type "pointer to cv D," where D is a class type,
2315 // can be converted to an rvalue of type "pointer to cv B," where
2316 // B is a base class (clause 10) of D. If B is an inaccessible
2317 // (clause 11) or ambiguous (10.2) base class of D, a program that
2318 // necessitates this conversion is ill-formed. The result of the
2319 // conversion is a pointer to the base class sub-object of the
2320 // derived class object. The null pointer value is converted to
2321 // the null pointer value of the destination type.
2322 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00002323 // Note that we do not check for ambiguity or inaccessibility
2324 // here. That is handled by CheckPointerConversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002325 if (getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002326 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00002327 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00002328 IsDerivedFrom(From->getLocStart(), FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002329 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002330 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002331 ToType, Context);
2332 return true;
2333 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002334
Fariborz Jahanianbc2ee932011-04-14 20:33:36 +00002335 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2336 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2337 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2338 ToPointeeType,
2339 ToType, Context);
2340 return true;
2341 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002342
Douglas Gregora119f102008-12-19 19:13:09 +00002343 return false;
2344}
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002345
Douglas Gregoraec25842011-04-26 23:16:46 +00002346/// \brief Adopt the given qualifiers for the given type.
2347static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2348 Qualifiers TQs = T.getQualifiers();
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002349
Douglas Gregoraec25842011-04-26 23:16:46 +00002350 // Check whether qualifiers already match.
2351 if (TQs == Qs)
2352 return T;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002353
Douglas Gregoraec25842011-04-26 23:16:46 +00002354 if (Qs.compatiblyIncludes(TQs))
2355 return Context.getQualifiedType(T, Qs);
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002356
Douglas Gregoraec25842011-04-26 23:16:46 +00002357 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2358}
Douglas Gregora119f102008-12-19 19:13:09 +00002359
2360/// isObjCPointerConversion - Determines whether this is an
2361/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2362/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00002363bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00002364 QualType& ConvertedType,
2365 bool &IncompatibleObjC) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002366 if (!getLangOpts().ObjC1)
Douglas Gregora119f102008-12-19 19:13:09 +00002367 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002368
Douglas Gregoraec25842011-04-26 23:16:46 +00002369 // The set of qualifiers on the type we're converting from.
2370 Qualifiers FromQualifiers = FromType.getQualifiers();
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002371
Steve Naroff7cae42b2009-07-10 23:34:53 +00002372 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00002373 const ObjCObjectPointerType* ToObjCPtr =
2374 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00002375 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00002376 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002377
Steve Naroff7cae42b2009-07-10 23:34:53 +00002378 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002379 // If the pointee types are the same (ignoring qualifications),
2380 // then this is not a pointer conversion.
2381 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2382 FromObjCPtr->getPointeeType()))
2383 return false;
2384
Douglas Gregorab209d82015-07-07 03:58:42 +00002385 // Conversion between Objective-C pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00002386 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002387 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2388 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002389 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002390 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2391 FromObjCPtr->getPointeeType()))
2392 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002393 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002394 ToObjCPtr->getPointeeType(),
2395 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002396 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002397 return true;
2398 }
2399
2400 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2401 // Okay: this is some kind of implicit downcast of Objective-C
2402 // interfaces, which is permitted. However, we're going to
2403 // complain about it.
2404 IncompatibleObjC = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002405 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002406 ToObjCPtr->getPointeeType(),
2407 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002408 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002409 return true;
2410 }
Mike Stump11289f42009-09-09 15:08:12 +00002411 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00002412 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00002413 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002414 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002415 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002416 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002417 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002418 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002419 // to a block pointer type.
2420 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002421 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002422 return true;
2423 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002424 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002425 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002426 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002427 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002428 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002429 // pointer to any object.
Douglas Gregoraec25842011-04-26 23:16:46 +00002430 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002431 return true;
2432 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002433 else
Douglas Gregora119f102008-12-19 19:13:09 +00002434 return false;
2435
Douglas Gregor033f56d2008-12-23 00:53:59 +00002436 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002437 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002438 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00002439 else if (const BlockPointerType *FromBlockPtr =
2440 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00002441 FromPointeeType = FromBlockPtr->getPointeeType();
2442 else
Douglas Gregora119f102008-12-19 19:13:09 +00002443 return false;
2444
Douglas Gregora119f102008-12-19 19:13:09 +00002445 // If we have pointers to pointers, recursively check whether this
2446 // is an Objective-C conversion.
2447 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2448 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2449 IncompatibleObjC)) {
2450 // We always complain about this conversion.
2451 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002452 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002453 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002454 return true;
2455 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002456 // Allow conversion of pointee being objective-c pointer to another one;
2457 // as in I* to id.
2458 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2459 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2460 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2461 IncompatibleObjC)) {
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002462
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002463 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002464 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002465 return true;
2466 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002467
Douglas Gregor033f56d2008-12-23 00:53:59 +00002468 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00002469 // differences in the argument and result types are in Objective-C
2470 // pointer conversions. If so, we permit the conversion (but
2471 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00002472 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002473 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002474 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002475 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002476 if (FromFunctionType && ToFunctionType) {
2477 // If the function types are exactly the same, this isn't an
2478 // Objective-C pointer conversion.
2479 if (Context.getCanonicalType(FromPointeeType)
2480 == Context.getCanonicalType(ToPointeeType))
2481 return false;
2482
2483 // Perform the quick checks that will tell us whether these
2484 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002485 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Douglas Gregora119f102008-12-19 19:13:09 +00002486 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2487 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2488 return false;
2489
2490 bool HasObjCConversion = false;
Alp Toker314cc812014-01-25 16:55:45 +00002491 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2492 Context.getCanonicalType(ToFunctionType->getReturnType())) {
Douglas Gregora119f102008-12-19 19:13:09 +00002493 // Okay, the types match exactly. Nothing to do.
Alp Toker314cc812014-01-25 16:55:45 +00002494 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2495 ToFunctionType->getReturnType(),
Douglas Gregora119f102008-12-19 19:13:09 +00002496 ConvertedType, IncompatibleObjC)) {
2497 // Okay, we have an Objective-C pointer conversion.
2498 HasObjCConversion = true;
2499 } else {
2500 // Function types are too different. Abort.
2501 return false;
2502 }
Mike Stump11289f42009-09-09 15:08:12 +00002503
Douglas Gregora119f102008-12-19 19:13:09 +00002504 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002505 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Douglas Gregora119f102008-12-19 19:13:09 +00002506 ArgIdx != NumArgs; ++ArgIdx) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002507 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2508 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Douglas Gregora119f102008-12-19 19:13:09 +00002509 if (Context.getCanonicalType(FromArgType)
2510 == Context.getCanonicalType(ToArgType)) {
2511 // Okay, the types match exactly. Nothing to do.
2512 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2513 ConvertedType, IncompatibleObjC)) {
2514 // Okay, we have an Objective-C pointer conversion.
2515 HasObjCConversion = true;
2516 } else {
2517 // Argument types are too different. Abort.
2518 return false;
2519 }
2520 }
2521
2522 if (HasObjCConversion) {
2523 // We had an Objective-C conversion. Allow this pointer
2524 // conversion, but complain about it.
Douglas Gregoraec25842011-04-26 23:16:46 +00002525 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002526 IncompatibleObjC = true;
2527 return true;
2528 }
2529 }
2530
Sebastian Redl72b597d2009-01-25 19:43:20 +00002531 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002532}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002533
John McCall31168b02011-06-15 23:02:42 +00002534/// \brief Determine whether this is an Objective-C writeback conversion,
2535/// used for parameter passing when performing automatic reference counting.
2536///
2537/// \param FromType The type we're converting form.
2538///
2539/// \param ToType The type we're converting to.
2540///
2541/// \param ConvertedType The type that will be produced after applying
2542/// this conversion.
2543bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2544 QualType &ConvertedType) {
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002545 if (!getLangOpts().ObjCAutoRefCount ||
John McCall31168b02011-06-15 23:02:42 +00002546 Context.hasSameUnqualifiedType(FromType, ToType))
2547 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002548
John McCall31168b02011-06-15 23:02:42 +00002549 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2550 QualType ToPointee;
2551 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2552 ToPointee = ToPointer->getPointeeType();
2553 else
2554 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002555
John McCall31168b02011-06-15 23:02:42 +00002556 Qualifiers ToQuals = ToPointee.getQualifiers();
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002557 if (!ToPointee->isObjCLifetimeType() ||
John McCall31168b02011-06-15 23:02:42 +00002558 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall18ce25e2012-02-08 00:46:36 +00002559 !ToQuals.withoutObjCLifetime().empty())
John McCall31168b02011-06-15 23:02:42 +00002560 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002561
John McCall31168b02011-06-15 23:02:42 +00002562 // Argument must be a pointer to __strong to __weak.
2563 QualType FromPointee;
2564 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2565 FromPointee = FromPointer->getPointeeType();
2566 else
2567 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002568
John McCall31168b02011-06-15 23:02:42 +00002569 Qualifiers FromQuals = FromPointee.getQualifiers();
2570 if (!FromPointee->isObjCLifetimeType() ||
2571 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2572 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2573 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002574
John McCall31168b02011-06-15 23:02:42 +00002575 // Make sure that we have compatible qualifiers.
2576 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2577 if (!ToQuals.compatiblyIncludes(FromQuals))
2578 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002579
John McCall31168b02011-06-15 23:02:42 +00002580 // Remove qualifiers from the pointee type we're converting from; they
2581 // aren't used in the compatibility check belong, and we'll be adding back
2582 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2583 FromPointee = FromPointee.getUnqualifiedType();
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002584
John McCall31168b02011-06-15 23:02:42 +00002585 // The unqualified form of the pointee types must be compatible.
2586 ToPointee = ToPointee.getUnqualifiedType();
2587 bool IncompatibleObjC;
2588 if (Context.typesAreCompatible(FromPointee, ToPointee))
2589 FromPointee = ToPointee;
2590 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2591 IncompatibleObjC))
2592 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002593
John McCall31168b02011-06-15 23:02:42 +00002594 /// \brief Construct the type we're converting to, which is a pointer to
2595 /// __autoreleasing pointee.
2596 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2597 ConvertedType = Context.getPointerType(FromPointee);
2598 return true;
2599}
2600
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002601bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2602 QualType& ConvertedType) {
2603 QualType ToPointeeType;
2604 if (const BlockPointerType *ToBlockPtr =
2605 ToType->getAs<BlockPointerType>())
2606 ToPointeeType = ToBlockPtr->getPointeeType();
2607 else
2608 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002609
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002610 QualType FromPointeeType;
2611 if (const BlockPointerType *FromBlockPtr =
2612 FromType->getAs<BlockPointerType>())
2613 FromPointeeType = FromBlockPtr->getPointeeType();
2614 else
2615 return false;
2616 // We have pointer to blocks, check whether the only
2617 // differences in the argument and result types are in Objective-C
2618 // pointer conversions. If so, we permit the conversion.
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002619
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002620 const FunctionProtoType *FromFunctionType
2621 = FromPointeeType->getAs<FunctionProtoType>();
2622 const FunctionProtoType *ToFunctionType
2623 = ToPointeeType->getAs<FunctionProtoType>();
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002624
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002625 if (!FromFunctionType || !ToFunctionType)
2626 return false;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002627
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002628 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002629 return true;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002630
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002631 // Perform the quick checks that will tell us whether these
2632 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002633 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002634 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2635 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002636
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002637 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2638 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2639 if (FromEInfo != ToEInfo)
2640 return false;
2641
2642 bool IncompatibleObjC = false;
Alp Toker314cc812014-01-25 16:55:45 +00002643 if (Context.hasSameType(FromFunctionType->getReturnType(),
2644 ToFunctionType->getReturnType())) {
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002645 // Okay, the types match exactly. Nothing to do.
2646 } else {
Alp Toker314cc812014-01-25 16:55:45 +00002647 QualType RHS = FromFunctionType->getReturnType();
2648 QualType LHS = ToFunctionType->getReturnType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002649 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002650 !RHS.hasQualifiers() && LHS.hasQualifiers())
2651 LHS = LHS.getUnqualifiedType();
2652
2653 if (Context.hasSameType(RHS,LHS)) {
2654 // OK exact match.
2655 } else if (isObjCPointerConversion(RHS, LHS,
2656 ConvertedType, IncompatibleObjC)) {
2657 if (IncompatibleObjC)
2658 return false;
2659 // Okay, we have an Objective-C pointer conversion.
2660 }
2661 else
2662 return false;
2663 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002664
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002665 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002666 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002667 ArgIdx != NumArgs; ++ArgIdx) {
2668 IncompatibleObjC = false;
Alp Toker9cacbab2014-01-20 20:26:09 +00002669 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2670 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002671 if (Context.hasSameType(FromArgType, ToArgType)) {
2672 // Okay, the types match exactly. Nothing to do.
2673 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2674 ConvertedType, IncompatibleObjC)) {
2675 if (IncompatibleObjC)
2676 return false;
2677 // Okay, we have an Objective-C pointer conversion.
2678 } else
2679 // Argument types are too different. Abort.
2680 return false;
2681 }
Akira Hatanaka98a49332017-09-22 00:41:05 +00002682
2683 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
2684 bool CanUseToFPT, CanUseFromFPT;
2685 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
2686 CanUseToFPT, CanUseFromFPT,
2687 NewParamInfos))
Fariborz Jahanian97676972011-09-28 21:52:05 +00002688 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002689
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002690 ConvertedType = ToType;
2691 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002692}
2693
Richard Trieucaff2472011-11-23 22:32:32 +00002694enum {
2695 ft_default,
2696 ft_different_class,
2697 ft_parameter_arity,
2698 ft_parameter_mismatch,
2699 ft_return_type,
Richard Smith3c4f8d22016-10-16 17:54:23 +00002700 ft_qualifer_mismatch,
2701 ft_noexcept
Richard Trieucaff2472011-11-23 22:32:32 +00002702};
2703
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002704/// Attempts to get the FunctionProtoType from a Type. Handles
2705/// MemberFunctionPointers properly.
2706static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2707 if (auto *FPT = FromType->getAs<FunctionProtoType>())
2708 return FPT;
2709
2710 if (auto *MPT = FromType->getAs<MemberPointerType>())
2711 return MPT->getPointeeType()->getAs<FunctionProtoType>();
2712
2713 return nullptr;
2714}
2715
Richard Trieucaff2472011-11-23 22:32:32 +00002716/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2717/// function types. Catches different number of parameter, mismatch in
2718/// parameter types, and different return types.
2719void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2720 QualType FromType, QualType ToType) {
Richard Trieu96ed5b62011-12-13 23:19:45 +00002721 // If either type is not valid, include no extra info.
2722 if (FromType.isNull() || ToType.isNull()) {
2723 PDiag << ft_default;
2724 return;
2725 }
2726
Richard Trieucaff2472011-11-23 22:32:32 +00002727 // Get the function type from the pointers.
2728 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2729 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2730 *ToMember = ToType->getAs<MemberPointerType>();
Richard Trieu9098c9f2014-05-22 01:39:16 +00002731 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
Richard Trieucaff2472011-11-23 22:32:32 +00002732 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2733 << QualType(FromMember->getClass(), 0);
2734 return;
2735 }
2736 FromType = FromMember->getPointeeType();
2737 ToType = ToMember->getPointeeType();
Richard Trieucaff2472011-11-23 22:32:32 +00002738 }
2739
Richard Trieu96ed5b62011-12-13 23:19:45 +00002740 if (FromType->isPointerType())
2741 FromType = FromType->getPointeeType();
2742 if (ToType->isPointerType())
2743 ToType = ToType->getPointeeType();
2744
2745 // Remove references.
Richard Trieucaff2472011-11-23 22:32:32 +00002746 FromType = FromType.getNonReferenceType();
2747 ToType = ToType.getNonReferenceType();
2748
Richard Trieucaff2472011-11-23 22:32:32 +00002749 // Don't print extra info for non-specialized template functions.
2750 if (FromType->isInstantiationDependentType() &&
2751 !FromType->getAs<TemplateSpecializationType>()) {
2752 PDiag << ft_default;
2753 return;
2754 }
2755
Richard Trieu96ed5b62011-12-13 23:19:45 +00002756 // No extra info for same types.
2757 if (Context.hasSameType(FromType, ToType)) {
2758 PDiag << ft_default;
2759 return;
2760 }
2761
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002762 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2763 *ToFunction = tryGetFunctionProtoType(ToType);
Richard Trieucaff2472011-11-23 22:32:32 +00002764
2765 // Both types need to be function types.
2766 if (!FromFunction || !ToFunction) {
2767 PDiag << ft_default;
2768 return;
2769 }
2770
Alp Toker9cacbab2014-01-20 20:26:09 +00002771 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2772 PDiag << ft_parameter_arity << ToFunction->getNumParams()
2773 << FromFunction->getNumParams();
Richard Trieucaff2472011-11-23 22:32:32 +00002774 return;
2775 }
2776
2777 // Handle different parameter types.
2778 unsigned ArgPos;
Alp Toker9cacbab2014-01-20 20:26:09 +00002779 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
Richard Trieucaff2472011-11-23 22:32:32 +00002780 PDiag << ft_parameter_mismatch << ArgPos + 1
Alp Toker9cacbab2014-01-20 20:26:09 +00002781 << ToFunction->getParamType(ArgPos)
2782 << FromFunction->getParamType(ArgPos);
Richard Trieucaff2472011-11-23 22:32:32 +00002783 return;
2784 }
2785
2786 // Handle different return type.
Alp Toker314cc812014-01-25 16:55:45 +00002787 if (!Context.hasSameType(FromFunction->getReturnType(),
2788 ToFunction->getReturnType())) {
2789 PDiag << ft_return_type << ToFunction->getReturnType()
2790 << FromFunction->getReturnType();
Richard Trieucaff2472011-11-23 22:32:32 +00002791 return;
2792 }
2793
2794 unsigned FromQuals = FromFunction->getTypeQuals(),
2795 ToQuals = ToFunction->getTypeQuals();
2796 if (FromQuals != ToQuals) {
2797 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2798 return;
2799 }
2800
Richard Smith3c4f8d22016-10-16 17:54:23 +00002801 // Handle exception specification differences on canonical type (in C++17
2802 // onwards).
2803 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2804 ->isNothrow(Context) !=
2805 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2806 ->isNothrow(Context)) {
2807 PDiag << ft_noexcept;
2808 return;
2809 }
2810
Richard Trieucaff2472011-11-23 22:32:32 +00002811 // Unable to find a difference, so add no extra info.
2812 PDiag << ft_default;
2813}
2814
Alp Toker9cacbab2014-01-20 20:26:09 +00002815/// FunctionParamTypesAreEqual - This routine checks two function proto types
Douglas Gregor2039ca02011-12-15 17:15:07 +00002816/// for equality of their argument types. Caller has already checked that
Eli Friedman5f508952013-06-18 22:41:37 +00002817/// they have same number of arguments. If the parameters are different,
2818/// ArgPos will have the parameter index of the first different parameter.
Alp Toker9cacbab2014-01-20 20:26:09 +00002819bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2820 const FunctionProtoType *NewType,
2821 unsigned *ArgPos) {
2822 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2823 N = NewType->param_type_begin(),
2824 E = OldType->param_type_end();
2825 O && (O != E); ++O, ++N) {
Richard Trieu4b03d982013-08-09 21:42:32 +00002826 if (!Context.hasSameType(O->getUnqualifiedType(),
2827 N->getUnqualifiedType())) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002828 if (ArgPos)
2829 *ArgPos = O - OldType->param_type_begin();
Larisse Voufo4154f462013-08-06 03:57:41 +00002830 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002831 }
2832 }
2833 return true;
2834}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002835
Douglas Gregor39c16d42008-10-24 04:54:22 +00002836/// CheckPointerConversion - Check the pointer conversion from the
2837/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00002838/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00002839/// conversions for which IsPointerConversion has already returned
2840/// true. It returns true and produces a diagnostic if there was an
2841/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002842bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002843 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002844 CXXCastPath& BasePath,
George Burgess IV60bc9722016-01-13 23:36:34 +00002845 bool IgnoreBaseAccess,
2846 bool Diagnose) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002847 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00002848 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002849
John McCall8cb679e2010-11-15 09:13:47 +00002850 Kind = CK_BitCast;
2851
George Burgess IV60bc9722016-01-13 23:36:34 +00002852 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
Argyrios Kyrtzidis3e3305d2014-02-02 05:26:43 +00002853 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
George Burgess IV60bc9722016-01-13 23:36:34 +00002854 Expr::NPCK_ZeroExpression) {
David Blaikie1c7c8f72012-08-08 17:33:31 +00002855 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2856 DiagRuntimeBehavior(From->getExprLoc(), From,
2857 PDiag(diag::warn_impcast_bool_to_null_pointer)
2858 << ToType << From->getSourceRange());
2859 else if (!isUnevaluatedContext())
2860 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2861 << ToType << From->getSourceRange();
2862 }
John McCall9320b872011-09-09 05:25:32 +00002863 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2864 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002865 QualType FromPointeeType = FromPtrType->getPointeeType(),
2866 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00002867
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002868 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2869 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002870 // We must have a derived-to-base conversion. Check an
2871 // ambiguous or inaccessible conversion.
George Burgess IV60bc9722016-01-13 23:36:34 +00002872 unsigned InaccessibleID = 0;
2873 unsigned AmbigiousID = 0;
2874 if (Diagnose) {
2875 InaccessibleID = diag::err_upcast_to_inaccessible_base;
2876 AmbigiousID = diag::err_ambiguous_derived_to_base_conv;
2877 }
2878 if (CheckDerivedToBaseConversion(
2879 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID,
2880 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
2881 &BasePath, IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002882 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002883
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002884 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00002885 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002886 }
David Majnemer6bf02822015-10-31 08:42:14 +00002887
George Burgess IV60bc9722016-01-13 23:36:34 +00002888 if (Diagnose && !IsCStyleOrFunctionalCast &&
2889 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
David Majnemer6bf02822015-10-31 08:42:14 +00002890 assert(getLangOpts().MSVCCompat &&
2891 "this should only be possible with MSVCCompat!");
2892 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
2893 << From->getSourceRange();
2894 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00002895 }
John McCall9320b872011-09-09 05:25:32 +00002896 } else if (const ObjCObjectPointerType *ToPtrType =
2897 ToType->getAs<ObjCObjectPointerType>()) {
2898 if (const ObjCObjectPointerType *FromPtrType =
2899 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002900 // Objective-C++ conversions are always okay.
2901 // FIXME: We should have a different class of conversions for the
2902 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00002903 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002904 return false;
John McCall9320b872011-09-09 05:25:32 +00002905 } else if (FromType->isBlockPointerType()) {
2906 Kind = CK_BlockPointerToObjCPointerCast;
2907 } else {
2908 Kind = CK_CPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00002909 }
John McCall9320b872011-09-09 05:25:32 +00002910 } else if (ToType->isBlockPointerType()) {
2911 if (!FromType->isBlockPointerType())
2912 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002913 }
John McCall8cb679e2010-11-15 09:13:47 +00002914
2915 // We shouldn't fall into this case unless it's valid for other
2916 // reasons.
2917 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2918 Kind = CK_NullToPointer;
2919
Douglas Gregor39c16d42008-10-24 04:54:22 +00002920 return false;
2921}
2922
Sebastian Redl72b597d2009-01-25 19:43:20 +00002923/// IsMemberPointerConversion - Determines whether the conversion of the
2924/// expression From, which has the (possibly adjusted) type FromType, can be
2925/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2926/// If so, returns true and places the converted type (that might differ from
2927/// ToType in its cv-qualifiers at some level) into ConvertedType.
2928bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002929 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00002930 bool InOverloadResolution,
2931 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002932 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002933 if (!ToTypePtr)
2934 return false;
2935
2936 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00002937 if (From->isNullPointerConstant(Context,
2938 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2939 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002940 ConvertedType = ToType;
2941 return true;
2942 }
2943
2944 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002945 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002946 if (!FromTypePtr)
2947 return false;
2948
2949 // A pointer to member of B can be converted to a pointer to member of D,
2950 // where D is derived from B (C++ 4.11p2).
2951 QualType FromClass(FromTypePtr->getClass(), 0);
2952 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002953
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002954 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00002955 IsDerivedFrom(From->getLocStart(), ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002956 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2957 ToClass.getTypePtr());
2958 return true;
2959 }
2960
2961 return false;
2962}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002963
Sebastian Redl72b597d2009-01-25 19:43:20 +00002964/// CheckMemberPointerConversion - Check the member pointer conversion from the
2965/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002966/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002967/// for which IsMemberPointerConversion has already returned true. It returns
2968/// true and produces a diagnostic if there was an error, or returns false
2969/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002970bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002971 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002972 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002973 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002974 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002975 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00002976 if (!FromPtrType) {
2977 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002978 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00002979 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00002980 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00002981 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00002982 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00002983 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00002984
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002985 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00002986 assert(ToPtrType && "No member pointer cast has a target type "
2987 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002988
Sebastian Redled8f2002009-01-28 18:33:18 +00002989 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2990 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002991
Sebastian Redled8f2002009-01-28 18:33:18 +00002992 // FIXME: What about dependent types?
2993 assert(FromClass->isRecordType() && "Pointer into non-class.");
2994 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002995
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002996 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002997 /*DetectVirtual=*/true);
Richard Smith0f59cb32015-12-18 21:45:41 +00002998 bool DerivationOkay =
2999 IsDerivedFrom(From->getLocStart(), ToClass, FromClass, Paths);
Sebastian Redled8f2002009-01-28 18:33:18 +00003000 assert(DerivationOkay &&
3001 "Should not have been called if derivation isn't OK.");
3002 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00003003
Sebastian Redled8f2002009-01-28 18:33:18 +00003004 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3005 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00003006 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3007 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3008 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3009 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00003010 }
Sebastian Redled8f2002009-01-28 18:33:18 +00003011
Douglas Gregor89ee6822009-02-28 01:32:25 +00003012 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00003013 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3014 << FromClass << ToClass << QualType(VBase, 0)
3015 << From->getSourceRange();
3016 return true;
3017 }
3018
John McCall5b0829a2010-02-10 09:31:12 +00003019 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00003020 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3021 Paths.front(),
3022 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00003023
Anders Carlssond7923c62009-08-22 23:33:40 +00003024 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00003025 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00003026 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00003027 return false;
3028}
3029
Douglas Gregorc9f019a2013-11-08 02:04:24 +00003030/// Determine whether the lifetime conversion between the two given
3031/// qualifiers sets is nontrivial.
3032static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3033 Qualifiers ToQuals) {
3034 // Converting anything to const __unsafe_unretained is trivial.
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003035 if (ToQuals.hasConst() &&
Douglas Gregorc9f019a2013-11-08 02:04:24 +00003036 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3037 return false;
3038
3039 return true;
3040}
3041
Douglas Gregor9a657932008-10-21 23:43:52 +00003042/// IsQualificationConversion - Determines whether the conversion from
3043/// an rvalue of type FromType to ToType is a qualification conversion
3044/// (C++ 4.4).
John McCall31168b02011-06-15 23:02:42 +00003045///
3046/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3047/// when the qualification conversion involves a change in the Objective-C
3048/// object lifetime.
Mike Stump11289f42009-09-09 15:08:12 +00003049bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003050Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00003051 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor9a657932008-10-21 23:43:52 +00003052 FromType = Context.getCanonicalType(FromType);
3053 ToType = Context.getCanonicalType(ToType);
John McCall31168b02011-06-15 23:02:42 +00003054 ObjCLifetimeConversion = false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003055
Douglas Gregor9a657932008-10-21 23:43:52 +00003056 // If FromType and ToType are the same type, this is not a
3057 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00003058 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00003059 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00003060
Douglas Gregor9a657932008-10-21 23:43:52 +00003061 // (C++ 4.4p4):
3062 // A conversion can add cv-qualifiers at levels other than the first
3063 // in multi-level pointers, subject to the following rules: [...]
3064 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00003065 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003066 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00003067 // Within each iteration of the loop, we check the qualifiers to
3068 // determine if this still looks like a qualification
3069 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003070 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00003071 // until there are no more pointers or pointers-to-members left to
3072 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003073 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00003074
Douglas Gregor90609aa2011-04-25 18:40:17 +00003075 Qualifiers FromQuals = FromType.getQualifiers();
3076 Qualifiers ToQuals = ToType.getQualifiers();
Andrey Bokhanko45d41322016-05-11 18:38:21 +00003077
3078 // Ignore __unaligned qualifier if this type is void.
3079 if (ToType.getUnqualifiedType()->isVoidType())
3080 FromQuals.removeUnaligned();
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003081
John McCall31168b02011-06-15 23:02:42 +00003082 // Objective-C ARC:
3083 // Check Objective-C lifetime conversions.
3084 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
3085 UnwrappedAnyPointer) {
3086 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00003087 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3088 ObjCLifetimeConversion = true;
John McCall31168b02011-06-15 23:02:42 +00003089 FromQuals.removeObjCLifetime();
3090 ToQuals.removeObjCLifetime();
3091 } else {
3092 // Qualification conversions cannot cast between different
3093 // Objective-C lifetime qualifiers.
3094 return false;
3095 }
3096 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003097
Douglas Gregorf30053d2011-05-08 06:09:53 +00003098 // Allow addition/removal of GC attributes but not changing GC attributes.
3099 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3100 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3101 FromQuals.removeObjCGCAttr();
3102 ToQuals.removeObjCGCAttr();
3103 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003104
Douglas Gregor9a657932008-10-21 23:43:52 +00003105 // -- for every j > 0, if const is in cv 1,j then const is in cv
3106 // 2,j, and similarly for volatile.
Douglas Gregor90609aa2011-04-25 18:40:17 +00003107 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor9a657932008-10-21 23:43:52 +00003108 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003109
Douglas Gregor9a657932008-10-21 23:43:52 +00003110 // -- if the cv 1,j and cv 2,j are different, then const is in
3111 // every cv for 0 < k < j.
Douglas Gregor90609aa2011-04-25 18:40:17 +00003112 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003113 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00003114 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003115
Douglas Gregor9a657932008-10-21 23:43:52 +00003116 // Keep track of whether all prior cv-qualifiers in the "to" type
3117 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00003118 PreviousToQualsIncludeConst
Douglas Gregor90609aa2011-04-25 18:40:17 +00003119 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003120 }
Douglas Gregor9a657932008-10-21 23:43:52 +00003121
3122 // We are left with FromType and ToType being the pointee types
3123 // after unwrapping the original FromType and ToType the same number
3124 // of types. If we unwrapped any pointers, and if FromType and
3125 // ToType have the same unqualified type (since we checked
3126 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003127 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00003128}
3129
Douglas Gregorc79862f2012-04-12 17:51:55 +00003130/// \brief - Determine whether this is a conversion from a scalar type to an
3131/// atomic type.
3132///
3133/// If successful, updates \c SCS's second and third steps in the conversion
3134/// sequence to finish the conversion.
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00003135static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3136 bool InOverloadResolution,
3137 StandardConversionSequence &SCS,
3138 bool CStyle) {
Douglas Gregorc79862f2012-04-12 17:51:55 +00003139 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3140 if (!ToAtomic)
3141 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003142
Douglas Gregorc79862f2012-04-12 17:51:55 +00003143 StandardConversionSequence InnerSCS;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003144 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
Douglas Gregorc79862f2012-04-12 17:51:55 +00003145 InOverloadResolution, InnerSCS,
3146 CStyle, /*AllowObjCWritebackConversion=*/false))
3147 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003148
Douglas Gregorc79862f2012-04-12 17:51:55 +00003149 SCS.Second = InnerSCS.Second;
3150 SCS.setToType(1, InnerSCS.getToType(1));
3151 SCS.Third = InnerSCS.Third;
3152 SCS.QualificationIncludesObjCLifetime
3153 = InnerSCS.QualificationIncludesObjCLifetime;
3154 SCS.setToType(2, InnerSCS.getToType(2));
3155 return true;
3156}
3157
Sebastian Redle5417162012-03-27 18:33:03 +00003158static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3159 CXXConstructorDecl *Constructor,
3160 QualType Type) {
3161 const FunctionProtoType *CtorType =
3162 Constructor->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00003163 if (CtorType->getNumParams() > 0) {
3164 QualType FirstArg = CtorType->getParamType(0);
Sebastian Redle5417162012-03-27 18:33:03 +00003165 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3166 return true;
3167 }
3168 return false;
3169}
3170
Sebastian Redl82ace982012-02-11 23:51:08 +00003171static OverloadingResult
3172IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3173 CXXRecordDecl *To,
3174 UserDefinedConversionSequence &User,
3175 OverloadCandidateSet &CandidateSet,
3176 bool AllowExplicit) {
Richard Smith67ef14f2017-09-26 18:37:55 +00003177 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
Richard Smithc2bebe92016-05-11 20:37:46 +00003178 for (auto *D : S.LookupConstructors(To)) {
3179 auto Info = getConstructorInfo(D);
Richard Smith5179eb72016-06-28 19:03:57 +00003180 if (!Info)
Richard Smithc2bebe92016-05-11 20:37:46 +00003181 continue;
Sebastian Redl82ace982012-02-11 23:51:08 +00003182
Richard Smithc2bebe92016-05-11 20:37:46 +00003183 bool Usable = !Info.Constructor->isInvalidDecl() &&
3184 S.isInitListConstructor(Info.Constructor) &&
3185 (AllowExplicit || !Info.Constructor->isExplicit());
Sebastian Redl82ace982012-02-11 23:51:08 +00003186 if (Usable) {
Sebastian Redle5417162012-03-27 18:33:03 +00003187 // If the first argument is (a reference to) the target type,
3188 // suppress conversions.
Richard Smithc2bebe92016-05-11 20:37:46 +00003189 bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3190 S.Context, Info.Constructor, ToType);
3191 if (Info.ConstructorTmpl)
3192 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3193 /*ExplicitArgs*/ nullptr, From,
3194 CandidateSet, SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00003195 else
Richard Smithc2bebe92016-05-11 20:37:46 +00003196 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3197 CandidateSet, SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00003198 }
3199 }
3200
3201 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3202
3203 OverloadCandidateSet::iterator Best;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003204 switch (auto Result =
3205 CandidateSet.BestViableFunction(S, From->getLocStart(),
Richard Smith67ef14f2017-09-26 18:37:55 +00003206 Best)) {
Fariborz Jahaniandcf06f42015-04-14 17:21:58 +00003207 case OR_Deleted:
Sebastian Redl82ace982012-02-11 23:51:08 +00003208 case OR_Success: {
3209 // Record the standard conversion we used and the conversion function.
3210 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Sebastian Redl82ace982012-02-11 23:51:08 +00003211 QualType ThisType = Constructor->getThisType(S.Context);
3212 // Initializer lists don't have conversions as such.
3213 User.Before.setAsIdentityConversion();
3214 User.HadMultipleCandidates = HadMultipleCandidates;
3215 User.ConversionFunction = Constructor;
3216 User.FoundConversionFunction = Best->FoundDecl;
3217 User.After.setAsIdentityConversion();
3218 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3219 User.After.setAllToTypes(ToType);
Fariborz Jahaniandcf06f42015-04-14 17:21:58 +00003220 return Result;
Sebastian Redl82ace982012-02-11 23:51:08 +00003221 }
3222
3223 case OR_No_Viable_Function:
3224 return OR_No_Viable_Function;
Sebastian Redl82ace982012-02-11 23:51:08 +00003225 case OR_Ambiguous:
3226 return OR_Ambiguous;
3227 }
3228
3229 llvm_unreachable("Invalid OverloadResult!");
3230}
3231
Douglas Gregor576e98c2009-01-30 23:27:23 +00003232/// Determines whether there is a user-defined conversion sequence
3233/// (C++ [over.ics.user]) that converts expression From to the type
3234/// ToType. If such a conversion exists, User will contain the
3235/// user-defined conversion sequence that performs such a conversion
3236/// and this routine will return true. Otherwise, this routine returns
3237/// false and User is unspecified.
3238///
Douglas Gregor576e98c2009-01-30 23:27:23 +00003239/// \param AllowExplicit true if the conversion should consider C++0x
3240/// "explicit" conversion functions as well as non-explicit conversion
3241/// functions (C++0x [class.conv.fct]p2).
Douglas Gregor4b60a152013-11-07 22:34:54 +00003242///
3243/// \param AllowObjCConversionOnExplicit true if the conversion should
3244/// allow an extra Objective-C pointer conversion on uses of explicit
3245/// constructors. Requires \c AllowExplicit to also be set.
John McCall5c32be02010-08-24 20:38:10 +00003246static OverloadingResult
3247IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl82ace982012-02-11 23:51:08 +00003248 UserDefinedConversionSequence &User,
3249 OverloadCandidateSet &CandidateSet,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003250 bool AllowExplicit,
3251 bool AllowObjCConversionOnExplicit) {
Douglas Gregor2ee1d992013-11-08 01:20:25 +00003252 assert(AllowExplicit || !AllowObjCConversionOnExplicit);
Richard Smith67ef14f2017-09-26 18:37:55 +00003253 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
Douglas Gregor4b60a152013-11-07 22:34:54 +00003254
Douglas Gregor5ab11652010-04-17 22:01:05 +00003255 // Whether we will only visit constructors.
3256 bool ConstructorsOnly = false;
3257
3258 // If the type we are conversion to is a class type, enumerate its
3259 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003260 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00003261 // C++ [over.match.ctor]p1:
3262 // When objects of class type are direct-initialized (8.5), or
3263 // copy-initialized from an expression of the same or a
3264 // derived class type (8.5), overload resolution selects the
3265 // constructor. [...] For copy-initialization, the candidate
3266 // functions are all the converting constructors (12.3.1) of
3267 // that class. The argument list is the expression-list within
3268 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00003269 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00003270 (From->getType()->getAs<RecordType>() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00003271 S.IsDerivedFrom(From->getLocStart(), From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00003272 ConstructorsOnly = true;
3273
Richard Smithdb0ac552015-12-18 22:40:25 +00003274 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003275 // We're not going to find any constructors.
3276 } else if (CXXRecordDecl *ToRecordDecl
3277 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003278
3279 Expr **Args = &From;
3280 unsigned NumArgs = 1;
3281 bool ListInitializing = false;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003282 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003283 // But first, see if there is an init-list-constructor that will work.
Sebastian Redl82ace982012-02-11 23:51:08 +00003284 OverloadingResult Result = IsInitializerListConstructorConversion(
3285 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3286 if (Result != OR_No_Viable_Function)
3287 return Result;
3288 // Never mind.
Richard Smith67ef14f2017-09-26 18:37:55 +00003289 CandidateSet.clear(
3290 OverloadCandidateSet::CSK_InitByUserDefinedConversion);
Sebastian Redl82ace982012-02-11 23:51:08 +00003291
3292 // If we're list-initializing, we pass the individual elements as
3293 // arguments, not the entire list.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003294 Args = InitList->getInits();
3295 NumArgs = InitList->getNumInits();
3296 ListInitializing = true;
3297 }
3298
Richard Smithc2bebe92016-05-11 20:37:46 +00003299 for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3300 auto Info = getConstructorInfo(D);
Richard Smith5179eb72016-06-28 19:03:57 +00003301 if (!Info)
Richard Smithc2bebe92016-05-11 20:37:46 +00003302 continue;
John McCalla0296f72010-03-19 07:35:19 +00003303
Richard Smithc2bebe92016-05-11 20:37:46 +00003304 bool Usable = !Info.Constructor->isInvalidDecl();
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003305 if (ListInitializing)
Richard Smithc2bebe92016-05-11 20:37:46 +00003306 Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit());
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003307 else
Richard Smithc2bebe92016-05-11 20:37:46 +00003308 Usable = Usable &&
3309 Info.Constructor->isConvertingConstructor(AllowExplicit);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003310 if (Usable) {
Sebastian Redld9170b02012-03-20 21:24:14 +00003311 bool SuppressUserConversions = !ConstructorsOnly;
3312 if (SuppressUserConversions && ListInitializing) {
3313 SuppressUserConversions = false;
3314 if (NumArgs == 1) {
3315 // If the first argument is (a reference to) the target type,
3316 // suppress conversions.
Sebastian Redle5417162012-03-27 18:33:03 +00003317 SuppressUserConversions = isFirstArgumentCompatibleWithType(
Richard Smithc2bebe92016-05-11 20:37:46 +00003318 S.Context, Info.Constructor, ToType);
Sebastian Redld9170b02012-03-20 21:24:14 +00003319 }
3320 }
Richard Smithc2bebe92016-05-11 20:37:46 +00003321 if (Info.ConstructorTmpl)
3322 S.AddTemplateOverloadCandidate(
3323 Info.ConstructorTmpl, Info.FoundDecl,
3324 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3325 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003326 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00003327 // Allow one user-defined conversion when user specifies a
3328 // From->ToType conversion via an static cast (c-style, etc).
Richard Smithc2bebe92016-05-11 20:37:46 +00003329 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003330 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003331 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003332 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00003333 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003334 }
3335 }
3336
Douglas Gregor5ab11652010-04-17 22:01:05 +00003337 // Enumerate conversion functions, if we're allowed to.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003338 if (ConstructorsOnly || isa<InitListExpr>(From)) {
Richard Smithdb0ac552015-12-18 22:40:25 +00003339 } else if (!S.isCompleteType(From->getLocStart(), From->getType())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003340 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00003341 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00003342 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00003343 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003344 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3345 // Add all of the conversion functions as candidates.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00003346 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3347 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00003348 DeclAccessPair FoundDecl = I.getPair();
3349 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003350 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3351 if (isa<UsingShadowDecl>(D))
3352 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3353
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003354 CXXConversionDecl *Conv;
3355 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00003356 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3357 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003358 else
John McCallda4458e2010-03-31 01:36:47 +00003359 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003360
3361 if (AllowExplicit || !Conv->isExplicit()) {
3362 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00003363 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3364 ActingContext, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003365 CandidateSet,
3366 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003367 else
John McCall5c32be02010-08-24 20:38:10 +00003368 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003369 From, ToType, CandidateSet,
3370 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003371 }
3372 }
3373 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00003374 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003375
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003376 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3377
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003378 OverloadCandidateSet::iterator Best;
Richard Smith48372b62015-01-27 03:30:40 +00003379 switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(),
Richard Smith67ef14f2017-09-26 18:37:55 +00003380 Best)) {
John McCall5c32be02010-08-24 20:38:10 +00003381 case OR_Success:
Richard Smith48372b62015-01-27 03:30:40 +00003382 case OR_Deleted:
John McCall5c32be02010-08-24 20:38:10 +00003383 // Record the standard conversion we used and the conversion function.
3384 if (CXXConstructorDecl *Constructor
3385 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3386 // C++ [over.ics.user]p1:
3387 // If the user-defined conversion is specified by a
3388 // constructor (12.3.1), the initial standard conversion
3389 // sequence converts the source type to the type required by
3390 // the argument of the constructor.
3391 //
3392 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003393 if (isa<InitListExpr>(From)) {
3394 // Initializer lists don't have conversions as such.
3395 User.Before.setAsIdentityConversion();
3396 } else {
3397 if (Best->Conversions[0].isEllipsis())
3398 User.EllipsisConversion = true;
3399 else {
3400 User.Before = Best->Conversions[0].Standard;
3401 User.EllipsisConversion = false;
3402 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003403 }
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003404 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003405 User.ConversionFunction = Constructor;
John McCall30909032011-09-21 08:36:56 +00003406 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003407 User.After.setAsIdentityConversion();
3408 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3409 User.After.setAllToTypes(ToType);
Richard Smith48372b62015-01-27 03:30:40 +00003410 return Result;
David Blaikie8a40f702012-01-17 06:56:22 +00003411 }
3412 if (CXXConversionDecl *Conversion
John McCall5c32be02010-08-24 20:38:10 +00003413 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3414 // C++ [over.ics.user]p1:
3415 //
3416 // [...] If the user-defined conversion is specified by a
3417 // conversion function (12.3.2), the initial standard
3418 // conversion sequence converts the source type to the
3419 // implicit object parameter of the conversion function.
3420 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003421 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003422 User.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00003423 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003424 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00003425
John McCall5c32be02010-08-24 20:38:10 +00003426 // C++ [over.ics.user]p2:
3427 // The second standard conversion sequence converts the
3428 // result of the user-defined conversion to the target type
3429 // for the sequence. Since an implicit conversion sequence
3430 // is an initialization, the special rules for
3431 // initialization by user-defined conversion apply when
3432 // selecting the best user-defined conversion for a
3433 // user-defined conversion sequence (see 13.3.3 and
3434 // 13.3.3.1).
3435 User.After = Best->FinalConversion;
Richard Smith48372b62015-01-27 03:30:40 +00003436 return Result;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003437 }
David Blaikie8a40f702012-01-17 06:56:22 +00003438 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003439
John McCall5c32be02010-08-24 20:38:10 +00003440 case OR_No_Viable_Function:
3441 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003442
John McCall5c32be02010-08-24 20:38:10 +00003443 case OR_Ambiguous:
3444 return OR_Ambiguous;
3445 }
3446
David Blaikie8a40f702012-01-17 06:56:22 +00003447 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003448}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003449
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003450bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00003451Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003452 ImplicitConversionSequence ICS;
Richard Smith100b24a2014-04-17 01:52:14 +00003453 OverloadCandidateSet CandidateSet(From->getExprLoc(),
3454 OverloadCandidateSet::CSK_Normal);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003455 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00003456 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003457 CandidateSet, false, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00003458 if (OvResult == OR_Ambiguous)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003459 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3460 << From->getType() << ToType << From->getSourceRange();
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003461 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
Larisse Voufo70bb43a2013-06-27 03:36:30 +00003462 if (!RequireCompleteType(From->getLocStart(), ToType,
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003463 diag::err_typecheck_nonviable_condition_incomplete,
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003464 From->getType(), From->getSourceRange()))
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003465 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
Nick Lewycky08426e22015-08-25 22:18:46 +00003466 << false << From->getType() << From->getSourceRange() << ToType;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003467 } else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003468 return false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003469 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003470 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003471}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003472
Douglas Gregor2837aa22012-02-22 17:32:19 +00003473/// \brief Compare the user-defined conversion functions or constructors
3474/// of two user-defined conversion sequences to determine whether any ordering
3475/// is possible.
3476static ImplicitConversionSequence::CompareKind
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003477compareConversionFunctions(Sema &S, FunctionDecl *Function1,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003478 FunctionDecl *Function2) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003479 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
Douglas Gregor2837aa22012-02-22 17:32:19 +00003480 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003481
Douglas Gregor2837aa22012-02-22 17:32:19 +00003482 // Objective-C++:
3483 // If both conversion functions are implicitly-declared conversions from
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003484 // a lambda closure type to a function pointer and a block pointer,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003485 // respectively, always prefer the conversion to a function pointer,
3486 // because the function pointer is more lightweight and is more likely
3487 // to keep code working.
Ted Kremenek8d265c22014-04-01 07:23:18 +00003488 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003489 if (!Conv1)
3490 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003491
Douglas Gregor2837aa22012-02-22 17:32:19 +00003492 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3493 if (!Conv2)
3494 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003495
Douglas Gregor2837aa22012-02-22 17:32:19 +00003496 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3497 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3498 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3499 if (Block1 != Block2)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003500 return Block1 ? ImplicitConversionSequence::Worse
3501 : ImplicitConversionSequence::Better;
Douglas Gregor2837aa22012-02-22 17:32:19 +00003502 }
3503
3504 return ImplicitConversionSequence::Indistinguishable;
3505}
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003506
3507static bool hasDeprecatedStringLiteralToCharPtrConversion(
3508 const ImplicitConversionSequence &ICS) {
3509 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3510 (ICS.isUserDefined() &&
3511 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3512}
3513
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003514/// CompareImplicitConversionSequences - Compare two implicit
3515/// conversion sequences to determine whether one is better than the
3516/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00003517static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +00003518CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +00003519 const ImplicitConversionSequence& ICS1,
3520 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003521{
3522 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3523 // conversion sequences (as defined in 13.3.3.1)
3524 // -- a standard conversion sequence (13.3.3.1.1) is a better
3525 // conversion sequence than a user-defined conversion sequence or
3526 // an ellipsis conversion sequence, and
3527 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3528 // conversion sequence than an ellipsis conversion sequence
3529 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00003530 //
John McCall0d1da222010-01-12 00:44:57 +00003531 // C++0x [over.best.ics]p10:
3532 // For the purpose of ranking implicit conversion sequences as
3533 // described in 13.3.3.2, the ambiguous conversion sequence is
3534 // treated as a user-defined sequence that is indistinguishable
3535 // from any other user-defined conversion sequence.
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003536
3537 // String literal to 'char *' conversion has been deprecated in C++03. It has
3538 // been removed from C++11. We still accept this conversion, if it happens at
3539 // the best viable function. Otherwise, this conversion is considered worse
3540 // than ellipsis conversion. Consider this as an extension; this is not in the
3541 // standard. For example:
3542 //
3543 // int &f(...); // #1
3544 // void f(char*); // #2
3545 // void g() { int &r = f("foo"); }
3546 //
3547 // In C++03, we pick #2 as the best viable function.
3548 // In C++11, we pick #1 as the best viable function, because ellipsis
3549 // conversion is better than string-literal to char* conversion (since there
3550 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3551 // convert arguments, #2 would be the best viable function in C++11.
3552 // If the best viable function has this conversion, a warning will be issued
3553 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3554
3555 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3556 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3557 hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3558 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3559 ? ImplicitConversionSequence::Worse
3560 : ImplicitConversionSequence::Better;
3561
Douglas Gregor5ab11652010-04-17 22:01:05 +00003562 if (ICS1.getKindRank() < ICS2.getKindRank())
3563 return ImplicitConversionSequence::Better;
David Blaikie8a40f702012-01-17 06:56:22 +00003564 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor5ab11652010-04-17 22:01:05 +00003565 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003566
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00003567 // The following checks require both conversion sequences to be of
3568 // the same kind.
3569 if (ICS1.getKind() != ICS2.getKind())
3570 return ImplicitConversionSequence::Indistinguishable;
3571
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003572 ImplicitConversionSequence::CompareKind Result =
3573 ImplicitConversionSequence::Indistinguishable;
3574
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003575 // Two implicit conversion sequences of the same form are
3576 // indistinguishable conversion sequences unless one of the
3577 // following rules apply: (C++ 13.3.3.2p3):
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003578
Larisse Voufo19d08672015-01-27 18:47:05 +00003579 // List-initialization sequence L1 is a better conversion sequence than
3580 // list-initialization sequence L2 if:
3581 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3582 // if not that,
NAKAMURA Takumib01d86b2015-02-25 11:02:00 +00003583 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
Larisse Voufo19d08672015-01-27 18:47:05 +00003584 // and N1 is smaller than N2.,
3585 // even if one of the other rules in this paragraph would otherwise apply.
3586 if (!ICS1.isBad()) {
3587 if (ICS1.isStdInitializerListElement() &&
3588 !ICS2.isStdInitializerListElement())
3589 return ImplicitConversionSequence::Better;
3590 if (!ICS1.isStdInitializerListElement() &&
3591 ICS2.isStdInitializerListElement())
3592 return ImplicitConversionSequence::Worse;
3593 }
3594
John McCall0d1da222010-01-12 00:44:57 +00003595 if (ICS1.isStandard())
Larisse Voufo19d08672015-01-27 18:47:05 +00003596 // Standard conversion sequence S1 is a better conversion sequence than
3597 // standard conversion sequence S2 if [...]
Richard Smith0f59cb32015-12-18 21:45:41 +00003598 Result = CompareStandardConversionSequences(S, Loc,
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003599 ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00003600 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003601 // User-defined conversion sequence U1 is a better conversion
3602 // sequence than another user-defined conversion sequence U2 if
3603 // they contain the same user-defined conversion function or
3604 // constructor and if the second standard conversion sequence of
3605 // U1 is better than the second standard conversion sequence of
3606 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00003607 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003608 ICS2.UserDefined.ConversionFunction)
Richard Smith0f59cb32015-12-18 21:45:41 +00003609 Result = CompareStandardConversionSequences(S, Loc,
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003610 ICS1.UserDefined.After,
3611 ICS2.UserDefined.After);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003612 else
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003613 Result = compareConversionFunctions(S,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003614 ICS1.UserDefined.ConversionFunction,
3615 ICS2.UserDefined.ConversionFunction);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003616 }
3617
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003618 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003619}
3620
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003621static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3622 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3623 Qualifiers Quals;
3624 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003625 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003626 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003627
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003628 return Context.hasSameUnqualifiedType(T1, T2);
3629}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003630
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003631// Per 13.3.3.2p3, compare the given standard conversion sequences to
3632// determine if one is a proper subset of the other.
3633static ImplicitConversionSequence::CompareKind
3634compareStandardConversionSubsets(ASTContext &Context,
3635 const StandardConversionSequence& SCS1,
3636 const StandardConversionSequence& SCS2) {
3637 ImplicitConversionSequence::CompareKind Result
3638 = ImplicitConversionSequence::Indistinguishable;
3639
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003640 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00003641 // any non-identity conversion sequence
Douglas Gregor377c1092011-06-05 06:15:20 +00003642 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3643 return ImplicitConversionSequence::Better;
3644 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3645 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003646
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003647 if (SCS1.Second != SCS2.Second) {
3648 if (SCS1.Second == ICK_Identity)
3649 Result = ImplicitConversionSequence::Better;
3650 else if (SCS2.Second == ICK_Identity)
3651 Result = ImplicitConversionSequence::Worse;
3652 else
3653 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003654 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003655 return ImplicitConversionSequence::Indistinguishable;
3656
3657 if (SCS1.Third == SCS2.Third) {
3658 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3659 : ImplicitConversionSequence::Indistinguishable;
3660 }
3661
3662 if (SCS1.Third == ICK_Identity)
3663 return Result == ImplicitConversionSequence::Worse
3664 ? ImplicitConversionSequence::Indistinguishable
3665 : ImplicitConversionSequence::Better;
3666
3667 if (SCS2.Third == ICK_Identity)
3668 return Result == ImplicitConversionSequence::Better
3669 ? ImplicitConversionSequence::Indistinguishable
3670 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003671
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003672 return ImplicitConversionSequence::Indistinguishable;
3673}
3674
Douglas Gregore696ebb2011-01-26 14:52:12 +00003675/// \brief Determine whether one of the given reference bindings is better
3676/// than the other based on what kind of bindings they are.
Richard Smith19172c42014-07-14 02:28:44 +00003677static bool
3678isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3679 const StandardConversionSequence &SCS2) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003680 // C++0x [over.ics.rank]p3b4:
3681 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3682 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003683 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00003684 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003685 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00003686 // reference*.
3687 //
3688 // FIXME: Rvalue references. We're going rogue with the above edits,
3689 // because the semantics in the current C++0x working paper (N3225 at the
3690 // time of this writing) break the standard definition of std::forward
3691 // and std::reference_wrapper when dealing with references to functions.
3692 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00003693 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3694 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3695 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003696
Douglas Gregore696ebb2011-01-26 14:52:12 +00003697 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3698 SCS2.IsLvalueReference) ||
3699 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
Richard Smith19172c42014-07-14 02:28:44 +00003700 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
Douglas Gregore696ebb2011-01-26 14:52:12 +00003701}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003702
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003703/// CompareStandardConversionSequences - Compare two standard
3704/// conversion sequences to determine whether one is better than the
3705/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00003706static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +00003707CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +00003708 const StandardConversionSequence& SCS1,
3709 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003710{
3711 // Standard conversion sequence S1 is a better conversion sequence
3712 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3713
3714 // -- S1 is a proper subsequence of S2 (comparing the conversion
3715 // sequences in the canonical form defined by 13.3.3.1.1,
3716 // excluding any Lvalue Transformation; the identity conversion
3717 // sequence is considered to be a subsequence of any
3718 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003719 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00003720 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003721 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003722
3723 // -- the rank of S1 is better than the rank of S2 (by the rules
3724 // defined below), or, if not that,
3725 ImplicitConversionRank Rank1 = SCS1.getRank();
3726 ImplicitConversionRank Rank2 = SCS2.getRank();
3727 if (Rank1 < Rank2)
3728 return ImplicitConversionSequence::Better;
3729 else if (Rank2 < Rank1)
3730 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003731
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003732 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3733 // are indistinguishable unless one of the following rules
3734 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00003735
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003736 // A conversion that is not a conversion of a pointer, or
3737 // pointer to member, to bool is better than another conversion
3738 // that is such a conversion.
3739 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3740 return SCS2.isPointerConversionToBool()
3741 ? ImplicitConversionSequence::Better
3742 : ImplicitConversionSequence::Worse;
3743
Douglas Gregor5c407d92008-10-23 00:40:37 +00003744 // C++ [over.ics.rank]p4b2:
3745 //
3746 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003747 // conversion of B* to A* is better than conversion of B* to
3748 // void*, and conversion of A* to void* is better than conversion
3749 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00003750 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003751 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00003752 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003753 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003754 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3755 // Exactly one of the conversion sequences is a conversion to
3756 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003757 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3758 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003759 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3760 // Neither conversion sequence converts to a void pointer; compare
3761 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003762 if (ImplicitConversionSequence::CompareKind DerivedCK
Richard Smith0f59cb32015-12-18 21:45:41 +00003763 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003764 return DerivedCK;
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003765 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3766 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003767 // Both conversion sequences are conversions to void
3768 // pointers. Compare the source types to determine if there's an
3769 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00003770 QualType FromType1 = SCS1.getFromType();
3771 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003772
3773 // Adjust the types we're converting from via the array-to-pointer
3774 // conversion, if we need to.
3775 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003776 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003777 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003778 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003779
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003780 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3781 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003782
Richard Smith0f59cb32015-12-18 21:45:41 +00003783 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003784 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00003785 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003786 return ImplicitConversionSequence::Worse;
3787
3788 // Objective-C++: If one interface is more specific than the
3789 // other, it is the better one.
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003790 const ObjCObjectPointerType* FromObjCPtr1
3791 = FromType1->getAs<ObjCObjectPointerType>();
3792 const ObjCObjectPointerType* FromObjCPtr2
3793 = FromType2->getAs<ObjCObjectPointerType>();
3794 if (FromObjCPtr1 && FromObjCPtr2) {
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003795 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003796 FromObjCPtr2);
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003797 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003798 FromObjCPtr1);
3799 if (AssignLeft != AssignRight) {
3800 return AssignLeft? ImplicitConversionSequence::Better
3801 : ImplicitConversionSequence::Worse;
3802 }
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003803 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003804 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003805
3806 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3807 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00003808 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00003809 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003810 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003811
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003812 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003813 // Check for a better reference binding based on the kind of bindings.
3814 if (isBetterReferenceBindingKind(SCS1, SCS2))
3815 return ImplicitConversionSequence::Better;
3816 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3817 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003818
Sebastian Redlb28b4072009-03-22 23:49:27 +00003819 // C++ [over.ics.rank]p3b4:
3820 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3821 // which the references refer are the same type except for
3822 // top-level cv-qualifiers, and the type to which the reference
3823 // initialized by S2 refers is more cv-qualified than the type
3824 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003825 QualType T1 = SCS1.getToType(2);
3826 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003827 T1 = S.Context.getCanonicalType(T1);
3828 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003829 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003830 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3831 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003832 if (UnqualT1 == UnqualT2) {
John McCall31168b02011-06-15 23:02:42 +00003833 // Objective-C++ ARC: If the references refer to objects with different
3834 // lifetimes, prefer bindings that don't change lifetime.
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003835 if (SCS1.ObjCLifetimeConversionBinding !=
John McCall31168b02011-06-15 23:02:42 +00003836 SCS2.ObjCLifetimeConversionBinding) {
3837 return SCS1.ObjCLifetimeConversionBinding
3838 ? ImplicitConversionSequence::Worse
3839 : ImplicitConversionSequence::Better;
3840 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003841
Chandler Carruth8e543b32010-12-12 08:17:55 +00003842 // If the type is an array type, promote the element qualifiers to the
3843 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003844 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003845 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003846 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003847 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003848 if (T2.isMoreQualifiedThan(T1))
3849 return ImplicitConversionSequence::Better;
3850 else if (T1.isMoreQualifiedThan(T2))
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003851 return ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003852 }
3853 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003854
Francois Pichet08d2fa02011-09-18 21:37:37 +00003855 // In Microsoft mode, prefer an integral conversion to a
3856 // floating-to-integral conversion if the integral conversion
3857 // is between types of the same size.
3858 // For example:
3859 // void f(float);
3860 // void f(int);
3861 // int main {
3862 // long a;
3863 // f(a);
3864 // }
3865 // Here, MSVC will call f(int) instead of generating a compile error
3866 // as clang will do in standard mode.
Alp Tokerbfa39342014-01-14 12:51:41 +00003867 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3868 SCS2.Second == ICK_Floating_Integral &&
Francois Pichet08d2fa02011-09-18 21:37:37 +00003869 S.Context.getTypeSize(SCS1.getFromType()) ==
Alp Tokerbfa39342014-01-14 12:51:41 +00003870 S.Context.getTypeSize(SCS1.getToType(2)))
Francois Pichet08d2fa02011-09-18 21:37:37 +00003871 return ImplicitConversionSequence::Better;
3872
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003873 return ImplicitConversionSequence::Indistinguishable;
3874}
3875
3876/// CompareQualificationConversions - Compares two standard conversion
3877/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00003878/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
Richard Smith17c00b42014-11-12 01:24:00 +00003879static ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003880CompareQualificationConversions(Sema &S,
3881 const StandardConversionSequence& SCS1,
3882 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00003883 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003884 // -- S1 and S2 differ only in their qualification conversion and
3885 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3886 // cv-qualification signature of type T1 is a proper subset of
3887 // the cv-qualification signature of type T2, and S1 is not the
3888 // deprecated string literal array-to-pointer conversion (4.2).
3889 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3890 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3891 return ImplicitConversionSequence::Indistinguishable;
3892
3893 // FIXME: the example in the standard doesn't use a qualification
3894 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003895 QualType T1 = SCS1.getToType(2);
3896 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003897 T1 = S.Context.getCanonicalType(T1);
3898 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003899 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003900 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3901 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003902
3903 // If the types are the same, we won't learn anything by unwrapped
3904 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003905 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003906 return ImplicitConversionSequence::Indistinguishable;
3907
Chandler Carruth607f38e2009-12-29 07:16:59 +00003908 // If the type is an array type, promote the element qualifiers to the type
3909 // for comparison.
3910 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003911 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003912 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003913 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003914
Mike Stump11289f42009-09-09 15:08:12 +00003915 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003916 = ImplicitConversionSequence::Indistinguishable;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003917
John McCall31168b02011-06-15 23:02:42 +00003918 // Objective-C++ ARC:
3919 // Prefer qualification conversions not involving a change in lifetime
3920 // to qualification conversions that do not change lifetime.
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003921 if (SCS1.QualificationIncludesObjCLifetime !=
John McCall31168b02011-06-15 23:02:42 +00003922 SCS2.QualificationIncludesObjCLifetime) {
3923 Result = SCS1.QualificationIncludesObjCLifetime
3924 ? ImplicitConversionSequence::Worse
3925 : ImplicitConversionSequence::Better;
3926 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003927
John McCall5c32be02010-08-24 20:38:10 +00003928 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003929 // Within each iteration of the loop, we check the qualifiers to
3930 // determine if this still looks like a qualification
3931 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003932 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003933 // until there are no more pointers or pointers-to-members left
3934 // to unwrap. This essentially mimics what
3935 // IsQualificationConversion does, but here we're checking for a
3936 // strict subset of qualifiers.
3937 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3938 // The qualifiers are the same, so this doesn't tell us anything
3939 // about how the sequences rank.
3940 ;
3941 else if (T2.isMoreQualifiedThan(T1)) {
3942 // T1 has fewer qualifiers, so it could be the better sequence.
3943 if (Result == ImplicitConversionSequence::Worse)
3944 // Neither has qualifiers that are a subset of the other's
3945 // qualifiers.
3946 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003947
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003948 Result = ImplicitConversionSequence::Better;
3949 } else if (T1.isMoreQualifiedThan(T2)) {
3950 // T2 has fewer qualifiers, so it could be the better sequence.
3951 if (Result == ImplicitConversionSequence::Better)
3952 // Neither has qualifiers that are a subset of the other's
3953 // qualifiers.
3954 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003955
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003956 Result = ImplicitConversionSequence::Worse;
3957 } else {
3958 // Qualifiers are disjoint.
3959 return ImplicitConversionSequence::Indistinguishable;
3960 }
3961
3962 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00003963 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003964 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003965 }
3966
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003967 // Check that the winning standard conversion sequence isn't using
3968 // the deprecated string literal array to pointer conversion.
3969 switch (Result) {
3970 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003971 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003972 Result = ImplicitConversionSequence::Indistinguishable;
3973 break;
3974
3975 case ImplicitConversionSequence::Indistinguishable:
3976 break;
3977
3978 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003979 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003980 Result = ImplicitConversionSequence::Indistinguishable;
3981 break;
3982 }
3983
3984 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003985}
3986
Douglas Gregor5c407d92008-10-23 00:40:37 +00003987/// CompareDerivedToBaseConversions - Compares two standard conversion
3988/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00003989/// various kinds of derived-to-base conversions (C++
3990/// [over.ics.rank]p4b3). As part of these checks, we also look at
3991/// conversions between Objective-C interface types.
Richard Smith17c00b42014-11-12 01:24:00 +00003992static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +00003993CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +00003994 const StandardConversionSequence& SCS1,
3995 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00003996 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003997 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00003998 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003999 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00004000
4001 // Adjust the types we're converting from via the array-to-pointer
4002 // conversion, if we need to.
4003 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00004004 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00004005 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00004006 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00004007
4008 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00004009 FromType1 = S.Context.getCanonicalType(FromType1);
4010 ToType1 = S.Context.getCanonicalType(ToType1);
4011 FromType2 = S.Context.getCanonicalType(FromType2);
4012 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00004013
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004014 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00004015 //
4016 // If class B is derived directly or indirectly from class A and
4017 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00004018 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004019 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00004020 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00004021 SCS2.Second == ICK_Pointer_Conversion &&
4022 /*FIXME: Remove if Objective-C id conversions get their own rank*/
4023 FromType1->isPointerType() && FromType2->isPointerType() &&
4024 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00004025 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004026 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00004027 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004028 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00004029 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004030 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00004031 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004032 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00004033
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004034 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00004035 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004036 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00004037 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004038 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00004039 return ImplicitConversionSequence::Worse;
4040 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004041
4042 // -- conversion of B* to A* is better than conversion of C* to A*,
4043 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004044 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004045 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004046 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004047 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00004048 }
4049 } else if (SCS1.Second == ICK_Pointer_Conversion &&
4050 SCS2.Second == ICK_Pointer_Conversion) {
4051 const ObjCObjectPointerType *FromPtr1
4052 = FromType1->getAs<ObjCObjectPointerType>();
4053 const ObjCObjectPointerType *FromPtr2
4054 = FromType2->getAs<ObjCObjectPointerType>();
4055 const ObjCObjectPointerType *ToPtr1
4056 = ToType1->getAs<ObjCObjectPointerType>();
4057 const ObjCObjectPointerType *ToPtr2
4058 = ToType2->getAs<ObjCObjectPointerType>();
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00004059
Douglas Gregor058d3de2011-01-31 18:51:41 +00004060 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4061 // Apply the same conversion ranking rules for Objective-C pointer types
4062 // that we do for C++ pointers to class types. However, we employ the
4063 // Objective-C pseudo-subtyping relationship used for assignment of
4064 // Objective-C pointer types.
4065 bool FromAssignLeft
4066 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4067 bool FromAssignRight
4068 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4069 bool ToAssignLeft
4070 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4071 bool ToAssignRight
4072 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
Alex Lorenza9832132017-04-06 13:06:34 +00004073
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00004074 // A conversion to an a non-id object pointer type or qualified 'id'
Douglas Gregor058d3de2011-01-31 18:51:41 +00004075 // type is better than a conversion to 'id'.
4076 if (ToPtr1->isObjCIdType() &&
4077 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4078 return ImplicitConversionSequence::Worse;
4079 if (ToPtr2->isObjCIdType() &&
4080 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4081 return ImplicitConversionSequence::Better;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00004082
4083 // A conversion to a non-id object pointer type is better than a
4084 // conversion to a qualified 'id' type
Douglas Gregor058d3de2011-01-31 18:51:41 +00004085 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4086 return ImplicitConversionSequence::Worse;
4087 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4088 return ImplicitConversionSequence::Better;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00004089
4090 // A conversion to an a non-Class object pointer type or qualified 'Class'
Douglas Gregor058d3de2011-01-31 18:51:41 +00004091 // type is better than a conversion to 'Class'.
4092 if (ToPtr1->isObjCClassType() &&
4093 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4094 return ImplicitConversionSequence::Worse;
4095 if (ToPtr2->isObjCClassType() &&
4096 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4097 return ImplicitConversionSequence::Better;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00004098
4099 // A conversion to a non-Class object pointer type is better than a
Douglas Gregor058d3de2011-01-31 18:51:41 +00004100 // conversion to a qualified 'Class' type.
4101 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4102 return ImplicitConversionSequence::Worse;
4103 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4104 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00004105
Douglas Gregor058d3de2011-01-31 18:51:41 +00004106 // -- "conversion of C* to B* is better than conversion of C* to A*,"
Alex Lorenza9832132017-04-06 13:06:34 +00004107 if (S.Context.hasSameType(FromType1, FromType2) &&
Douglas Gregor058d3de2011-01-31 18:51:41 +00004108 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
Alex Lorenza9832132017-04-06 13:06:34 +00004109 (ToAssignLeft != ToAssignRight)) {
4110 if (FromPtr1->isSpecialized()) {
4111 // "conversion of B<A> * to B * is better than conversion of B * to
4112 // C *.
4113 bool IsFirstSame =
4114 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4115 bool IsSecondSame =
4116 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4117 if (IsFirstSame) {
4118 if (!IsSecondSame)
4119 return ImplicitConversionSequence::Better;
4120 } else if (IsSecondSame)
4121 return ImplicitConversionSequence::Worse;
4122 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00004123 return ToAssignLeft? ImplicitConversionSequence::Worse
4124 : ImplicitConversionSequence::Better;
Alex Lorenza9832132017-04-06 13:06:34 +00004125 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00004126
4127 // -- "conversion of B* to A* is better than conversion of C* to A*,"
4128 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4129 (FromAssignLeft != FromAssignRight))
4130 return FromAssignLeft? ImplicitConversionSequence::Better
4131 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004132 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00004133 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00004134
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00004135 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004136 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4137 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4138 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004139 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004140 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004141 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004142 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004143 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004144 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004145 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004146 ToType2->getAs<MemberPointerType>();
4147 const Type *FromPointeeType1 = FromMemPointer1->getClass();
4148 const Type *ToPointeeType1 = ToMemPointer1->getClass();
4149 const Type *FromPointeeType2 = FromMemPointer2->getClass();
4150 const Type *ToPointeeType2 = ToMemPointer2->getClass();
4151 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4152 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4153 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4154 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00004155 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004156 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004157 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004158 return ImplicitConversionSequence::Worse;
Richard Smith0f59cb32015-12-18 21:45:41 +00004159 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004160 return ImplicitConversionSequence::Better;
4161 }
4162 // conversion of B::* to C::* is better than conversion of A::* to C::*
4163 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004164 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004165 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004166 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004167 return ImplicitConversionSequence::Worse;
4168 }
4169 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004170
Douglas Gregor5ab11652010-04-17 22:01:05 +00004171 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00004172 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00004173 // -- binding of an expression of type C to a reference of type
4174 // B& is better than binding an expression of type C to a
4175 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00004176 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4177 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004178 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004179 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004180 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004181 return ImplicitConversionSequence::Worse;
4182 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004183
Douglas Gregor2fe98832008-11-03 19:09:14 +00004184 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00004185 // -- binding of an expression of type B to a reference of type
4186 // A& is better than binding an expression of type C to a
4187 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00004188 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4189 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004190 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004191 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004192 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004193 return ImplicitConversionSequence::Worse;
4194 }
4195 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004196
Douglas Gregor5c407d92008-10-23 00:40:37 +00004197 return ImplicitConversionSequence::Indistinguishable;
4198}
4199
Douglas Gregor45bb4832013-03-26 23:36:30 +00004200/// \brief Determine whether the given type is valid, e.g., it is not an invalid
4201/// C++ class.
4202static bool isTypeValid(QualType T) {
4203 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4204 return !Record->isInvalidDecl();
4205
4206 return true;
4207}
4208
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004209/// CompareReferenceRelationship - Compare the two types T1 and T2 to
4210/// determine whether they are reference-related,
4211/// reference-compatible, reference-compatible with added
4212/// qualification, or incompatible, for use in C++ initialization by
4213/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4214/// type, and the first type (T1) is the pointee type of the reference
4215/// type being initialized.
4216Sema::ReferenceCompareResult
4217Sema::CompareReferenceRelationship(SourceLocation Loc,
4218 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004219 bool &DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004220 bool &ObjCConversion,
4221 bool &ObjCLifetimeConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004222 assert(!OrigT1->isReferenceType() &&
4223 "T1 must be the pointee type of the reference type");
4224 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4225
4226 QualType T1 = Context.getCanonicalType(OrigT1);
4227 QualType T2 = Context.getCanonicalType(OrigT2);
4228 Qualifiers T1Quals, T2Quals;
4229 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4230 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4231
4232 // C++ [dcl.init.ref]p4:
4233 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4234 // reference-related to "cv2 T2" if T1 is the same type as T2, or
4235 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004236 DerivedToBase = false;
4237 ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004238 ObjCLifetimeConversion = false;
Richard Smith1be59c52016-10-22 01:32:19 +00004239 QualType ConvertedT2;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004240 if (UnqualT1 == UnqualT2) {
4241 // Nothing to do.
Richard Smithdb0ac552015-12-18 22:40:25 +00004242 } else if (isCompleteType(Loc, OrigT2) &&
Douglas Gregor45bb4832013-03-26 23:36:30 +00004243 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00004244 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004245 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004246 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4247 UnqualT2->isObjCObjectOrInterfaceType() &&
4248 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4249 ObjCConversion = true;
Richard Smith1be59c52016-10-22 01:32:19 +00004250 else if (UnqualT2->isFunctionType() &&
4251 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2))
4252 // C++1z [dcl.init.ref]p4:
4253 // cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept
4254 // function" and T1 is "function"
4255 //
4256 // We extend this to also apply to 'noreturn', so allow any function
4257 // conversion between function types.
4258 return Ref_Compatible;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004259 else
4260 return Ref_Incompatible;
4261
4262 // At this point, we know that T1 and T2 are reference-related (at
4263 // least).
4264
4265 // If the type is an array type, promote the element qualifiers to the type
4266 // for comparison.
4267 if (isa<ArrayType>(T1) && T1Quals)
4268 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4269 if (isa<ArrayType>(T2) && T2Quals)
4270 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4271
4272 // C++ [dcl.init.ref]p4:
4273 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4274 // reference-related to T2 and cv1 is the same cv-qualification
4275 // as, or greater cv-qualification than, cv2. For purposes of
4276 // overload resolution, cases for which cv1 is greater
4277 // cv-qualification than cv2 are identified as
4278 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregord517d552011-04-28 17:56:11 +00004279 //
4280 // Note that we also require equivalence of Objective-C GC and address-space
4281 // qualifiers when performing these computations, so that e.g., an int in
4282 // address space 1 is not reference-compatible with an int in address
4283 // space 2.
John McCall31168b02011-06-15 23:02:42 +00004284 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4285 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00004286 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4287 ObjCLifetimeConversion = true;
4288
John McCall31168b02011-06-15 23:02:42 +00004289 T1Quals.removeObjCLifetime();
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00004290 T2Quals.removeObjCLifetime();
John McCall31168b02011-06-15 23:02:42 +00004291 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00004292
Andrey Bokhanko45d41322016-05-11 18:38:21 +00004293 // MS compiler ignores __unaligned qualifier for references; do the same.
4294 T1Quals.removeUnaligned();
4295 T2Quals.removeUnaligned();
4296
Richard Smithce766292016-10-21 23:01:55 +00004297 if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004298 return Ref_Compatible;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004299 else
4300 return Ref_Related;
4301}
4302
George Burgess IVd5c7e7c2017-01-14 05:19:34 +00004303/// \brief Look for a user-defined conversion to a value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00004304/// with DeclType. Return true if something definite is found.
4305static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00004306FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4307 QualType DeclType, SourceLocation DeclLoc,
4308 Expr *Init, QualType T2, bool AllowRvalues,
4309 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004310 assert(T2->isRecordType() && "Can only find conversions of record types.");
4311 CXXRecordDecl *T2RecordDecl
4312 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4313
Richard Smith67ef14f2017-09-26 18:37:55 +00004314 OverloadCandidateSet CandidateSet(
4315 DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004316 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4317 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004318 NamedDecl *D = *I;
4319 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4320 if (isa<UsingShadowDecl>(D))
4321 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4322
4323 FunctionTemplateDecl *ConvTemplate
4324 = dyn_cast<FunctionTemplateDecl>(D);
4325 CXXConversionDecl *Conv;
4326 if (ConvTemplate)
4327 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4328 else
4329 Conv = cast<CXXConversionDecl>(D);
4330
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004331 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00004332 // explicit conversions, skip it.
4333 if (!AllowExplicit && Conv->isExplicit())
4334 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004335
Douglas Gregor836a7e82010-08-11 02:15:33 +00004336 if (AllowRvalues) {
4337 bool DerivedToBase = false;
4338 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004339 bool ObjCLifetimeConversion = false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00004340
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004341 // If we are initializing an rvalue reference, don't permit conversion
4342 // functions that return lvalues.
4343 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4344 const ReferenceType *RefType
4345 = Conv->getConversionType()->getAs<LValueReferenceType>();
4346 if (RefType && !RefType->getPointeeType()->isFunctionType())
4347 continue;
4348 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00004349
Douglas Gregor836a7e82010-08-11 02:15:33 +00004350 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00004351 S.CompareReferenceRelationship(
4352 DeclLoc,
4353 Conv->getConversionType().getNonReferenceType()
4354 .getUnqualifiedType(),
4355 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCall31168b02011-06-15 23:02:42 +00004356 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth8e543b32010-12-12 08:17:55 +00004357 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00004358 continue;
4359 } else {
4360 // If the conversion function doesn't return a reference type,
4361 // it can't be considered for this conversion. An rvalue reference
4362 // is only acceptable if its referencee is a function type.
4363
4364 const ReferenceType *RefType =
4365 Conv->getConversionType()->getAs<ReferenceType>();
4366 if (!RefType ||
4367 (!RefType->isLValueReferenceType() &&
4368 !RefType->getPointeeType()->isFunctionType()))
4369 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00004370 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004371
Douglas Gregor836a7e82010-08-11 02:15:33 +00004372 if (ConvTemplate)
4373 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004374 Init, DeclType, CandidateSet,
4375 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor836a7e82010-08-11 02:15:33 +00004376 else
4377 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004378 DeclType, CandidateSet,
4379 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redld92badf2010-06-30 18:13:39 +00004380 }
4381
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004382 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4383
Sebastian Redld92badf2010-06-30 18:13:39 +00004384 OverloadCandidateSet::iterator Best;
Richard Smith67ef14f2017-09-26 18:37:55 +00004385 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004386 case OR_Success:
4387 // C++ [over.ics.ref]p1:
4388 //
4389 // [...] If the parameter binds directly to the result of
4390 // applying a conversion function to the argument
4391 // expression, the implicit conversion sequence is a
4392 // user-defined conversion sequence (13.3.3.1.2), with the
4393 // second standard conversion sequence either an identity
4394 // conversion or, if the conversion function returns an
4395 // entity of a type that is a derived class of the parameter
4396 // type, a derived-to-base Conversion.
4397 if (!Best->FinalConversion.DirectBinding)
4398 return false;
4399
4400 ICS.setUserDefined();
4401 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4402 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004403 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redld92badf2010-06-30 18:13:39 +00004404 ICS.UserDefined.ConversionFunction = Best->Function;
John McCall30909032011-09-21 08:36:56 +00004405 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redld92badf2010-06-30 18:13:39 +00004406 ICS.UserDefined.EllipsisConversion = false;
4407 assert(ICS.UserDefined.After.ReferenceBinding &&
4408 ICS.UserDefined.After.DirectBinding &&
4409 "Expected a direct reference binding!");
4410 return true;
4411
4412 case OR_Ambiguous:
4413 ICS.setAmbiguous();
4414 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4415 Cand != CandidateSet.end(); ++Cand)
4416 if (Cand->Viable)
Richard Smithc2bebe92016-05-11 20:37:46 +00004417 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
Sebastian Redld92badf2010-06-30 18:13:39 +00004418 return true;
4419
4420 case OR_No_Viable_Function:
4421 case OR_Deleted:
4422 // There was no suitable conversion, or we found a deleted
4423 // conversion; continue with other checks.
4424 return false;
4425 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004426
David Blaikie8a40f702012-01-17 06:56:22 +00004427 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redld92badf2010-06-30 18:13:39 +00004428}
4429
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004430/// \brief Compute an implicit conversion sequence for reference
4431/// initialization.
4432static ImplicitConversionSequence
Sebastian Redldf888642011-12-03 14:54:30 +00004433TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004434 SourceLocation DeclLoc,
4435 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00004436 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004437 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4438
4439 // Most paths end in a failed conversion.
4440 ImplicitConversionSequence ICS;
4441 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4442
4443 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4444 QualType T2 = Init->getType();
4445
4446 // If the initializer is the address of an overloaded function, try
4447 // to resolve the overloaded function. If all goes well, T2 is the
4448 // type of the resulting function.
4449 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4450 DeclAccessPair Found;
4451 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4452 false, Found))
4453 T2 = Fn->getType();
4454 }
4455
4456 // Compute some basic properties of the types and the initializer.
4457 bool isRValRef = DeclType->isRValueReferenceType();
4458 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004459 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004460 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00004461 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004462 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004463 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004464 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004465
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004466
Sebastian Redld92badf2010-06-30 18:13:39 +00004467 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00004468 // A reference to type "cv1 T1" is initialized by an expression
4469 // of type "cv2 T2" as follows:
4470
Sebastian Redld92badf2010-06-30 18:13:39 +00004471 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00004472 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004473 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4474 // reference-compatible with "cv2 T2," or
4475 //
4476 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
Richard Smithce766292016-10-21 23:01:55 +00004477 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004478 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00004479 // When a parameter of reference type binds directly (8.5.3)
4480 // to an argument expression, the implicit conversion sequence
4481 // is the identity conversion, unless the argument expression
4482 // has a type that is a derived class of the parameter type,
4483 // in which case the implicit conversion sequence is a
4484 // derived-to-base Conversion (13.3.3.1).
4485 ICS.setStandard();
4486 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004487 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4488 : ObjCConversion? ICK_Compatible_Conversion
4489 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00004490 ICS.Standard.Third = ICK_Identity;
4491 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4492 ICS.Standard.setToType(0, T2);
4493 ICS.Standard.setToType(1, T1);
4494 ICS.Standard.setToType(2, T1);
4495 ICS.Standard.ReferenceBinding = true;
4496 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004497 ICS.Standard.IsLvalueReference = !isRValRef;
4498 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4499 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004500 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004501 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Craig Topperc3ec1492014-05-26 06:22:03 +00004502 ICS.Standard.CopyConstructor = nullptr;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004503 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004504
Sebastian Redld92badf2010-06-30 18:13:39 +00004505 // Nothing more to do: the inaccessibility/ambiguity check for
4506 // derived-to-base conversions is suppressed when we're
4507 // computing the implicit conversion sequence (C++
4508 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004509 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00004510 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004511
Sebastian Redld92badf2010-06-30 18:13:39 +00004512 // -- has a class type (i.e., T2 is a class type), where T1 is
4513 // not reference-related to T2, and can be implicitly
4514 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4515 // is reference-compatible with "cv3 T3" 92) (this
4516 // conversion is selected by enumerating the applicable
4517 // conversion functions (13.3.1.6) and choosing the best
4518 // one through overload resolution (13.3)),
4519 if (!SuppressUserConversions && T2->isRecordType() &&
Richard Smithdb0ac552015-12-18 22:40:25 +00004520 S.isCompleteType(DeclLoc, T2) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00004521 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00004522 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4523 Init, T2, /*AllowRvalues=*/false,
4524 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00004525 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004526 }
4527 }
4528
Sebastian Redld92badf2010-06-30 18:13:39 +00004529 // -- Otherwise, the reference shall be an lvalue reference to a
4530 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00004531 // shall be an rvalue reference.
Richard Smithce4f6082012-05-24 04:29:20 +00004532 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004533 return ICS;
4534
Douglas Gregorf143cd52011-01-24 16:14:37 +00004535 // -- If the initializer expression
4536 //
4537 // -- is an xvalue, class prvalue, array prvalue or function
John McCall31168b02011-06-15 23:02:42 +00004538 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Richard Smithce766292016-10-21 23:01:55 +00004539 if (RefRelationship == Sema::Ref_Compatible &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004540 (InitCategory.isXValue() ||
Richard Smithce766292016-10-21 23:01:55 +00004541 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4542 (InitCategory.isLValue() && T2->isFunctionType()))) {
Douglas Gregorf143cd52011-01-24 16:14:37 +00004543 ICS.setStandard();
4544 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004545 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004546 : ObjCConversion? ICK_Compatible_Conversion
4547 : ICK_Identity;
4548 ICS.Standard.Third = ICK_Identity;
4549 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4550 ICS.Standard.setToType(0, T2);
4551 ICS.Standard.setToType(1, T1);
4552 ICS.Standard.setToType(2, T1);
4553 ICS.Standard.ReferenceBinding = true;
4554 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4555 // binding unless we're binding to a class prvalue.
4556 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4557 // allow the use of rvalue references in C++98/03 for the benefit of
4558 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004559 ICS.Standard.DirectBinding =
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004560 S.getLangOpts().CPlusPlus11 ||
Richard Smithb94afe12014-07-14 19:54:05 +00004561 !(InitCategory.isPRValue() || T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00004562 ICS.Standard.IsLvalueReference = !isRValRef;
4563 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004564 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00004565 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004566 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Craig Topperc3ec1492014-05-26 06:22:03 +00004567 ICS.Standard.CopyConstructor = nullptr;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004568 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004569 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00004570 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004571
Douglas Gregorf143cd52011-01-24 16:14:37 +00004572 // -- has a class type (i.e., T2 is a class type), where T1 is not
4573 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004574 // an xvalue, class prvalue, or function lvalue of type
4575 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00004576 // "cv3 T3",
4577 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004578 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00004579 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004580 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004581 // class subobject).
4582 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
Richard Smithdb0ac552015-12-18 22:40:25 +00004583 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004584 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4585 Init, T2, /*AllowRvalues=*/true,
4586 AllowExplicit)) {
4587 // In the second case, if the reference is an rvalue reference
4588 // and the second standard conversion sequence of the
4589 // user-defined conversion sequence includes an lvalue-to-rvalue
4590 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004591 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004592 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4593 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4594
Douglas Gregor95273c32011-01-21 16:36:05 +00004595 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00004596 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004597
Richard Smith19172c42014-07-14 02:28:44 +00004598 // A temporary of function type cannot be created; don't even try.
4599 if (T1->isFunctionType())
4600 return ICS;
4601
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004602 // -- Otherwise, a temporary of type "cv1 T1" is created and
4603 // initialized from the initializer expression using the
4604 // rules for a non-reference copy initialization (8.5). The
4605 // reference is then bound to the temporary. If T1 is
4606 // reference-related to T2, cv1 must be the same
4607 // cv-qualification as, or greater cv-qualification than,
4608 // cv2; otherwise, the program is ill-formed.
4609 if (RefRelationship == Sema::Ref_Related) {
4610 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4611 // we would be reference-compatible or reference-compatible with
4612 // added qualification. But that wasn't the case, so the reference
4613 // initialization fails.
John McCall31168b02011-06-15 23:02:42 +00004614 //
4615 // Note that we only want to check address spaces and cvr-qualifiers here.
Andrey Bokhanko45d41322016-05-11 18:38:21 +00004616 // ObjC GC, lifetime and unaligned qualifiers aren't important.
John McCall31168b02011-06-15 23:02:42 +00004617 Qualifiers T1Quals = T1.getQualifiers();
4618 Qualifiers T2Quals = T2.getQualifiers();
4619 T1Quals.removeObjCGCAttr();
4620 T1Quals.removeObjCLifetime();
4621 T2Quals.removeObjCGCAttr();
4622 T2Quals.removeObjCLifetime();
Andrey Bokhanko45d41322016-05-11 18:38:21 +00004623 // MS compiler ignores __unaligned qualifier for references; do the same.
4624 T1Quals.removeUnaligned();
4625 T2Quals.removeUnaligned();
John McCall31168b02011-06-15 23:02:42 +00004626 if (!T1Quals.compatiblyIncludes(T2Quals))
4627 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004628 }
4629
4630 // If at least one of the types is a class type, the types are not
4631 // related, and we aren't allowed any user conversions, the
4632 // reference binding fails. This case is important for breaking
4633 // recursion, since TryImplicitConversion below will attempt to
4634 // create a temporary through the use of a copy constructor.
4635 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4636 (T1->isRecordType() || T2->isRecordType()))
4637 return ICS;
4638
Douglas Gregorcba72b12011-01-21 05:18:22 +00004639 // If T1 is reference-related to T2 and the reference is an rvalue
4640 // reference, the initializer expression shall not be an lvalue.
4641 if (RefRelationship >= Sema::Ref_Related &&
4642 isRValRef && Init->Classify(S.Context).isLValue())
4643 return ICS;
4644
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004645 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004646 // When a parameter of reference type is not bound directly to
4647 // an argument expression, the conversion sequence is the one
4648 // required to convert the argument expression to the
4649 // underlying type of the reference according to
4650 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4651 // to copy-initializing a temporary of the underlying type with
4652 // the argument expression. Any difference in top-level
4653 // cv-qualification is subsumed by the initialization itself
4654 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00004655 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4656 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004657 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004658 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004659 /*AllowObjCWritebackConversion=*/false,
4660 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004661
4662 // Of course, that's still a reference binding.
4663 if (ICS.isStandard()) {
4664 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004665 ICS.Standard.IsLvalueReference = !isRValRef;
Richard Smith19172c42014-07-14 02:28:44 +00004666 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004667 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004668 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004669 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004670 } else if (ICS.isUserDefined()) {
Richard Smith19172c42014-07-14 02:28:44 +00004671 const ReferenceType *LValRefType =
4672 ICS.UserDefined.ConversionFunction->getReturnType()
4673 ->getAs<LValueReferenceType>();
4674
4675 // C++ [over.ics.ref]p3:
4676 // Except for an implicit object parameter, for which see 13.3.1, a
4677 // standard conversion sequence cannot be formed if it requires [...]
4678 // binding an rvalue reference to an lvalue other than a function
4679 // lvalue.
4680 // Note that the function case is not possible here.
4681 if (DeclType->isRValueReferenceType() && LValRefType) {
4682 // FIXME: This is the wrong BadConversionSequence. The problem is binding
4683 // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4684 // reference to an rvalue!
4685 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4686 return ICS;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004687 }
Richard Smith19172c42014-07-14 02:28:44 +00004688
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004689 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004690 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
Richard Smith19172c42014-07-14 02:28:44 +00004691 ICS.UserDefined.After.BindsToFunctionLvalue = false;
4692 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004693 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4694 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004695 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00004696
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004697 return ICS;
4698}
4699
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004700static ImplicitConversionSequence
4701TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4702 bool SuppressUserConversions,
4703 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004704 bool AllowObjCWritebackConversion,
4705 bool AllowExplicit = false);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004706
4707/// TryListConversion - Try to copy-initialize a value of type ToType from the
4708/// initializer list From.
4709static ImplicitConversionSequence
4710TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4711 bool SuppressUserConversions,
4712 bool InOverloadResolution,
4713 bool AllowObjCWritebackConversion) {
4714 // C++11 [over.ics.list]p1:
4715 // When an argument is an initializer list, it is not an expression and
4716 // special rules apply for converting it to a parameter type.
4717
4718 ImplicitConversionSequence Result;
4719 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4720
Sebastian Redl09edce02012-01-23 22:09:39 +00004721 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004722 // initialized from init lists.
Richard Smithdb0ac552015-12-18 22:40:25 +00004723 if (!S.isCompleteType(From->getLocStart(), ToType))
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004724 return Result;
4725
Larisse Voufo19d08672015-01-27 18:47:05 +00004726 // Per DR1467:
4727 // If the parameter type is a class X and the initializer list has a single
4728 // element of type cv U, where U is X or a class derived from X, the
4729 // implicit conversion sequence is the one required to convert the element
4730 // to the parameter type.
4731 //
4732 // Otherwise, if the parameter type is a character array [... ]
4733 // and the initializer list has a single element that is an
4734 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4735 // implicit conversion sequence is the identity conversion.
4736 if (From->getNumInits() == 1) {
4737 if (ToType->isRecordType()) {
4738 QualType InitType = From->getInit(0)->getType();
4739 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00004740 S.IsDerivedFrom(From->getLocStart(), InitType, ToType))
Larisse Voufo19d08672015-01-27 18:47:05 +00004741 return TryCopyInitialization(S, From->getInit(0), ToType,
4742 SuppressUserConversions,
4743 InOverloadResolution,
4744 AllowObjCWritebackConversion);
4745 }
Richard Smith1bbaba82015-01-27 23:23:39 +00004746 // FIXME: Check the other conditions here: array of character type,
4747 // initializer is a string literal.
4748 if (ToType->isArrayType()) {
Larisse Voufo19d08672015-01-27 18:47:05 +00004749 InitializedEntity Entity =
4750 InitializedEntity::InitializeParameter(S.Context, ToType,
4751 /*Consumed=*/false);
4752 if (S.CanPerformCopyInitialization(Entity, From)) {
4753 Result.setStandard();
4754 Result.Standard.setAsIdentityConversion();
4755 Result.Standard.setFromType(ToType);
4756 Result.Standard.setAllToTypes(ToType);
4757 return Result;
4758 }
4759 }
4760 }
4761
4762 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004763 // C++11 [over.ics.list]p2:
4764 // If the parameter type is std::initializer_list<X> or "array of X" and
4765 // all the elements can be implicitly converted to X, the implicit
4766 // conversion sequence is the worst conversion necessary to convert an
4767 // element of the list to X.
Larisse Voufo19d08672015-01-27 18:47:05 +00004768 //
4769 // C++14 [over.ics.list]p3:
NAKAMURA Takumib01d86b2015-02-25 11:02:00 +00004770 // Otherwise, if the parameter type is "array of N X", if the initializer
Larisse Voufo19d08672015-01-27 18:47:05 +00004771 // list has exactly N elements or if it has fewer than N elements and X is
4772 // default-constructible, and if all the elements of the initializer list
4773 // can be implicitly converted to X, the implicit conversion sequence is
4774 // the worst conversion necessary to convert an element of the list to X.
Richard Smith1bbaba82015-01-27 23:23:39 +00004775 //
4776 // FIXME: We're missing a lot of these checks.
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004777 bool toStdInitializerList = false;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004778 QualType X;
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004779 if (ToType->isArrayType())
Richard Smith0db1ea52012-12-09 06:48:56 +00004780 X = S.Context.getAsArrayType(ToType)->getElementType();
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004781 else
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004782 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004783 if (!X.isNull()) {
4784 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4785 Expr *Init = From->getInit(i);
4786 ImplicitConversionSequence ICS =
4787 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4788 InOverloadResolution,
4789 AllowObjCWritebackConversion);
4790 // If a single element isn't convertible, fail.
4791 if (ICS.isBad()) {
4792 Result = ICS;
4793 break;
4794 }
4795 // Otherwise, look for the worst conversion.
4796 if (Result.isBad() ||
Richard Smith0f59cb32015-12-18 21:45:41 +00004797 CompareImplicitConversionSequences(S, From->getLocStart(), ICS,
4798 Result) ==
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004799 ImplicitConversionSequence::Worse)
4800 Result = ICS;
4801 }
Douglas Gregor0f5c1c02012-04-04 23:09:20 +00004802
4803 // For an empty list, we won't have computed any conversion sequence.
4804 // Introduce the identity conversion sequence.
4805 if (From->getNumInits() == 0) {
4806 Result.setStandard();
4807 Result.Standard.setAsIdentityConversion();
4808 Result.Standard.setFromType(ToType);
4809 Result.Standard.setAllToTypes(ToType);
4810 }
4811
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004812 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004813 return Result;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004814 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004815
Larisse Voufo19d08672015-01-27 18:47:05 +00004816 // C++14 [over.ics.list]p4:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004817 // C++11 [over.ics.list]p3:
4818 // Otherwise, if the parameter is a non-aggregate class X and overload
4819 // resolution chooses a single best constructor [...] the implicit
4820 // conversion sequence is a user-defined conversion sequence. If multiple
4821 // constructors are viable but none is better than the others, the
4822 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004823 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4824 // This function can deal with initializer lists.
Richard Smitha93f1022013-09-06 22:30:28 +00004825 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4826 /*AllowExplicit=*/false,
4827 InOverloadResolution, /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004828 AllowObjCWritebackConversion,
4829 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004830 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004831
Larisse Voufo19d08672015-01-27 18:47:05 +00004832 // C++14 [over.ics.list]p5:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004833 // C++11 [over.ics.list]p4:
4834 // Otherwise, if the parameter has an aggregate type which can be
4835 // initialized from the initializer list [...] the implicit conversion
4836 // sequence is a user-defined conversion sequence.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004837 if (ToType->isAggregateType()) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004838 // Type is an aggregate, argument is an init list. At this point it comes
4839 // down to checking whether the initialization works.
4840 // FIXME: Find out whether this parameter is consumed or not.
Richard Smithb8c0f552016-12-09 18:49:13 +00004841 // FIXME: Expose SemaInit's aggregate initialization code so that we don't
4842 // need to call into the initialization code here; overload resolution
4843 // should not be doing that.
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004844 InitializedEntity Entity =
4845 InitializedEntity::InitializeParameter(S.Context, ToType,
4846 /*Consumed=*/false);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004847 if (S.CanPerformCopyInitialization(Entity, From)) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004848 Result.setUserDefined();
4849 Result.UserDefined.Before.setAsIdentityConversion();
4850 // Initializer lists don't have a type.
4851 Result.UserDefined.Before.setFromType(QualType());
4852 Result.UserDefined.Before.setAllToTypes(QualType());
4853
4854 Result.UserDefined.After.setAsIdentityConversion();
4855 Result.UserDefined.After.setFromType(ToType);
4856 Result.UserDefined.After.setAllToTypes(ToType);
Craig Topperc3ec1492014-05-26 06:22:03 +00004857 Result.UserDefined.ConversionFunction = nullptr;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004858 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004859 return Result;
4860 }
4861
Larisse Voufo19d08672015-01-27 18:47:05 +00004862 // C++14 [over.ics.list]p6:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004863 // C++11 [over.ics.list]p5:
4864 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redldf888642011-12-03 14:54:30 +00004865 if (ToType->isReferenceType()) {
4866 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4867 // mention initializer lists in any way. So we go by what list-
4868 // initialization would do and try to extrapolate from that.
4869
4870 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4871
4872 // If the initializer list has a single element that is reference-related
4873 // to the parameter type, we initialize the reference from that.
4874 if (From->getNumInits() == 1) {
4875 Expr *Init = From->getInit(0);
4876
4877 QualType T2 = Init->getType();
4878
4879 // If the initializer is the address of an overloaded function, try
4880 // to resolve the overloaded function. If all goes well, T2 is the
4881 // type of the resulting function.
4882 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4883 DeclAccessPair Found;
4884 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4885 Init, ToType, false, Found))
4886 T2 = Fn->getType();
4887 }
4888
4889 // Compute some basic properties of the types and the initializer.
4890 bool dummy1 = false;
4891 bool dummy2 = false;
4892 bool dummy3 = false;
4893 Sema::ReferenceCompareResult RefRelationship
4894 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4895 dummy2, dummy3);
4896
Richard Smith4d2bbd72013-09-06 01:22:42 +00004897 if (RefRelationship >= Sema::Ref_Related) {
Richard Smitha93f1022013-09-06 22:30:28 +00004898 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4899 SuppressUserConversions,
4900 /*AllowExplicit=*/false);
Richard Smith4d2bbd72013-09-06 01:22:42 +00004901 }
Sebastian Redldf888642011-12-03 14:54:30 +00004902 }
4903
4904 // Otherwise, we bind the reference to a temporary created from the
4905 // initializer list.
4906 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4907 InOverloadResolution,
4908 AllowObjCWritebackConversion);
4909 if (Result.isFailure())
4910 return Result;
4911 assert(!Result.isEllipsis() &&
4912 "Sub-initialization cannot result in ellipsis conversion.");
4913
4914 // Can we even bind to a temporary?
4915 if (ToType->isRValueReferenceType() ||
4916 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4917 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4918 Result.UserDefined.After;
4919 SCS.ReferenceBinding = true;
4920 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4921 SCS.BindsToRvalue = true;
4922 SCS.BindsToFunctionLvalue = false;
4923 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4924 SCS.ObjCLifetimeConversionBinding = false;
4925 } else
4926 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4927 From, ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004928 return Result;
Sebastian Redldf888642011-12-03 14:54:30 +00004929 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004930
Larisse Voufo19d08672015-01-27 18:47:05 +00004931 // C++14 [over.ics.list]p7:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004932 // C++11 [over.ics.list]p6:
4933 // Otherwise, if the parameter type is not a class:
4934 if (!ToType->isRecordType()) {
Larisse Voufo19d08672015-01-27 18:47:05 +00004935 // - if the initializer list has one element that is not itself an
4936 // initializer list, the implicit conversion sequence is the one
4937 // required to convert the element to the parameter type.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004938 unsigned NumInits = From->getNumInits();
Richard Smith1bbaba82015-01-27 23:23:39 +00004939 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004940 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4941 SuppressUserConversions,
4942 InOverloadResolution,
4943 AllowObjCWritebackConversion);
4944 // - if the initializer list has no elements, the implicit conversion
4945 // sequence is the identity conversion.
4946 else if (NumInits == 0) {
4947 Result.setStandard();
4948 Result.Standard.setAsIdentityConversion();
John McCallb73bc9a2012-04-04 02:40:27 +00004949 Result.Standard.setFromType(ToType);
4950 Result.Standard.setAllToTypes(ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004951 }
4952 return Result;
4953 }
4954
Larisse Voufo19d08672015-01-27 18:47:05 +00004955 // C++14 [over.ics.list]p8:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004956 // C++11 [over.ics.list]p7:
4957 // In all cases other than those enumerated above, no conversion is possible
4958 return Result;
4959}
4960
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004961/// TryCopyInitialization - Try to copy-initialize a value of type
4962/// ToType from the expression From. Return the implicit conversion
4963/// sequence required to pass this argument, which may be a bad
4964/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00004965/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00004966/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004967static ImplicitConversionSequence
4968TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004969 bool SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004970 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004971 bool AllowObjCWritebackConversion,
4972 bool AllowExplicit) {
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004973 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4974 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4975 InOverloadResolution,AllowObjCWritebackConversion);
4976
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004977 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004978 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004979 /*FIXME:*/From->getLocStart(),
4980 SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004981 AllowExplicit);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004982
John McCall5c32be02010-08-24 20:38:10 +00004983 return TryImplicitConversion(S, From, ToType,
4984 SuppressUserConversions,
4985 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004986 InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00004987 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004988 AllowObjCWritebackConversion,
4989 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004990}
4991
Anna Zaks1b068122011-07-28 19:46:48 +00004992static bool TryCopyInitialization(const CanQualType FromQTy,
4993 const CanQualType ToQTy,
4994 Sema &S,
4995 SourceLocation Loc,
4996 ExprValueKind FromVK) {
4997 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4998 ImplicitConversionSequence ICS =
4999 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5000
5001 return !ICS.isBad();
5002}
5003
Douglas Gregor436424c2008-11-18 23:14:02 +00005004/// TryObjectArgumentInitialization - Try to initialize the object
5005/// parameter of the given member function (@c Method) from the
5006/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00005007static ImplicitConversionSequence
Richard Smith0f59cb32015-12-18 21:45:41 +00005008TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00005009 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00005010 CXXMethodDecl *Method,
5011 CXXRecordDecl *ActingContext) {
5012 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00005013 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
5014 // const volatile object.
5015 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
5016 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00005017 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00005018
5019 // Set up the conversion sequence as a "bad" conversion, to allow us
5020 // to exit early.
5021 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00005022
5023 // We need to have an object of class type.
Douglas Gregor02824322011-01-26 19:30:28 +00005024 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005025 FromType = PT->getPointeeType();
5026
Douglas Gregor02824322011-01-26 19:30:28 +00005027 // When we had a pointer, it's implicitly dereferenced, so we
5028 // better have an lvalue.
5029 assert(FromClassification.isLValue());
5030 }
5031
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005032 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00005033
Douglas Gregor02824322011-01-26 19:30:28 +00005034 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005035 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00005036 // parameter is
5037 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005038 // - "lvalue reference to cv X" for functions declared without a
5039 // ref-qualifier or with the & ref-qualifier
5040 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00005041 // ref-qualifier
5042 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005043 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00005044 // cv-qualification on the member function declaration.
5045 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005046 // However, when finding an implicit conversion sequence for the argument, we
Richard Smith122f88d2016-12-06 23:52:28 +00005047 // are not allowed to perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00005048 // (C++ [over.match.funcs]p5). We perform a simplified version of
5049 // reference binding here, that allows class rvalues to bind to
5050 // non-constant references.
5051
Douglas Gregor02824322011-01-26 19:30:28 +00005052 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00005053 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005054 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005055 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00005056 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00005057 ICS.setBad(BadConversionSequence::bad_qualifiers,
Richard Smith03c66d32013-01-26 02:07:32 +00005058 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00005059 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00005060 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005061
5062 // Check that we have either the same type or a derived type. It
5063 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00005064 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00005065 ImplicitConversionKind SecondKind;
5066 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5067 SecondKind = ICK_Identity;
Richard Smith0f59cb32015-12-18 21:45:41 +00005068 } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00005069 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00005070 else {
John McCall65eb8792010-02-25 01:37:24 +00005071 ICS.setBad(BadConversionSequence::unrelated_class,
5072 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00005073 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00005074 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005075
Douglas Gregor02824322011-01-26 19:30:28 +00005076 // Check the ref-qualifier.
5077 switch (Method->getRefQualifier()) {
5078 case RQ_None:
5079 // Do nothing; we don't care about lvalueness or rvalueness.
5080 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005081
Douglas Gregor02824322011-01-26 19:30:28 +00005082 case RQ_LValue:
5083 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
5084 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005085 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00005086 ImplicitParamType);
5087 return ICS;
5088 }
5089 break;
5090
5091 case RQ_RValue:
5092 if (!FromClassification.isRValue()) {
5093 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005094 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00005095 ImplicitParamType);
5096 return ICS;
5097 }
5098 break;
5099 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005100
Douglas Gregor436424c2008-11-18 23:14:02 +00005101 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00005102 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00005103 ICS.Standard.setAsIdentityConversion();
5104 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00005105 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00005106 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00005107 ICS.Standard.ReferenceBinding = true;
5108 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005109 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00005110 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00005111 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5112 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5113 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00005114 return ICS;
5115}
5116
5117/// PerformObjectArgumentInitialization - Perform initialization of
5118/// the implicit object parameter for the given Method with the given
5119/// expression.
John Wiegley01296292011-04-08 18:41:53 +00005120ExprResult
5121Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005122 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00005123 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00005124 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005125 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00005126 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005127 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00005128
Douglas Gregor02824322011-01-26 19:30:28 +00005129 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005130 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005131 FromRecordType = PT->getPointeeType();
5132 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00005133 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005134 } else {
5135 FromRecordType = From->getType();
5136 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00005137 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005138 }
5139
John McCall6e9f8f62009-12-03 04:06:58 +00005140 // Note that we always use the true parent context when performing
5141 // the actual argument initialization.
Nico Weberb58e51c2014-11-19 05:21:39 +00005142 ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
Richard Smith0f59cb32015-12-18 21:45:41 +00005143 *this, From->getLocStart(), From->getType(), FromClassification, Method,
5144 Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005145 if (ICS.isBad()) {
Jacob Bandes-Storchbb935782017-12-31 18:27:29 +00005146 switch (ICS.Bad.Kind) {
5147 case BadConversionSequence::bad_qualifiers: {
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005148 Qualifiers FromQs = FromRecordType.getQualifiers();
5149 Qualifiers ToQs = DestType.getQualifiers();
5150 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5151 if (CVR) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005152 Diag(From->getLocStart(),
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005153 diag::err_member_function_call_bad_cvr)
5154 << Method->getDeclName() << FromRecordType << (CVR - 1)
5155 << From->getSourceRange();
5156 Diag(Method->getLocation(), diag::note_previous_decl)
5157 << Method->getDeclName();
John Wiegley01296292011-04-08 18:41:53 +00005158 return ExprError();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005159 }
Jacob Bandes-Storchbb935782017-12-31 18:27:29 +00005160 break;
5161 }
5162
5163 case BadConversionSequence::lvalue_ref_to_rvalue:
5164 case BadConversionSequence::rvalue_ref_to_lvalue: {
5165 bool IsRValueQualified =
5166 Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
5167 Diag(From->getLocStart(), diag::err_member_function_call_bad_ref)
5168 << Method->getDeclName() << FromClassification.isRValue()
5169 << IsRValueQualified;
5170 Diag(Method->getLocation(), diag::note_previous_decl)
5171 << Method->getDeclName();
5172 return ExprError();
5173 }
5174
5175 case BadConversionSequence::no_conversion:
5176 case BadConversionSequence::unrelated_class:
5177 break;
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005178 }
5179
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005180 return Diag(From->getLocStart(),
Jacob Bandes-Storchbb935782017-12-31 18:27:29 +00005181 diag::err_member_function_call_bad_type)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005182 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005183 }
Mike Stump11289f42009-09-09 15:08:12 +00005184
John Wiegley01296292011-04-08 18:41:53 +00005185 if (ICS.Standard.Second == ICK_Derived_To_Base) {
5186 ExprResult FromRes =
5187 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5188 if (FromRes.isInvalid())
5189 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005190 From = FromRes.get();
John Wiegley01296292011-04-08 18:41:53 +00005191 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005192
Douglas Gregorcc3f3252010-03-03 23:55:11 +00005193 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley01296292011-04-08 18:41:53 +00005194 From = ImpCastExprToType(From, DestType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005195 From->getValueKind()).get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005196 return From;
Douglas Gregor436424c2008-11-18 23:14:02 +00005197}
5198
Douglas Gregor5fb53972009-01-14 15:45:31 +00005199/// TryContextuallyConvertToBool - Attempt to contextually convert the
5200/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00005201static ImplicitConversionSequence
5202TryContextuallyConvertToBool(Sema &S, Expr *From) {
John McCall5c32be02010-08-24 20:38:10 +00005203 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00005204 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00005205 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00005206 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00005207 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005208 /*AllowObjCWritebackConversion=*/false,
5209 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00005210}
5211
5212/// PerformContextuallyConvertToBool - Perform a contextual conversion
5213/// of the expression From to bool (C++0x [conv]p3).
John Wiegley01296292011-04-08 18:41:53 +00005214ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00005215 if (checkPlaceholderForOverload(*this, From))
5216 return ExprError();
5217
John McCall5c32be02010-08-24 20:38:10 +00005218 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00005219 if (!ICS.isBad())
5220 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005221
Fariborz Jahanian76197412009-11-18 18:26:29 +00005222 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005223 return Diag(From->getLocStart(),
John McCall0009fcc2011-04-26 20:42:42 +00005224 diag::err_typecheck_bool_condition)
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00005225 << From->getType() << From->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00005226 return ExprError();
Douglas Gregor5fb53972009-01-14 15:45:31 +00005227}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005228
Richard Smithf8379a02012-01-18 23:55:52 +00005229/// Check that the specified conversion is permitted in a converted constant
5230/// expression, according to C++11 [expr.const]p3. Return true if the conversion
5231/// is acceptable.
5232static bool CheckConvertedConstantConversions(Sema &S,
5233 StandardConversionSequence &SCS) {
5234 // Since we know that the target type is an integral or unscoped enumeration
5235 // type, most conversion kinds are impossible. All possible First and Third
5236 // conversions are fine.
5237 switch (SCS.Second) {
5238 case ICK_Identity:
Richard Smith3c4f8d22016-10-16 17:54:23 +00005239 case ICK_Function_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005240 case ICK_Integral_Promotion:
Richard Smith410cc892014-11-26 03:26:53 +00005241 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
Egor Churaev89831422016-12-23 14:55:49 +00005242 case ICK_Zero_Queue_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005243 return true;
5244
5245 case ICK_Boolean_Conversion:
Richard Smithca24ed42012-09-13 22:00:12 +00005246 // Conversion from an integral or unscoped enumeration type to bool is
Richard Smith410cc892014-11-26 03:26:53 +00005247 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5248 // conversion, so we allow it in a converted constant expression.
5249 //
5250 // FIXME: Per core issue 1407, we should not allow this, but that breaks
5251 // a lot of popular code. We should at least add a warning for this
5252 // (non-conforming) extension.
Richard Smithca24ed42012-09-13 22:00:12 +00005253 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5254 SCS.getToType(2)->isBooleanType();
5255
Richard Smith410cc892014-11-26 03:26:53 +00005256 case ICK_Pointer_Conversion:
5257 case ICK_Pointer_Member:
5258 // C++1z: null pointer conversions and null member pointer conversions are
5259 // only permitted if the source type is std::nullptr_t.
5260 return SCS.getFromType()->isNullPtrType();
5261
5262 case ICK_Floating_Promotion:
5263 case ICK_Complex_Promotion:
5264 case ICK_Floating_Conversion:
5265 case ICK_Complex_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005266 case ICK_Floating_Integral:
Richard Smith410cc892014-11-26 03:26:53 +00005267 case ICK_Compatible_Conversion:
5268 case ICK_Derived_To_Base:
5269 case ICK_Vector_Conversion:
5270 case ICK_Vector_Splat:
Richard Smithf8379a02012-01-18 23:55:52 +00005271 case ICK_Complex_Real:
Richard Smith410cc892014-11-26 03:26:53 +00005272 case ICK_Block_Pointer_Conversion:
5273 case ICK_TransparentUnionConversion:
5274 case ICK_Writeback_Conversion:
5275 case ICK_Zero_Event_Conversion:
George Burgess IV45461812015-10-11 20:13:20 +00005276 case ICK_C_Only_Conversion:
George Burgess IV2099b542016-09-02 22:59:57 +00005277 case ICK_Incompatible_Pointer_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005278 return false;
5279
5280 case ICK_Lvalue_To_Rvalue:
5281 case ICK_Array_To_Pointer:
5282 case ICK_Function_To_Pointer:
Richard Smith410cc892014-11-26 03:26:53 +00005283 llvm_unreachable("found a first conversion kind in Second");
5284
Richard Smithf8379a02012-01-18 23:55:52 +00005285 case ICK_Qualification:
Richard Smith410cc892014-11-26 03:26:53 +00005286 llvm_unreachable("found a third conversion kind in Second");
Richard Smithf8379a02012-01-18 23:55:52 +00005287
5288 case ICK_Num_Conversion_Kinds:
5289 break;
5290 }
5291
5292 llvm_unreachable("unknown conversion kind");
5293}
5294
5295/// CheckConvertedConstantExpression - Check that the expression From is a
5296/// converted constant expression of type T, perform the conversion and produce
5297/// the converted expression, per C++11 [expr.const]p3.
Richard Smith410cc892014-11-26 03:26:53 +00005298static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5299 QualType T, APValue &Value,
5300 Sema::CCEKind CCE,
5301 bool RequireInt) {
5302 assert(S.getLangOpts().CPlusPlus11 &&
5303 "converted constant expression outside C++11");
Richard Smithf8379a02012-01-18 23:55:52 +00005304
Richard Smith410cc892014-11-26 03:26:53 +00005305 if (checkPlaceholderForOverload(S, From))
Richard Smithf8379a02012-01-18 23:55:52 +00005306 return ExprError();
5307
Richard Smith410cc892014-11-26 03:26:53 +00005308 // C++1z [expr.const]p3:
5309 // A converted constant expression of type T is an expression,
5310 // implicitly converted to type T, where the converted
5311 // expression is a constant expression and the implicit conversion
5312 // sequence contains only [... list of conversions ...].
Ismail Pazarbasi4a007742016-09-07 18:24:54 +00005313 // C++1z [stmt.if]p2:
5314 // If the if statement is of the form if constexpr, the value of the
5315 // condition shall be a contextually converted constant expression of type
5316 // bool.
Richard Smithf8379a02012-01-18 23:55:52 +00005317 ImplicitConversionSequence ICS =
Ismail Pazarbasi4a007742016-09-07 18:24:54 +00005318 CCE == Sema::CCEK_ConstexprIf
5319 ? TryContextuallyConvertToBool(S, From)
5320 : TryCopyInitialization(S, From, T,
5321 /*SuppressUserConversions=*/false,
5322 /*InOverloadResolution=*/false,
5323 /*AllowObjcWritebackConversion=*/false,
5324 /*AllowExplicit=*/false);
Craig Topperc3ec1492014-05-26 06:22:03 +00005325 StandardConversionSequence *SCS = nullptr;
Richard Smithf8379a02012-01-18 23:55:52 +00005326 switch (ICS.getKind()) {
5327 case ImplicitConversionSequence::StandardConversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005328 SCS = &ICS.Standard;
5329 break;
5330 case ImplicitConversionSequence::UserDefinedConversion:
Richard Smith410cc892014-11-26 03:26:53 +00005331 // We are converting to a non-class type, so the Before sequence
5332 // must be trivial.
Richard Smithf8379a02012-01-18 23:55:52 +00005333 SCS = &ICS.UserDefined.After;
5334 break;
5335 case ImplicitConversionSequence::AmbiguousConversion:
5336 case ImplicitConversionSequence::BadConversion:
Richard Smith410cc892014-11-26 03:26:53 +00005337 if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5338 return S.Diag(From->getLocStart(),
5339 diag::err_typecheck_converted_constant_expression)
5340 << From->getType() << From->getSourceRange() << T;
Richard Smithf8379a02012-01-18 23:55:52 +00005341 return ExprError();
5342
5343 case ImplicitConversionSequence::EllipsisConversion:
5344 llvm_unreachable("ellipsis conversion in converted constant expression");
5345 }
5346
Richard Smith410cc892014-11-26 03:26:53 +00005347 // Check that we would only use permitted conversions.
5348 if (!CheckConvertedConstantConversions(S, *SCS)) {
5349 return S.Diag(From->getLocStart(),
5350 diag::err_typecheck_converted_constant_expression_disallowed)
5351 << From->getType() << From->getSourceRange() << T;
5352 }
5353 // [...] and where the reference binding (if any) binds directly.
5354 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5355 return S.Diag(From->getLocStart(),
5356 diag::err_typecheck_converted_constant_expression_indirect)
5357 << From->getType() << From->getSourceRange() << T;
5358 }
5359
5360 ExprResult Result =
5361 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
Richard Smithf8379a02012-01-18 23:55:52 +00005362 if (Result.isInvalid())
5363 return Result;
5364
5365 // Check for a narrowing implicit conversion.
5366 APValue PreNarrowingValue;
Richard Smith5614ca72012-03-23 23:55:39 +00005367 QualType PreNarrowingType;
Richard Smith410cc892014-11-26 03:26:53 +00005368 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
Richard Smith5614ca72012-03-23 23:55:39 +00005369 PreNarrowingType)) {
Richard Smith52e624f2016-12-21 21:42:57 +00005370 case NK_Dependent_Narrowing:
5371 // Implicit conversion to a narrower type, but the expression is
5372 // value-dependent so we can't tell whether it's actually narrowing.
Richard Smithf8379a02012-01-18 23:55:52 +00005373 case NK_Variable_Narrowing:
5374 // Implicit conversion to a narrower type, and the value is not a constant
5375 // expression. We'll diagnose this in a moment.
5376 case NK_Not_Narrowing:
5377 break;
5378
5379 case NK_Constant_Narrowing:
Richard Smith410cc892014-11-26 03:26:53 +00005380 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00005381 << CCE << /*Constant*/1
Richard Smith410cc892014-11-26 03:26:53 +00005382 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
Richard Smithf8379a02012-01-18 23:55:52 +00005383 break;
5384
5385 case NK_Type_Narrowing:
Richard Smith410cc892014-11-26 03:26:53 +00005386 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00005387 << CCE << /*Constant*/0 << From->getType() << T;
5388 break;
5389 }
5390
Richard Smith52e624f2016-12-21 21:42:57 +00005391 if (Result.get()->isValueDependent()) {
5392 Value = APValue();
5393 return Result;
5394 }
5395
Richard Smithf8379a02012-01-18 23:55:52 +00005396 // Check the expression is a constant expression.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005397 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithf8379a02012-01-18 23:55:52 +00005398 Expr::EvalResult Eval;
5399 Eval.Diag = &Notes;
5400
Richard Smith410cc892014-11-26 03:26:53 +00005401 if ((T->isReferenceType()
5402 ? !Result.get()->EvaluateAsLValue(Eval, S.Context)
5403 : !Result.get()->EvaluateAsRValue(Eval, S.Context)) ||
5404 (RequireInt && !Eval.Val.isInt())) {
Richard Smithf8379a02012-01-18 23:55:52 +00005405 // The expression can't be folded, so we can't keep it at this position in
5406 // the AST.
5407 Result = ExprError();
Richard Smith911e1422012-01-30 22:27:01 +00005408 } else {
Richard Smith410cc892014-11-26 03:26:53 +00005409 Value = Eval.Val;
Richard Smith911e1422012-01-30 22:27:01 +00005410
5411 if (Notes.empty()) {
5412 // It's a constant expression.
5413 return Result;
5414 }
Richard Smithf8379a02012-01-18 23:55:52 +00005415 }
5416
5417 // It's not a constant expression. Produce an appropriate diagnostic.
5418 if (Notes.size() == 1 &&
5419 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
Richard Smith410cc892014-11-26 03:26:53 +00005420 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
Richard Smithf8379a02012-01-18 23:55:52 +00005421 else {
Richard Smith410cc892014-11-26 03:26:53 +00005422 S.Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smithf8379a02012-01-18 23:55:52 +00005423 << CCE << From->getSourceRange();
5424 for (unsigned I = 0; I < Notes.size(); ++I)
Richard Smith410cc892014-11-26 03:26:53 +00005425 S.Diag(Notes[I].first, Notes[I].second);
Richard Smithf8379a02012-01-18 23:55:52 +00005426 }
Richard Smith410cc892014-11-26 03:26:53 +00005427 return ExprError();
Richard Smithf8379a02012-01-18 23:55:52 +00005428}
5429
Richard Smith410cc892014-11-26 03:26:53 +00005430ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5431 APValue &Value, CCEKind CCE) {
5432 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5433}
5434
5435ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5436 llvm::APSInt &Value,
5437 CCEKind CCE) {
5438 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5439
5440 APValue V;
5441 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
Richard Smith01bfa682016-12-27 02:02:09 +00005442 if (!R.isInvalid() && !R.get()->isValueDependent())
Richard Smith410cc892014-11-26 03:26:53 +00005443 Value = V.getInt();
5444 return R;
5445}
5446
5447
John McCallfec112d2011-09-09 06:11:02 +00005448/// dropPointerConversions - If the given standard conversion sequence
5449/// involves any pointer conversions, remove them. This may change
5450/// the result type of the conversion sequence.
5451static void dropPointerConversion(StandardConversionSequence &SCS) {
5452 if (SCS.Second == ICK_Pointer_Conversion) {
5453 SCS.Second = ICK_Identity;
5454 SCS.Third = ICK_Identity;
5455 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5456 }
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005457}
John McCall5c32be02010-08-24 20:38:10 +00005458
John McCallfec112d2011-09-09 06:11:02 +00005459/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5460/// convert the expression From to an Objective-C pointer type.
5461static ImplicitConversionSequence
5462TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5463 // Do an implicit conversion to 'id'.
5464 QualType Ty = S.Context.getObjCIdType();
5465 ImplicitConversionSequence ICS
5466 = TryImplicitConversion(S, From, Ty,
5467 // FIXME: Are these flags correct?
5468 /*SuppressUserConversions=*/false,
5469 /*AllowExplicit=*/true,
5470 /*InOverloadResolution=*/false,
5471 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005472 /*AllowObjCWritebackConversion=*/false,
5473 /*AllowObjCConversionOnExplicit=*/true);
John McCallfec112d2011-09-09 06:11:02 +00005474
5475 // Strip off any final conversions to 'id'.
5476 switch (ICS.getKind()) {
5477 case ImplicitConversionSequence::BadConversion:
5478 case ImplicitConversionSequence::AmbiguousConversion:
5479 case ImplicitConversionSequence::EllipsisConversion:
5480 break;
5481
5482 case ImplicitConversionSequence::UserDefinedConversion:
5483 dropPointerConversion(ICS.UserDefined.After);
5484 break;
5485
5486 case ImplicitConversionSequence::StandardConversion:
5487 dropPointerConversion(ICS.Standard);
5488 break;
5489 }
5490
5491 return ICS;
5492}
5493
5494/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5495/// conversion of the expression From to an Objective-C pointer type.
Richard Smithe15a3702016-10-06 23:12:58 +00005496/// Returns a valid but null ExprResult if no conversion sequence exists.
John McCallfec112d2011-09-09 06:11:02 +00005497ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00005498 if (checkPlaceholderForOverload(*this, From))
5499 return ExprError();
5500
John McCall8b07ec22010-05-15 11:32:37 +00005501 QualType Ty = Context.getObjCIdType();
John McCallfec112d2011-09-09 06:11:02 +00005502 ImplicitConversionSequence ICS =
5503 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005504 if (!ICS.isBad())
5505 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
Richard Smithe15a3702016-10-06 23:12:58 +00005506 return ExprResult();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005507}
Douglas Gregor5fb53972009-01-14 15:45:31 +00005508
Richard Smith8dd34252012-02-04 07:07:42 +00005509/// Determine whether the provided type is an integral type, or an enumeration
5510/// type of a permitted flavor.
Richard Smithccc11812013-05-21 19:05:48 +00005511bool Sema::ICEConvertDiagnoser::match(QualType T) {
5512 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5513 : T->isIntegralOrUnscopedEnumerationType();
Richard Smith8dd34252012-02-04 07:07:42 +00005514}
5515
Larisse Voufo236bec22013-06-10 06:50:24 +00005516static ExprResult
5517diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5518 Sema::ContextualImplicitConverter &Converter,
5519 QualType T, UnresolvedSetImpl &ViableConversions) {
5520
5521 if (Converter.Suppress)
5522 return ExprError();
5523
5524 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5525 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5526 CXXConversionDecl *Conv =
5527 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5528 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5529 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5530 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005531 return From;
Larisse Voufo236bec22013-06-10 06:50:24 +00005532}
5533
5534static bool
5535diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5536 Sema::ContextualImplicitConverter &Converter,
5537 QualType T, bool HadMultipleCandidates,
5538 UnresolvedSetImpl &ExplicitConversions) {
5539 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5540 DeclAccessPair Found = ExplicitConversions[0];
5541 CXXConversionDecl *Conversion =
5542 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5543
5544 // The user probably meant to invoke the given explicit
5545 // conversion; use it.
5546 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5547 std::string TypeStr;
5548 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5549
5550 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5551 << FixItHint::CreateInsertion(From->getLocStart(),
5552 "static_cast<" + TypeStr + ">(")
5553 << FixItHint::CreateInsertion(
Alp Tokerb6cc5922014-05-03 03:45:55 +00005554 SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
Larisse Voufo236bec22013-06-10 06:50:24 +00005555 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5556
5557 // If we aren't in a SFINAE context, build a call to the
5558 // explicit conversion function.
5559 if (SemaRef.isSFINAEContext())
5560 return true;
5561
Craig Topperc3ec1492014-05-26 06:22:03 +00005562 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
Larisse Voufo236bec22013-06-10 06:50:24 +00005563 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5564 HadMultipleCandidates);
5565 if (Result.isInvalid())
5566 return true;
5567 // Record usage of conversion in an implicit cast.
5568 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005569 CK_UserDefinedConversion, Result.get(),
5570 nullptr, Result.get()->getValueKind());
Larisse Voufo236bec22013-06-10 06:50:24 +00005571 }
5572 return false;
5573}
5574
5575static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5576 Sema::ContextualImplicitConverter &Converter,
5577 QualType T, bool HadMultipleCandidates,
5578 DeclAccessPair &Found) {
5579 CXXConversionDecl *Conversion =
5580 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00005581 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
Larisse Voufo236bec22013-06-10 06:50:24 +00005582
5583 QualType ToType = Conversion->getConversionType().getNonReferenceType();
5584 if (!Converter.SuppressConversion) {
5585 if (SemaRef.isSFINAEContext())
5586 return true;
5587
5588 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5589 << From->getSourceRange();
5590 }
5591
5592 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5593 HadMultipleCandidates);
5594 if (Result.isInvalid())
5595 return true;
5596 // Record usage of conversion in an implicit cast.
5597 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005598 CK_UserDefinedConversion, Result.get(),
5599 nullptr, Result.get()->getValueKind());
Larisse Voufo236bec22013-06-10 06:50:24 +00005600 return false;
5601}
5602
5603static ExprResult finishContextualImplicitConversion(
5604 Sema &SemaRef, SourceLocation Loc, Expr *From,
5605 Sema::ContextualImplicitConverter &Converter) {
5606 if (!Converter.match(From->getType()) && !Converter.Suppress)
5607 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5608 << From->getSourceRange();
5609
5610 return SemaRef.DefaultLvalueConversion(From);
5611}
5612
5613static void
5614collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5615 UnresolvedSetImpl &ViableConversions,
5616 OverloadCandidateSet &CandidateSet) {
5617 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5618 DeclAccessPair FoundDecl = ViableConversions[I];
5619 NamedDecl *D = FoundDecl.getDecl();
5620 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5621 if (isa<UsingShadowDecl>(D))
5622 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5623
5624 CXXConversionDecl *Conv;
5625 FunctionTemplateDecl *ConvTemplate;
5626 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5627 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5628 else
5629 Conv = cast<CXXConversionDecl>(D);
5630
5631 if (ConvTemplate)
5632 SemaRef.AddTemplateConversionCandidate(
Douglas Gregor4b60a152013-11-07 22:34:54 +00005633 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5634 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005635 else
5636 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005637 ToType, CandidateSet,
5638 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005639 }
5640}
5641
Richard Smithccc11812013-05-21 19:05:48 +00005642/// \brief Attempt to convert the given expression to a type which is accepted
5643/// by the given converter.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005644///
Richard Smithccc11812013-05-21 19:05:48 +00005645/// This routine will attempt to convert an expression of class type to a
5646/// type accepted by the specified converter. In C++11 and before, the class
5647/// must have a single non-explicit conversion function converting to a matching
5648/// type. In C++1y, there can be multiple such conversion functions, but only
5649/// one target type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005650///
Douglas Gregor4799d032010-06-30 00:20:43 +00005651/// \param Loc The source location of the construct that requires the
5652/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005653///
James Dennett18348b62012-06-22 08:52:37 +00005654/// \param From The expression we're converting from.
Douglas Gregor4799d032010-06-30 00:20:43 +00005655///
Richard Smithccc11812013-05-21 19:05:48 +00005656/// \param Converter Used to control and diagnose the conversion process.
Richard Smith8dd34252012-02-04 07:07:42 +00005657///
Douglas Gregor4799d032010-06-30 00:20:43 +00005658/// \returns The expression, converted to an integral or enumeration type if
5659/// successful.
Richard Smithccc11812013-05-21 19:05:48 +00005660ExprResult Sema::PerformContextualImplicitConversion(
5661 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005662 // We can't perform any more checking for type-dependent expressions.
5663 if (From->isTypeDependent())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005664 return From;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005665
Eli Friedman1da70392012-01-26 00:26:18 +00005666 // Process placeholders immediately.
5667 if (From->hasPlaceholderType()) {
5668 ExprResult result = CheckPlaceholderExpr(From);
Larisse Voufo236bec22013-06-10 06:50:24 +00005669 if (result.isInvalid())
5670 return result;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005671 From = result.get();
Eli Friedman1da70392012-01-26 00:26:18 +00005672 }
5673
Richard Smithccc11812013-05-21 19:05:48 +00005674 // If the expression already has a matching type, we're golden.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005675 QualType T = From->getType();
Richard Smithccc11812013-05-21 19:05:48 +00005676 if (Converter.match(T))
Eli Friedman1da70392012-01-26 00:26:18 +00005677 return DefaultLvalueConversion(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005678
5679 // FIXME: Check for missing '()' if T is a function type?
5680
Richard Smithccc11812013-05-21 19:05:48 +00005681 // We can only perform contextual implicit conversions on objects of class
5682 // type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005683 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikiebbafb8a2012-03-11 07:00:24 +00005684 if (!RecordTy || !getLangOpts().CPlusPlus) {
Richard Smithccc11812013-05-21 19:05:48 +00005685 if (!Converter.Suppress)
5686 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005687 return From;
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005688 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005689
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005690 // We must have a complete class type.
Douglas Gregora6c5abb2012-05-04 16:48:41 +00005691 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
Richard Smithccc11812013-05-21 19:05:48 +00005692 ContextualImplicitConverter &Converter;
Douglas Gregore2b37442012-05-04 22:38:52 +00005693 Expr *From;
Richard Smithccc11812013-05-21 19:05:48 +00005694
5695 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
Richard Smithdb0ac552015-12-18 22:40:25 +00005696 : Converter(Converter), From(From) {}
Richard Smithccc11812013-05-21 19:05:48 +00005697
Craig Toppere14c0f82014-03-12 04:55:44 +00005698 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00005699 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005700 }
Richard Smithccc11812013-05-21 19:05:48 +00005701 } IncompleteDiagnoser(Converter, From);
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005702
Richard Smithdb0ac552015-12-18 22:40:25 +00005703 if (Converter.Suppress ? !isCompleteType(Loc, T)
5704 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005705 return From;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005706
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005707 // Look for a conversion to an integral or enumeration type.
Larisse Voufo236bec22013-06-10 06:50:24 +00005708 UnresolvedSet<4>
5709 ViableConversions; // These are *potentially* viable in C++1y.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005710 UnresolvedSet<4> ExplicitConversions;
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005711 const auto &Conversions =
Larisse Voufo236bec22013-06-10 06:50:24 +00005712 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005713
Larisse Voufo236bec22013-06-10 06:50:24 +00005714 bool HadMultipleCandidates =
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005715 (std::distance(Conversions.begin(), Conversions.end()) > 1);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005716
Larisse Voufo236bec22013-06-10 06:50:24 +00005717 // To check that there is only one target type, in C++1y:
5718 QualType ToType;
5719 bool HasUniqueTargetType = true;
5720
5721 // Collect explicit or viable (potentially in C++1y) conversions.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005722 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005723 NamedDecl *D = (*I)->getUnderlyingDecl();
5724 CXXConversionDecl *Conversion;
5725 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5726 if (ConvTemplate) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005727 if (getLangOpts().CPlusPlus14)
Larisse Voufo236bec22013-06-10 06:50:24 +00005728 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5729 else
5730 continue; // C++11 does not consider conversion operator templates(?).
5731 } else
5732 Conversion = cast<CXXConversionDecl>(D);
5733
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005734 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
Larisse Voufo236bec22013-06-10 06:50:24 +00005735 "Conversion operator templates are considered potentially "
5736 "viable in C++1y");
5737
5738 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5739 if (Converter.match(CurToType) || ConvTemplate) {
5740
5741 if (Conversion->isExplicit()) {
5742 // FIXME: For C++1y, do we need this restriction?
5743 // cf. diagnoseNoViableConversion()
5744 if (!ConvTemplate)
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005745 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
Larisse Voufo236bec22013-06-10 06:50:24 +00005746 } else {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005747 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005748 if (ToType.isNull())
5749 ToType = CurToType.getUnqualifiedType();
5750 else if (HasUniqueTargetType &&
5751 (CurToType.getUnqualifiedType() != ToType))
5752 HasUniqueTargetType = false;
5753 }
5754 ViableConversions.addDecl(I.getDecl(), I.getAccess());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005755 }
Richard Smith8dd34252012-02-04 07:07:42 +00005756 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005757 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005758
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005759 if (getLangOpts().CPlusPlus14) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005760 // C++1y [conv]p6:
5761 // ... An expression e of class type E appearing in such a context
5762 // is said to be contextually implicitly converted to a specified
5763 // type T and is well-formed if and only if e can be implicitly
5764 // converted to a type T that is determined as follows: E is searched
Larisse Voufo67170bd2013-06-10 08:25:58 +00005765 // for conversion functions whose return type is cv T or reference to
5766 // cv T such that T is allowed by the context. There shall be
Larisse Voufo236bec22013-06-10 06:50:24 +00005767 // exactly one such T.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005768
Larisse Voufo236bec22013-06-10 06:50:24 +00005769 // If no unique T is found:
5770 if (ToType.isNull()) {
5771 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5772 HadMultipleCandidates,
5773 ExplicitConversions))
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005774 return ExprError();
Larisse Voufo236bec22013-06-10 06:50:24 +00005775 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005776 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005777
Larisse Voufo236bec22013-06-10 06:50:24 +00005778 // If more than one unique Ts are found:
5779 if (!HasUniqueTargetType)
5780 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5781 ViableConversions);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005782
Larisse Voufo236bec22013-06-10 06:50:24 +00005783 // If one unique T is found:
5784 // First, build a candidate set from the previously recorded
5785 // potentially viable conversions.
Richard Smith100b24a2014-04-17 01:52:14 +00005786 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Larisse Voufo236bec22013-06-10 06:50:24 +00005787 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5788 CandidateSet);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005789
Larisse Voufo236bec22013-06-10 06:50:24 +00005790 // Then, perform overload resolution over the candidate set.
5791 OverloadCandidateSet::iterator Best;
5792 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5793 case OR_Success: {
5794 // Apply this conversion.
5795 DeclAccessPair Found =
5796 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5797 if (recordConversion(*this, Loc, From, Converter, T,
5798 HadMultipleCandidates, Found))
5799 return ExprError();
5800 break;
5801 }
5802 case OR_Ambiguous:
5803 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5804 ViableConversions);
5805 case OR_No_Viable_Function:
5806 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5807 HadMultipleCandidates,
5808 ExplicitConversions))
5809 return ExprError();
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00005810 LLVM_FALLTHROUGH;
Larisse Voufo236bec22013-06-10 06:50:24 +00005811 case OR_Deleted:
5812 // We'll complain below about a non-integral condition type.
5813 break;
5814 }
5815 } else {
5816 switch (ViableConversions.size()) {
5817 case 0: {
5818 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5819 HadMultipleCandidates,
5820 ExplicitConversions))
Douglas Gregor4799d032010-06-30 00:20:43 +00005821 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005822
Larisse Voufo236bec22013-06-10 06:50:24 +00005823 // We'll complain below about a non-integral condition type.
5824 break;
Douglas Gregor4799d032010-06-30 00:20:43 +00005825 }
Larisse Voufo236bec22013-06-10 06:50:24 +00005826 case 1: {
5827 // Apply this conversion.
5828 DeclAccessPair Found = ViableConversions[0];
5829 if (recordConversion(*this, Loc, From, Converter, T,
5830 HadMultipleCandidates, Found))
5831 return ExprError();
5832 break;
5833 }
5834 default:
5835 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5836 ViableConversions);
5837 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005838 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005839
Larisse Voufo236bec22013-06-10 06:50:24 +00005840 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005841}
5842
Richard Smith100b24a2014-04-17 01:52:14 +00005843/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5844/// an acceptable non-member overloaded operator for a call whose
5845/// arguments have types T1 (and, if non-empty, T2). This routine
5846/// implements the check in C++ [over.match.oper]p3b2 concerning
5847/// enumeration types.
5848static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5849 FunctionDecl *Fn,
5850 ArrayRef<Expr *> Args) {
5851 QualType T1 = Args[0]->getType();
5852 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5853
5854 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5855 return true;
5856
5857 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5858 return true;
5859
5860 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5861 if (Proto->getNumParams() < 1)
5862 return false;
5863
5864 if (T1->isEnumeralType()) {
5865 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5866 if (Context.hasSameUnqualifiedType(T1, ArgType))
5867 return true;
5868 }
5869
5870 if (Proto->getNumParams() < 2)
5871 return false;
5872
5873 if (!T2.isNull() && T2->isEnumeralType()) {
5874 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5875 if (Context.hasSameUnqualifiedType(T2, ArgType))
5876 return true;
5877 }
5878
5879 return false;
5880}
5881
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005882/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00005883/// candidate functions, using the given function call arguments. If
5884/// @p SuppressUserConversions, then don't allow user-defined
5885/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00005886///
James Dennett2a4d13c2012-06-15 07:13:21 +00005887/// \param PartialOverloading true if we are performing "partial" overloading
Douglas Gregorcabea402009-09-22 15:41:20 +00005888/// based on an incomplete set of function arguments. This feature is used by
5889/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00005890void
5891Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00005892 DeclAccessPair FoundDecl,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005893 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005894 OverloadCandidateSet &CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00005895 bool SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005896 bool PartialOverloading,
Richard Smith6eedfe72017-01-09 08:01:21 +00005897 bool AllowExplicit,
5898 ConversionSequenceList EarlyConversions) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005899 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00005900 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005901 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00005902 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005903 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00005904
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005905 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005906 if (!isa<CXXConstructorDecl>(Method)) {
5907 // If we get here, it's because we're calling a member function
5908 // that is named without a member access expression (e.g.,
5909 // "this->f") that was either written explicitly or created
5910 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00005911 // function, e.g., X::f(). We use an empty type for the implied
5912 // object argument (C++ [over.call.func]p3), and the acting context
5913 // is irrelevant.
Richard Smith6eedfe72017-01-09 08:01:21 +00005914 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
George Burgess IVce6284b2017-01-28 02:19:40 +00005915 Expr::Classification::makeSimpleLValue(), Args,
5916 CandidateSet, SuppressUserConversions,
5917 PartialOverloading, EarlyConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005918 return;
5919 }
5920 // We treat a constructor like a non-member function, since its object
5921 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005922 }
5923
Douglas Gregorff7028a2009-11-13 23:59:09 +00005924 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005925 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00005926
Richard Smith100b24a2014-04-17 01:52:14 +00005927 // C++ [over.match.oper]p3:
5928 // if no operand has a class type, only those non-member functions in the
5929 // lookup set that have a first parameter of type T1 or "reference to
5930 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5931 // is a right operand) a second parameter of type T2 or "reference to
5932 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
5933 // candidate functions.
5934 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5935 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5936 return;
5937
Richard Smith8b86f2d2013-11-04 01:48:18 +00005938 // C++11 [class.copy]p11: [DR1402]
5939 // A defaulted move constructor that is defined as deleted is ignored by
5940 // overload resolution.
5941 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5942 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5943 Constructor->isMoveConstructor())
5944 return;
5945
Douglas Gregor27381f32009-11-23 12:27:39 +00005946 // Overload resolution is always an unevaluated context.
Faisal Valid143a0c2017-04-01 21:30:49 +00005947 EnterExpressionEvaluationContext Unevaluated(
5948 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005949
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005950 // Add this candidate
Richard Smith6eedfe72017-01-09 08:01:21 +00005951 OverloadCandidate &Candidate =
5952 CandidateSet.addCandidate(Args.size(), EarlyConversions);
John McCalla0296f72010-03-19 07:35:19 +00005953 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005954 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005955 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005956 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005957 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005958 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005959
Erich Keane281d20b2018-01-08 21:34:17 +00005960 if (Function->isMultiVersion() &&
5961 !Function->getAttr<TargetAttr>()->isDefaultVersion()) {
5962 Candidate.Viable = false;
5963 Candidate.FailureKind = ovl_non_default_multiversion_function;
5964 return;
5965 }
5966
John McCall578a1f82014-12-14 01:46:53 +00005967 if (Constructor) {
5968 // C++ [class.copy]p3:
5969 // A member function template is never instantiated to perform the copy
5970 // of a class object to an object of its class type.
5971 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
Richard Smith0f59cb32015-12-18 21:45:41 +00005972 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
John McCall578a1f82014-12-14 01:46:53 +00005973 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00005974 IsDerivedFrom(Args[0]->getLocStart(), Args[0]->getType(),
5975 ClassType))) {
John McCall578a1f82014-12-14 01:46:53 +00005976 Candidate.Viable = false;
5977 Candidate.FailureKind = ovl_fail_illegal_constructor;
5978 return;
5979 }
Richard Smith836a3b42017-01-13 20:46:54 +00005980
5981 // C++ [over.match.funcs]p8: (proposed DR resolution)
5982 // A constructor inherited from class type C that has a first parameter
5983 // of type "reference to P" (including such a constructor instantiated
5984 // from a template) is excluded from the set of candidate functions when
5985 // constructing an object of type cv D if the argument list has exactly
5986 // one argument and D is reference-related to P and P is reference-related
5987 // to C.
5988 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
5989 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
5990 Constructor->getParamDecl(0)->getType()->isReferenceType()) {
5991 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
5992 QualType C = Context.getRecordType(Constructor->getParent());
5993 QualType D = Context.getRecordType(Shadow->getParent());
5994 SourceLocation Loc = Args.front()->getExprLoc();
5995 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
5996 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
5997 Candidate.Viable = false;
5998 Candidate.FailureKind = ovl_fail_inhctor_slice;
5999 return;
6000 }
6001 }
John McCall578a1f82014-12-14 01:46:53 +00006002 }
6003
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006004 unsigned NumParams = Proto->getNumParams();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006005
6006 // (C++ 13.3.2p2): A candidate function having fewer than m
6007 // parameters is viable only if it has an ellipsis in its parameter
6008 // list (8.3.5).
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006009 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
Douglas Gregor2a920012009-09-23 14:56:09 +00006010 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006011 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006012 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006013 return;
6014 }
6015
6016 // (C++ 13.3.2p2): A candidate function having more than m parameters
6017 // is viable only if the (m+1)st parameter has a default argument
6018 // (8.3.6). For the purposes of overload resolution, the
6019 // parameter list is truncated on the right, so that there are
6020 // exactly m parameters.
6021 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006022 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006023 // Not enough arguments.
6024 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006025 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006026 return;
6027 }
6028
Peter Collingbourne7277fe82011-10-02 23:49:40 +00006029 // (CUDA B.1): Check for invalid calls between targets.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006030 if (getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00006031 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
Eli Bendersky9a220fc2014-09-29 20:38:29 +00006032 // Skip the check for callers that are implicit members, because in this
6033 // case we may not yet know what the member's target is; the target is
6034 // inferred for the member automatically, based on the bases and fields of
6035 // the class.
Justin Lebarb0080032016-08-10 01:09:11 +00006036 if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00006037 Candidate.Viable = false;
6038 Candidate.FailureKind = ovl_fail_bad_target;
6039 return;
6040 }
6041
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006042 // Determine the implicit conversion sequences for each of the
6043 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006044 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Richard Smith6eedfe72017-01-09 08:01:21 +00006045 if (Candidate.Conversions[ArgIdx].isInitialized()) {
6046 // We already formed a conversion sequence for this parameter during
6047 // template argument deduction.
6048 } else if (ArgIdx < NumParams) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006049 // (C++ 13.3.2p3): for F to be a viable function, there shall
6050 // exist for each argument an implicit conversion sequence
6051 // (13.3.3.1) that converts that argument to the corresponding
6052 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00006053 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00006054 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006055 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006056 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00006057 /*InOverloadResolution=*/true,
6058 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006059 getLangOpts().ObjCAutoRefCount,
Douglas Gregor6073dca2012-02-24 23:56:31 +00006060 AllowExplicit);
John McCall0d1da222010-01-12 00:44:57 +00006061 if (Candidate.Conversions[ArgIdx].isBad()) {
6062 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006063 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006064 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00006065 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006066 } else {
6067 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6068 // argument for which there is no corresponding parameter is
6069 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006070 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006071 }
6072 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006073
6074 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
6075 Candidate.Viable = false;
6076 Candidate.FailureKind = ovl_fail_enable_if;
6077 Candidate.DeductionFailure.Data = FailedAttr;
6078 return;
6079 }
Yaxun Liu5b746652016-12-18 05:18:55 +00006080
6081 if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) {
6082 Candidate.Viable = false;
6083 Candidate.FailureKind = ovl_fail_ext_disabled;
6084 return;
6085 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006086}
6087
Manman Rend2a3cd72016-04-07 19:30:20 +00006088ObjCMethodDecl *
6089Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
6090 SmallVectorImpl<ObjCMethodDecl *> &Methods) {
6091 if (Methods.size() <= 1)
Fariborz Jahanian0ded4242014-08-13 21:24:14 +00006092 return nullptr;
Manman Rend2a3cd72016-04-07 19:30:20 +00006093
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006094 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6095 bool Match = true;
6096 ObjCMethodDecl *Method = Methods[b];
6097 unsigned NumNamedArgs = Sel.getNumArgs();
6098 // Method might have more arguments than selector indicates. This is due
6099 // to addition of c-style arguments in method.
6100 if (Method->param_size() > NumNamedArgs)
6101 NumNamedArgs = Method->param_size();
6102 if (Args.size() < NumNamedArgs)
6103 continue;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00006104
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006105 for (unsigned i = 0; i < NumNamedArgs; i++) {
6106 // We can't do any type-checking on a type-dependent argument.
6107 if (Args[i]->isTypeDependent()) {
6108 Match = false;
6109 break;
6110 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00006111
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006112 ParmVarDecl *param = Method->parameters()[i];
6113 Expr *argExpr = Args[i];
6114 assert(argExpr && "SelectBestMethod(): missing expression");
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00006115
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006116 // Strip the unbridged-cast placeholder expression off unless it's
6117 // a consumed argument.
6118 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
6119 !param->hasAttr<CFConsumedAttr>())
6120 argExpr = stripARCUnbridgedCast(argExpr);
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00006121
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006122 // If the parameter is __unknown_anytype, move on to the next method.
6123 if (param->getType() == Context.UnknownAnyTy) {
6124 Match = false;
6125 break;
6126 }
George Burgess IV45461812015-10-11 20:13:20 +00006127
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006128 ImplicitConversionSequence ConversionState
6129 = TryCopyInitialization(*this, argExpr, param->getType(),
6130 /*SuppressUserConversions*/false,
6131 /*InOverloadResolution=*/true,
6132 /*AllowObjCWritebackConversion=*/
6133 getLangOpts().ObjCAutoRefCount,
6134 /*AllowExplicit*/false);
George Burgess IV2099b542016-09-02 22:59:57 +00006135 // This function looks for a reasonably-exact match, so we consider
6136 // incompatible pointer conversions to be a failure here.
6137 if (ConversionState.isBad() ||
6138 (ConversionState.isStandard() &&
6139 ConversionState.Standard.Second ==
6140 ICK_Incompatible_Pointer_Conversion)) {
6141 Match = false;
6142 break;
6143 }
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006144 }
6145 // Promote additional arguments to variadic methods.
6146 if (Match && Method->isVariadic()) {
6147 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6148 if (Args[i]->isTypeDependent()) {
6149 Match = false;
6150 break;
6151 }
6152 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6153 nullptr);
6154 if (Arg.isInvalid()) {
6155 Match = false;
6156 break;
6157 }
6158 }
Fariborz Jahanian180d76b2014-08-27 16:38:47 +00006159 } else {
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006160 // Check for extra arguments to non-variadic methods.
6161 if (Args.size() != NumNamedArgs)
6162 Match = false;
Fariborz Jahanian180d76b2014-08-27 16:38:47 +00006163 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6164 // Special case when selectors have no argument. In this case, select
6165 // one with the most general result type of 'id'.
6166 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6167 QualType ReturnT = Methods[b]->getReturnType();
6168 if (ReturnT->isObjCIdType())
6169 return Methods[b];
6170 }
6171 }
6172 }
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006173
6174 if (Match)
6175 return Method;
6176 }
6177 return nullptr;
6178}
6179
George Burgess IV2a6150d2015-10-16 01:17:38 +00006180// specific_attr_iterator iterates over enable_if attributes in reverse, and
6181// enable_if is order-sensitive. As a result, we need to reverse things
6182// sometimes. Size of 4 elements is arbitrary.
6183static SmallVector<EnableIfAttr *, 4>
6184getOrderedEnableIfAttrs(const FunctionDecl *Function) {
6185 SmallVector<EnableIfAttr *, 4> Result;
6186 if (!Function->hasAttrs())
6187 return Result;
6188
6189 const auto &FuncAttrs = Function->getAttrs();
6190 for (Attr *Attr : FuncAttrs)
6191 if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr))
6192 Result.push_back(EnableIf);
6193
6194 std::reverse(Result.begin(), Result.end());
6195 return Result;
6196}
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006197
George Burgess IV177399e2017-01-09 04:12:14 +00006198static bool
6199convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg,
6200 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap,
6201 bool MissingImplicitThis, Expr *&ConvertedThis,
6202 SmallVectorImpl<Expr *> &ConvertedArgs) {
6203 if (ThisArg) {
6204 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6205 assert(!isa<CXXConstructorDecl>(Method) &&
6206 "Shouldn't have `this` for ctors!");
6207 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
6208 ExprResult R = S.PerformObjectArgumentInitialization(
6209 ThisArg, /*Qualifier=*/nullptr, Method, Method);
6210 if (R.isInvalid())
6211 return false;
6212 ConvertedThis = R.get();
6213 } else {
6214 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
6215 (void)MD;
6216 assert((MissingImplicitThis || MD->isStatic() ||
6217 isa<CXXConstructorDecl>(MD)) &&
6218 "Expected `this` for non-ctor instance methods");
6219 }
6220 ConvertedThis = nullptr;
6221 }
Nick Lewyckye283c552015-08-25 22:33:16 +00006222
George Burgess IV458b3f32016-08-12 04:19:35 +00006223 // Ignore any variadic arguments. Converting them is pointless, since the
George Burgess IV177399e2017-01-09 04:12:14 +00006224 // user can't refer to them in the function condition.
George Burgess IV53b938d2016-08-12 04:12:31 +00006225 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6226
Nick Lewyckye283c552015-08-25 22:33:16 +00006227 // Convert the arguments.
George Burgess IV53b938d2016-08-12 04:12:31 +00006228 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
George Burgess IVe96abf72016-02-24 22:31:14 +00006229 ExprResult R;
George Burgess IV177399e2017-01-09 04:12:14 +00006230 R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6231 S.Context, Function->getParamDecl(I)),
George Burgess IVe96abf72016-02-24 22:31:14 +00006232 SourceLocation(), Args[I]);
George Burgess IVe96abf72016-02-24 22:31:14 +00006233
George Burgess IV177399e2017-01-09 04:12:14 +00006234 if (R.isInvalid())
6235 return false;
George Burgess IVe96abf72016-02-24 22:31:14 +00006236
George Burgess IVe96abf72016-02-24 22:31:14 +00006237 ConvertedArgs.push_back(R.get());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006238 }
6239
George Burgess IV177399e2017-01-09 04:12:14 +00006240 if (Trap.hasErrorOccurred())
6241 return false;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006242
Nick Lewyckye283c552015-08-25 22:33:16 +00006243 // Push default arguments if needed.
6244 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6245 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6246 ParmVarDecl *P = Function->getParamDecl(i);
George Burgess IV177399e2017-01-09 04:12:14 +00006247 ExprResult R = S.PerformCopyInitialization(
6248 InitializedEntity::InitializeParameter(S.Context,
Nick Lewyckye283c552015-08-25 22:33:16 +00006249 Function->getParamDecl(i)),
6250 SourceLocation(),
6251 P->hasUninstantiatedDefaultArg() ? P->getUninstantiatedDefaultArg()
6252 : P->getDefaultArg());
George Burgess IV177399e2017-01-09 04:12:14 +00006253 if (R.isInvalid())
6254 return false;
Nick Lewyckye283c552015-08-25 22:33:16 +00006255 ConvertedArgs.push_back(R.get());
6256 }
6257
George Burgess IV177399e2017-01-09 04:12:14 +00006258 if (Trap.hasErrorOccurred())
6259 return false;
Nick Lewyckye283c552015-08-25 22:33:16 +00006260 }
George Burgess IV177399e2017-01-09 04:12:14 +00006261 return true;
6262}
6263
6264EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
6265 bool MissingImplicitThis) {
6266 SmallVector<EnableIfAttr *, 4> EnableIfAttrs =
6267 getOrderedEnableIfAttrs(Function);
6268 if (EnableIfAttrs.empty())
6269 return nullptr;
6270
6271 SFINAETrap Trap(*this);
6272 SmallVector<Expr *, 16> ConvertedArgs;
6273 // FIXME: We should look into making enable_if late-parsed.
6274 Expr *DiscardedThis;
6275 if (!convertArgsForAvailabilityChecks(
6276 *this, Function, /*ThisArg=*/nullptr, Args, Trap,
6277 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
6278 return EnableIfAttrs[0];
Nick Lewyckye283c552015-08-25 22:33:16 +00006279
George Burgess IV2a6150d2015-10-16 01:17:38 +00006280 for (auto *EIA : EnableIfAttrs) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006281 APValue Result;
George Burgess IVe8f10cc2016-05-11 01:38:27 +00006282 // FIXME: This doesn't consider value-dependent cases, because doing so is
6283 // very difficult. Ideally, we should handle them more gracefully.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006284 if (!EIA->getCond()->EvaluateWithSubstitution(
George Burgess IVe8f10cc2016-05-11 01:38:27 +00006285 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006286 return EIA;
George Burgess IVe8f10cc2016-05-11 01:38:27 +00006287
6288 if (!Result.isInt() || !Result.getInt().getBoolValue())
6289 return EIA;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006290 }
Craig Topperc3ec1492014-05-26 06:22:03 +00006291 return nullptr;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006292}
6293
George Burgess IV177399e2017-01-09 04:12:14 +00006294template <typename CheckFn>
Argyrios Kyrtzidisa7233bd2017-05-24 00:46:27 +00006295static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
George Burgess IVce6284b2017-01-28 02:19:40 +00006296 bool ArgDependent, SourceLocation Loc,
6297 CheckFn &&IsSuccessful) {
6298 SmallVector<const DiagnoseIfAttr *, 8> Attrs;
Argyrios Kyrtzidisa7233bd2017-05-24 00:46:27 +00006299 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
George Burgess IVce6284b2017-01-28 02:19:40 +00006300 if (ArgDependent == DIA->getArgDependent())
6301 Attrs.push_back(DIA);
6302 }
6303
6304 // Common case: No diagnose_if attributes, so we can quit early.
6305 if (Attrs.empty())
6306 return false;
6307
6308 auto WarningBegin = std::stable_partition(
6309 Attrs.begin(), Attrs.end(),
6310 [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
6311
George Burgess IV177399e2017-01-09 04:12:14 +00006312 // Note that diagnose_if attributes are late-parsed, so they appear in the
6313 // correct order (unlike enable_if attributes).
George Burgess IVce6284b2017-01-28 02:19:40 +00006314 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
6315 IsSuccessful);
6316 if (ErrAttr != WarningBegin) {
6317 const DiagnoseIfAttr *DIA = *ErrAttr;
6318 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
6319 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6320 << DIA->getParent() << DIA->getCond()->getSourceRange();
6321 return true;
6322 }
George Burgess IV177399e2017-01-09 04:12:14 +00006323
George Burgess IVce6284b2017-01-28 02:19:40 +00006324 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
6325 if (IsSuccessful(DIA)) {
6326 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
6327 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6328 << DIA->getParent() << DIA->getCond()->getSourceRange();
6329 }
6330
6331 return false;
George Burgess IV177399e2017-01-09 04:12:14 +00006332}
6333
George Burgess IVce6284b2017-01-28 02:19:40 +00006334bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
6335 const Expr *ThisArg,
6336 ArrayRef<const Expr *> Args,
6337 SourceLocation Loc) {
6338 return diagnoseDiagnoseIfAttrsWith(
6339 *this, Function, /*ArgDependent=*/true, Loc,
6340 [&](const DiagnoseIfAttr *DIA) {
6341 APValue Result;
6342 // It's sane to use the same Args for any redecl of this function, since
6343 // EvaluateWithSubstitution only cares about the position of each
6344 // argument in the arg list, not the ParmVarDecl* it maps to.
6345 if (!DIA->getCond()->EvaluateWithSubstitution(
Argyrios Kyrtzidisa7233bd2017-05-24 00:46:27 +00006346 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
George Burgess IVce6284b2017-01-28 02:19:40 +00006347 return false;
6348 return Result.isInt() && Result.getInt().getBoolValue();
6349 });
George Burgess IV177399e2017-01-09 04:12:14 +00006350}
6351
Argyrios Kyrtzidisa7233bd2017-05-24 00:46:27 +00006352bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
George Burgess IVce6284b2017-01-28 02:19:40 +00006353 SourceLocation Loc) {
6354 return diagnoseDiagnoseIfAttrsWith(
Argyrios Kyrtzidisa7233bd2017-05-24 00:46:27 +00006355 *this, ND, /*ArgDependent=*/false, Loc,
George Burgess IVce6284b2017-01-28 02:19:40 +00006356 [&](const DiagnoseIfAttr *DIA) {
6357 bool Result;
6358 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
6359 Result;
6360 });
George Burgess IV177399e2017-01-09 04:12:14 +00006361}
6362
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006363/// \brief Add all of the function declarations in the given function set to
Nick Lewyckyed4265c2013-09-22 10:06:01 +00006364/// the overload candidate set.
John McCall4c4c1df2010-01-26 03:27:55 +00006365void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006366 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006367 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006368 TemplateArgumentListInfo *ExplicitTemplateArgs,
Richard Smithbcc22fc2012-03-09 08:00:36 +00006369 bool SuppressUserConversions,
Benjamin Kramere3962ae2017-10-26 08:41:28 +00006370 bool PartialOverloading,
6371 bool FirstArgumentIsBase) {
John McCall4c4c1df2010-01-26 03:27:55 +00006372 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00006373 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6374 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Benjamin Kramere3962ae2017-10-26 08:41:28 +00006375 ArrayRef<Expr *> FunctionArgs = Args;
Erik Verbruggenf1898cf2017-03-28 07:22:21 +00006376 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
6377 QualType ObjectType;
6378 Expr::Classification ObjectClassification;
Benjamin Kramere3962ae2017-10-26 08:41:28 +00006379 if (Args.size() > 0) {
6380 if (Expr *E = Args[0]) {
6381 // Use the explit base to restrict the lookup:
6382 ObjectType = E->getType();
6383 ObjectClassification = E->Classify(Context);
6384 } // .. else there is an implit base.
6385 FunctionArgs = Args.slice(1);
6386 }
John McCalla0296f72010-03-19 07:35:19 +00006387 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
Erik Verbruggenf1898cf2017-03-28 07:22:21 +00006388 cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
Benjamin Kramere3962ae2017-10-26 08:41:28 +00006389 ObjectClassification, FunctionArgs, CandidateSet,
Erik Verbruggenf1898cf2017-03-28 07:22:21 +00006390 SuppressUserConversions, PartialOverloading);
6391 } else {
Benjamin Kramere3962ae2017-10-26 08:41:28 +00006392 // Slice the first argument (which is the base) when we access
6393 // static method as non-static
6394 if (Args.size() > 0 && (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
6395 !isa<CXXConstructorDecl>(FD)))) {
6396 assert(cast<CXXMethodDecl>(FD)->isStatic());
6397 FunctionArgs = Args.slice(1);
6398 }
6399 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006400 SuppressUserConversions, PartialOverloading);
Erik Verbruggenf1898cf2017-03-28 07:22:21 +00006401 }
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006402 } else {
John McCalla0296f72010-03-19 07:35:19 +00006403 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006404 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
Erik Verbruggenf1898cf2017-03-28 07:22:21 +00006405 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic()) {
6406 QualType ObjectType;
6407 Expr::Classification ObjectClassification;
6408 if (Expr *E = Args[0]) {
6409 // Use the explit base to restrict the lookup:
6410 ObjectType = E->getType();
6411 ObjectClassification = E->Classify(Context);
6412 } // .. else there is an implit base.
George Burgess IV177399e2017-01-09 04:12:14 +00006413 AddMethodTemplateCandidate(
6414 FunTmpl, F.getPair(),
6415 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Erik Verbruggenf1898cf2017-03-28 07:22:21 +00006416 ExplicitTemplateArgs, ObjectType, ObjectClassification,
6417 Args.slice(1), CandidateSet, SuppressUserConversions,
6418 PartialOverloading);
6419 } else {
John McCalla0296f72010-03-19 07:35:19 +00006420 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smithbcc22fc2012-03-09 08:00:36 +00006421 ExplicitTemplateArgs, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006422 CandidateSet, SuppressUserConversions,
6423 PartialOverloading);
Erik Verbruggenf1898cf2017-03-28 07:22:21 +00006424 }
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006425 }
Douglas Gregor15448f82009-06-27 21:05:07 +00006426 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006427}
6428
John McCallf0f1cf02009-11-17 07:50:12 +00006429/// AddMethodCandidate - Adds a named decl (which is some kind of
6430/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00006431void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006432 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006433 Expr::Classification ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00006434 ArrayRef<Expr *> Args,
John McCallf0f1cf02009-11-17 07:50:12 +00006435 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006436 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00006437 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00006438 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00006439
6440 if (isa<UsingShadowDecl>(Decl))
6441 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006442
John McCallf0f1cf02009-11-17 07:50:12 +00006443 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6444 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6445 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00006446 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
George Burgess IVce6284b2017-01-28 02:19:40 +00006447 /*ExplicitArgs*/ nullptr, ObjectType,
6448 ObjectClassification, Args, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006449 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00006450 } else {
John McCalla0296f72010-03-19 07:35:19 +00006451 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
George Burgess IVce6284b2017-01-28 02:19:40 +00006452 ObjectType, ObjectClassification, Args, CandidateSet,
6453 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00006454 }
6455}
6456
Douglas Gregor436424c2008-11-18 23:14:02 +00006457/// AddMethodCandidate - Adds the given C++ member function to the set
6458/// of candidate functions, using the given function call arguments
6459/// and the object argument (@c Object). For example, in a call
6460/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6461/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6462/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00006463/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00006464void
John McCalla0296f72010-03-19 07:35:19 +00006465Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00006466 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006467 Expr::Classification ObjectClassification,
George Burgess IVce6284b2017-01-28 02:19:40 +00006468 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006469 OverloadCandidateSet &CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006470 bool SuppressUserConversions,
Richard Smith6eedfe72017-01-09 08:01:21 +00006471 bool PartialOverloading,
6472 ConversionSequenceList EarlyConversions) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006473 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00006474 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00006475 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00006476 assert(!isa<CXXConstructorDecl>(Method) &&
6477 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00006478
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006479 if (!CandidateSet.isNewCandidate(Method))
6480 return;
6481
Richard Smith8b86f2d2013-11-04 01:48:18 +00006482 // C++11 [class.copy]p23: [DR1402]
6483 // A defaulted move assignment operator that is defined as deleted is
6484 // ignored by overload resolution.
6485 if (Method->isDefaulted() && Method->isDeleted() &&
6486 Method->isMoveAssignmentOperator())
6487 return;
6488
Douglas Gregor27381f32009-11-23 12:27:39 +00006489 // Overload resolution is always an unevaluated context.
Faisal Valid143a0c2017-04-01 21:30:49 +00006490 EnterExpressionEvaluationContext Unevaluated(
6491 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006492
Douglas Gregor436424c2008-11-18 23:14:02 +00006493 // Add this candidate
Richard Smith6eedfe72017-01-09 08:01:21 +00006494 OverloadCandidate &Candidate =
6495 CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
John McCalla0296f72010-03-19 07:35:19 +00006496 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00006497 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006498 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006499 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006500 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor436424c2008-11-18 23:14:02 +00006501
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006502 unsigned NumParams = Proto->getNumParams();
Douglas Gregor436424c2008-11-18 23:14:02 +00006503
6504 // (C++ 13.3.2p2): A candidate function having fewer than m
6505 // parameters is viable only if it has an ellipsis in its parameter
6506 // list (8.3.5).
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006507 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6508 !Proto->isVariadic()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006509 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006510 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00006511 return;
6512 }
6513
6514 // (C++ 13.3.2p2): A candidate function having more than m parameters
6515 // is viable only if the (m+1)st parameter has a default argument
6516 // (8.3.6). For the purposes of overload resolution, the
6517 // parameter list is truncated on the right, so that there are
6518 // exactly m parameters.
6519 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006520 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006521 // Not enough arguments.
6522 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006523 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00006524 return;
6525 }
6526
6527 Candidate.Viable = true;
Douglas Gregor436424c2008-11-18 23:14:02 +00006528
John McCall6e9f8f62009-12-03 04:06:58 +00006529 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006530 // The implicit object argument is ignored.
6531 Candidate.IgnoreObjectArgument = true;
6532 else {
6533 // Determine the implicit conversion sequence for the object
6534 // parameter.
Richard Smith0f59cb32015-12-18 21:45:41 +00006535 Candidate.Conversions[0] = TryObjectArgumentInitialization(
6536 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6537 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00006538 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006539 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006540 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006541 return;
6542 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006543 }
6544
Eli Bendersky291a57e2014-09-25 23:59:08 +00006545 // (CUDA B.1): Check for invalid calls between targets.
6546 if (getLangOpts().CUDA)
6547 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
Justin Lebarb0080032016-08-10 01:09:11 +00006548 if (!IsAllowedCUDACall(Caller, Method)) {
Eli Bendersky291a57e2014-09-25 23:59:08 +00006549 Candidate.Viable = false;
6550 Candidate.FailureKind = ovl_fail_bad_target;
6551 return;
6552 }
6553
Douglas Gregor436424c2008-11-18 23:14:02 +00006554 // Determine the implicit conversion sequences for each of the
6555 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006556 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Richard Smith6eedfe72017-01-09 08:01:21 +00006557 if (Candidate.Conversions[ArgIdx + 1].isInitialized()) {
6558 // We already formed a conversion sequence for this parameter during
6559 // template argument deduction.
6560 } else if (ArgIdx < NumParams) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006561 // (C++ 13.3.2p3): for F to be a viable function, there shall
6562 // exist for each argument an implicit conversion sequence
6563 // (13.3.3.1) that converts that argument to the corresponding
6564 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00006565 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00006566 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006567 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006568 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00006569 /*InOverloadResolution=*/true,
6570 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006571 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00006572 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006573 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006574 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006575 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00006576 }
6577 } else {
6578 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6579 // argument for which there is no corresponding parameter is
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006580 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006581 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00006582 }
6583 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006584
6585 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6586 Candidate.Viable = false;
6587 Candidate.FailureKind = ovl_fail_enable_if;
6588 Candidate.DeductionFailure.Data = FailedAttr;
6589 return;
6590 }
Erich Keane281d20b2018-01-08 21:34:17 +00006591
6592 if (Method->isMultiVersion() &&
6593 !Method->getAttr<TargetAttr>()->isDefaultVersion()) {
6594 Candidate.Viable = false;
6595 Candidate.FailureKind = ovl_non_default_multiversion_function;
6596 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006597}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006598
Douglas Gregor97628d62009-08-21 00:16:32 +00006599/// \brief Add a C++ member function template as a candidate to the candidate
6600/// set, using template argument deduction to produce an appropriate member
6601/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00006602void
Douglas Gregor97628d62009-08-21 00:16:32 +00006603Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00006604 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006605 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006606 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006607 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006608 Expr::Classification ObjectClassification,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006609 ArrayRef<Expr *> Args,
Douglas Gregor97628d62009-08-21 00:16:32 +00006610 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006611 bool SuppressUserConversions,
6612 bool PartialOverloading) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006613 if (!CandidateSet.isNewCandidate(MethodTmpl))
6614 return;
6615
Douglas Gregor97628d62009-08-21 00:16:32 +00006616 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00006617 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00006618 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00006619 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00006620 // candidate functions in the usual way.113) A given name can refer to one
6621 // or more function templates and also to a set of overloaded non-template
6622 // functions. In such a case, the candidate functions generated from each
6623 // function template are combined with the set of non-template candidate
6624 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00006625 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006626 FunctionDecl *Specialization = nullptr;
Richard Smith6eedfe72017-01-09 08:01:21 +00006627 ConversionSequenceList Conversions;
6628 if (TemplateDeductionResult Result = DeduceTemplateArguments(
6629 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
6630 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6631 return CheckNonDependentConversions(
6632 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
6633 SuppressUserConversions, ActingContext, ObjectType,
6634 ObjectClassification);
6635 })) {
6636 OverloadCandidate &Candidate =
6637 CandidateSet.addCandidate(Conversions.size(), Conversions);
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006638 Candidate.FoundDecl = FoundDecl;
6639 Candidate.Function = MethodTmpl->getTemplatedDecl();
6640 Candidate.Viable = false;
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006641 Candidate.IsSurrogate = false;
Richard Smith9d05e152017-01-10 20:52:50 +00006642 Candidate.IgnoreObjectArgument =
6643 cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
6644 ObjectType.isNull();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006645 Candidate.ExplicitCallArguments = Args.size();
Richard Smith6eedfe72017-01-09 08:01:21 +00006646 if (Result == TDK_NonDependentConversionFailure)
6647 Candidate.FailureKind = ovl_fail_bad_conversion;
6648 else {
6649 Candidate.FailureKind = ovl_fail_bad_deduction;
6650 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6651 Info);
6652 }
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006653 return;
6654 }
Mike Stump11289f42009-09-09 15:08:12 +00006655
Douglas Gregor97628d62009-08-21 00:16:32 +00006656 // Add the function template specialization produced by template argument
6657 // deduction as a candidate.
6658 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00006659 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00006660 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00006661 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
George Burgess IVce6284b2017-01-28 02:19:40 +00006662 ActingContext, ObjectType, ObjectClassification, Args,
6663 CandidateSet, SuppressUserConversions, PartialOverloading,
6664 Conversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00006665}
6666
Douglas Gregor05155d82009-08-21 23:19:43 +00006667/// \brief Add a C++ function template specialization as a candidate
6668/// in the candidate set, using template argument deduction to produce
6669/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00006670void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006671Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00006672 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006673 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006674 ArrayRef<Expr *> Args,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006675 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006676 bool SuppressUserConversions,
6677 bool PartialOverloading) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006678 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6679 return;
6680
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006681 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00006682 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006683 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00006684 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006685 // candidate functions in the usual way.113) A given name can refer to one
6686 // or more function templates and also to a set of overloaded non-template
6687 // functions. In such a case, the candidate functions generated from each
6688 // function template are combined with the set of non-template candidate
6689 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00006690 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006691 FunctionDecl *Specialization = nullptr;
Richard Smith6eedfe72017-01-09 08:01:21 +00006692 ConversionSequenceList Conversions;
6693 if (TemplateDeductionResult Result = DeduceTemplateArguments(
6694 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
6695 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6696 return CheckNonDependentConversions(FunctionTemplate, ParamTypes,
6697 Args, CandidateSet, Conversions,
6698 SuppressUserConversions);
6699 })) {
6700 OverloadCandidate &Candidate =
6701 CandidateSet.addCandidate(Conversions.size(), Conversions);
John McCalla0296f72010-03-19 07:35:19 +00006702 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00006703 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6704 Candidate.Viable = false;
6705 Candidate.IsSurrogate = false;
Richard Smith9d05e152017-01-10 20:52:50 +00006706 // Ignore the object argument if there is one, since we don't have an object
6707 // type.
6708 Candidate.IgnoreObjectArgument =
6709 isa<CXXMethodDecl>(Candidate.Function) &&
6710 !isa<CXXConstructorDecl>(Candidate.Function);
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006711 Candidate.ExplicitCallArguments = Args.size();
Richard Smith6eedfe72017-01-09 08:01:21 +00006712 if (Result == TDK_NonDependentConversionFailure)
6713 Candidate.FailureKind = ovl_fail_bad_conversion;
6714 else {
6715 Candidate.FailureKind = ovl_fail_bad_deduction;
6716 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6717 Info);
6718 }
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006719 return;
6720 }
Mike Stump11289f42009-09-09 15:08:12 +00006721
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006722 // Add the function template specialization produced by template argument
6723 // deduction as a candidate.
6724 assert(Specialization && "Missing function template specialization?");
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006725 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Richard Smith6eedfe72017-01-09 08:01:21 +00006726 SuppressUserConversions, PartialOverloading,
6727 /*AllowExplicit*/false, Conversions);
6728}
6729
6730/// Check that implicit conversion sequences can be formed for each argument
6731/// whose corresponding parameter has a non-dependent type, per DR1391's
6732/// [temp.deduct.call]p10.
6733bool Sema::CheckNonDependentConversions(
6734 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
6735 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
6736 ConversionSequenceList &Conversions, bool SuppressUserConversions,
6737 CXXRecordDecl *ActingContext, QualType ObjectType,
6738 Expr::Classification ObjectClassification) {
6739 // FIXME: The cases in which we allow explicit conversions for constructor
6740 // arguments never consider calling a constructor template. It's not clear
6741 // that is correct.
6742 const bool AllowExplicit = false;
6743
6744 auto *FD = FunctionTemplate->getTemplatedDecl();
6745 auto *Method = dyn_cast<CXXMethodDecl>(FD);
6746 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
6747 unsigned ThisConversions = HasThisConversion ? 1 : 0;
6748
6749 Conversions =
6750 CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
6751
6752 // Overload resolution is always an unevaluated context.
Faisal Valid143a0c2017-04-01 21:30:49 +00006753 EnterExpressionEvaluationContext Unevaluated(
6754 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Richard Smith6eedfe72017-01-09 08:01:21 +00006755
6756 // For a method call, check the 'this' conversion here too. DR1391 doesn't
6757 // require that, but this check should never result in a hard error, and
6758 // overload resolution is permitted to sidestep instantiations.
6759 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
6760 !ObjectType.isNull()) {
6761 Conversions[0] = TryObjectArgumentInitialization(
6762 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6763 Method, ActingContext);
6764 if (Conversions[0].isBad())
6765 return true;
6766 }
6767
6768 for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N;
6769 ++I) {
6770 QualType ParamType = ParamTypes[I];
6771 if (!ParamType->isDependentType()) {
6772 Conversions[ThisConversions + I]
6773 = TryCopyInitialization(*this, Args[I], ParamType,
6774 SuppressUserConversions,
6775 /*InOverloadResolution=*/true,
6776 /*AllowObjCWritebackConversion=*/
6777 getLangOpts().ObjCAutoRefCount,
6778 AllowExplicit);
6779 if (Conversions[ThisConversions + I].isBad())
6780 return true;
6781 }
6782 }
6783
6784 return false;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006785}
Mike Stump11289f42009-09-09 15:08:12 +00006786
Douglas Gregor4b60a152013-11-07 22:34:54 +00006787/// Determine whether this is an allowable conversion from the result
6788/// of an explicit conversion operator to the expected type, per C++
6789/// [over.match.conv]p1 and [over.match.ref]p1.
6790///
6791/// \param ConvType The return type of the conversion function.
6792///
6793/// \param ToType The type we are converting to.
6794///
6795/// \param AllowObjCPointerConversion Allow a conversion from one
6796/// Objective-C pointer to another.
6797///
6798/// \returns true if the conversion is allowable, false otherwise.
6799static bool isAllowableExplicitConversion(Sema &S,
6800 QualType ConvType, QualType ToType,
6801 bool AllowObjCPointerConversion) {
6802 QualType ToNonRefType = ToType.getNonReferenceType();
6803
6804 // Easy case: the types are the same.
6805 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6806 return true;
6807
6808 // Allow qualification conversions.
6809 bool ObjCLifetimeConversion;
6810 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6811 ObjCLifetimeConversion))
6812 return true;
6813
6814 // If we're not allowed to consider Objective-C pointer conversions,
6815 // we're done.
6816 if (!AllowObjCPointerConversion)
6817 return false;
6818
6819 // Is this an Objective-C pointer conversion?
6820 bool IncompatibleObjC = false;
6821 QualType ConvertedType;
6822 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6823 IncompatibleObjC);
6824}
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00006825
Douglas Gregora1f013e2008-11-07 22:36:19 +00006826/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00006827/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00006828/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00006829/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00006830/// (which may or may not be the same type as the type that the
6831/// conversion function produces).
6832void
6833Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006834 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006835 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00006836 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006837 OverloadCandidateSet& CandidateSet,
Richard Smith67ef14f2017-09-26 18:37:55 +00006838 bool AllowObjCConversionOnExplicit,
6839 bool AllowResultConversion) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006840 assert(!Conversion->getDescribedFunctionTemplate() &&
6841 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00006842 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006843 if (!CandidateSet.isNewCandidate(Conversion))
6844 return;
6845
Richard Smith2a7d4812013-05-04 07:00:32 +00006846 // If the conversion function has an undeduced return type, trigger its
6847 // deduction now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006848 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00006849 if (DeduceReturnType(Conversion, From->getExprLoc()))
6850 return;
6851 ConvType = Conversion->getConversionType().getNonReferenceType();
6852 }
6853
Richard Smith67ef14f2017-09-26 18:37:55 +00006854 // If we don't allow any conversion of the result type, ignore conversion
6855 // functions that don't convert to exactly (possibly cv-qualified) T.
6856 if (!AllowResultConversion &&
6857 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
6858 return;
6859
Richard Smith089c3162013-09-21 21:55:46 +00006860 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6861 // operator is only a candidate if its return type is the target type or
6862 // can be converted to the target type with a qualification conversion.
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00006863 if (Conversion->isExplicit() &&
6864 !isAllowableExplicitConversion(*this, ConvType, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006865 AllowObjCConversionOnExplicit))
Richard Smith089c3162013-09-21 21:55:46 +00006866 return;
6867
Douglas Gregor27381f32009-11-23 12:27:39 +00006868 // Overload resolution is always an unevaluated context.
Faisal Valid143a0c2017-04-01 21:30:49 +00006869 EnterExpressionEvaluationContext Unevaluated(
6870 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006871
Douglas Gregora1f013e2008-11-07 22:36:19 +00006872 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006873 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCalla0296f72010-03-19 07:35:19 +00006874 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006875 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006876 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006877 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006878 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00006879 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00006880 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00006881 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006882 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006883
Douglas Gregor6affc782010-08-19 15:37:02 +00006884 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006885 // For conversion functions, the function is considered to be a member of
6886 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00006887 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006888 //
6889 // Determine the implicit conversion sequence for the implicit
6890 // object parameter.
6891 QualType ImplicitParamType = From->getType();
6892 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6893 ImplicitParamType = FromPtrType->getPointeeType();
6894 CXXRecordDecl *ConversionContext
6895 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006896
Richard Smith0f59cb32015-12-18 21:45:41 +00006897 Candidate.Conversions[0] = TryObjectArgumentInitialization(
6898 *this, CandidateSet.getLocation(), From->getType(),
6899 From->Classify(Context), Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006900
John McCall0d1da222010-01-12 00:44:57 +00006901 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006902 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006903 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006904 return;
6905 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006906
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006907 // We won't go through a user-defined type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006908 // derived to base as such conversions are given Conversion Rank. They only
6909 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6910 QualType FromCanon
6911 = Context.getCanonicalType(From->getType().getUnqualifiedType());
6912 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
Richard Smith0f59cb32015-12-18 21:45:41 +00006913 if (FromCanon == ToCanon ||
6914 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006915 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006916 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006917 return;
6918 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006919
Douglas Gregora1f013e2008-11-07 22:36:19 +00006920 // To determine what the conversion from the result of calling the
6921 // conversion function to the type we're eventually trying to
6922 // convert to (ToType), we need to synthesize a call to the
6923 // conversion function and attempt copy initialization from it. This
6924 // makes sure that we get the right semantics with respect to
6925 // lvalues/rvalues and the type. Fortunately, we can allocate this
6926 // call on the stack and we don't need its arguments to be
6927 // well-formed.
John McCall113bee02012-03-10 09:33:50 +00006928 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00006929 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00006930 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6931 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00006932 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00006933 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00006934
Richard Smith48d24642011-07-13 22:53:21 +00006935 QualType ConversionType = Conversion->getConversionType();
Richard Smithdb0ac552015-12-18 22:40:25 +00006936 if (!isCompleteType(From->getLocStart(), ConversionType)) {
Douglas Gregor72ebdab2010-11-13 19:36:57 +00006937 Candidate.Viable = false;
6938 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6939 return;
6940 }
6941
Richard Smith48d24642011-07-13 22:53:21 +00006942 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCall7decc9e2010-11-18 06:31:45 +00006943
Mike Stump11289f42009-09-09 15:08:12 +00006944 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00006945 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6946 // allocator).
Richard Smith48d24642011-07-13 22:53:21 +00006947 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00006948 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00006949 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00006950 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006951 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00006952 /*SuppressUserConversions=*/true,
John McCall31168b02011-06-15 23:02:42 +00006953 /*InOverloadResolution=*/false,
6954 /*AllowObjCWritebackConversion=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00006955
John McCall0d1da222010-01-12 00:44:57 +00006956 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006957 case ImplicitConversionSequence::StandardConversion:
6958 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006959
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006960 // C++ [over.ics.user]p3:
6961 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006962 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006963 // shall have exact match rank.
6964 if (Conversion->getPrimaryTemplate() &&
6965 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6966 Candidate.Viable = false;
6967 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006968 return;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006969 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006970
Douglas Gregorcba72b12011-01-21 05:18:22 +00006971 // C++0x [dcl.init.ref]p5:
6972 // In the second case, if the reference is an rvalue reference and
6973 // the second standard conversion sequence of the user-defined
6974 // conversion sequence includes an lvalue-to-rvalue conversion, the
6975 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006976 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00006977 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6978 Candidate.Viable = false;
6979 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006980 return;
Douglas Gregorcba72b12011-01-21 05:18:22 +00006981 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00006982 break;
6983
6984 case ImplicitConversionSequence::BadConversion:
6985 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006986 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006987 return;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006988
6989 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006990 llvm_unreachable(
Douglas Gregora1f013e2008-11-07 22:36:19 +00006991 "Can only end up with a standard conversion sequence or failure");
6992 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006993
Craig Topper5fc8fc22014-08-27 06:28:36 +00006994 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006995 Candidate.Viable = false;
6996 Candidate.FailureKind = ovl_fail_enable_if;
6997 Candidate.DeductionFailure.Data = FailedAttr;
6998 return;
6999 }
Erich Keane281d20b2018-01-08 21:34:17 +00007000
7001 if (Conversion->isMultiVersion() &&
7002 !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) {
7003 Candidate.Viable = false;
7004 Candidate.FailureKind = ovl_non_default_multiversion_function;
7005 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00007006}
7007
Douglas Gregor05155d82009-08-21 23:19:43 +00007008/// \brief Adds a conversion function template specialization
7009/// candidate to the overload set, using template argument deduction
7010/// to deduce the template arguments of the conversion function
7011/// template from the type that we are converting to (C++
7012/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00007013void
Douglas Gregor05155d82009-08-21 23:19:43 +00007014Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00007015 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00007016 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00007017 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00007018 OverloadCandidateSet &CandidateSet,
Richard Smith67ef14f2017-09-26 18:37:55 +00007019 bool AllowObjCConversionOnExplicit,
7020 bool AllowResultConversion) {
Douglas Gregor05155d82009-08-21 23:19:43 +00007021 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
7022 "Only conversion function templates permitted here");
7023
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00007024 if (!CandidateSet.isNewCandidate(FunctionTemplate))
7025 return;
7026
Craig Toppere6706e42012-09-19 02:26:47 +00007027 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00007028 CXXConversionDecl *Specialization = nullptr;
Douglas Gregor05155d82009-08-21 23:19:43 +00007029 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00007030 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00007031 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00007032 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00007033 Candidate.FoundDecl = FoundDecl;
7034 Candidate.Function = FunctionTemplate->getTemplatedDecl();
7035 Candidate.Viable = false;
7036 Candidate.FailureKind = ovl_fail_bad_deduction;
7037 Candidate.IsSurrogate = false;
7038 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00007039 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007040 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00007041 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00007042 return;
7043 }
Mike Stump11289f42009-09-09 15:08:12 +00007044
Douglas Gregor05155d82009-08-21 23:19:43 +00007045 // Add the conversion function template specialization produced by
7046 // template argument deduction as a candidate.
7047 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00007048 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
Richard Smith67ef14f2017-09-26 18:37:55 +00007049 CandidateSet, AllowObjCConversionOnExplicit,
7050 AllowResultConversion);
Douglas Gregor05155d82009-08-21 23:19:43 +00007051}
7052
Douglas Gregorab7897a2008-11-19 22:57:39 +00007053/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
7054/// converts the given @c Object to a function pointer via the
7055/// conversion function @c Conversion, and then attempts to call it
7056/// with the given arguments (C++ [over.call.object]p2-4). Proto is
7057/// the type of function that we'll eventually be calling.
7058void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00007059 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00007060 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007061 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00007062 Expr *Object,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007063 ArrayRef<Expr *> Args,
Douglas Gregorab7897a2008-11-19 22:57:39 +00007064 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00007065 if (!CandidateSet.isNewCandidate(Conversion))
7066 return;
7067
Douglas Gregor27381f32009-11-23 12:27:39 +00007068 // Overload resolution is always an unevaluated context.
Faisal Valid143a0c2017-04-01 21:30:49 +00007069 EnterExpressionEvaluationContext Unevaluated(
7070 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00007071
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00007072 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00007073 Candidate.FoundDecl = FoundDecl;
Craig Topperc3ec1492014-05-26 06:22:03 +00007074 Candidate.Function = nullptr;
Douglas Gregorab7897a2008-11-19 22:57:39 +00007075 Candidate.Surrogate = Conversion;
7076 Candidate.Viable = true;
7077 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007078 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00007079 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregorab7897a2008-11-19 22:57:39 +00007080
7081 // Determine the implicit conversion sequence for the implicit
7082 // object parameter.
Richard Smith0f59cb32015-12-18 21:45:41 +00007083 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
7084 *this, CandidateSet.getLocation(), Object->getType(),
7085 Object->Classify(Context), Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00007086 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00007087 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00007088 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00007089 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00007090 return;
7091 }
7092
7093 // The first conversion is actually a user-defined conversion whose
7094 // first conversion is ObjectInit's standard conversion (which is
7095 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00007096 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00007097 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00007098 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00007099 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00007100 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00007101 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump11289f42009-09-09 15:08:12 +00007102 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00007103 = Candidate.Conversions[0].UserDefined.Before;
7104 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
7105
Mike Stump11289f42009-09-09 15:08:12 +00007106 // Find the
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00007107 unsigned NumParams = Proto->getNumParams();
Douglas Gregorab7897a2008-11-19 22:57:39 +00007108
7109 // (C++ 13.3.2p2): A candidate function having fewer than m
7110 // parameters is viable only if it has an ellipsis in its parameter
7111 // list (8.3.5).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00007112 if (Args.size() > NumParams && !Proto->isVariadic()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00007113 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00007114 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00007115 return;
7116 }
7117
7118 // Function types don't have any default arguments, so just check if
7119 // we have enough arguments.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00007120 if (Args.size() < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00007121 // Not enough arguments.
7122 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00007123 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00007124 return;
7125 }
7126
7127 // Determine the implicit conversion sequences for each of the
7128 // arguments.
Richard Smithe54c3072013-05-05 15:51:06 +00007129 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00007130 if (ArgIdx < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00007131 // (C++ 13.3.2p3): for F to be a viable function, there shall
7132 // exist for each argument an implicit conversion sequence
7133 // (13.3.3.1) that converts that argument to the corresponding
7134 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00007135 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00007136 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00007137 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00007138 /*SuppressUserConversions=*/false,
John McCall31168b02011-06-15 23:02:42 +00007139 /*InOverloadResolution=*/false,
7140 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00007141 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00007142 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00007143 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00007144 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007145 return;
Douglas Gregorab7897a2008-11-19 22:57:39 +00007146 }
7147 } else {
7148 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7149 // argument for which there is no corresponding parameter is
7150 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00007151 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00007152 }
7153 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007154
Craig Topper5fc8fc22014-08-27 06:28:36 +00007155 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007156 Candidate.Viable = false;
7157 Candidate.FailureKind = ovl_fail_enable_if;
7158 Candidate.DeductionFailure.Data = FailedAttr;
7159 return;
7160 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00007161}
7162
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007163/// \brief Add overload candidates for overloaded operators that are
7164/// member functions.
7165///
7166/// Add the overloaded operator candidates that are member functions
7167/// for the operator Op that was used in an operator expression such
7168/// as "x Op y". , Args/NumArgs provides the operator arguments, and
7169/// CandidateSet will store the added overload candidates. (C++
7170/// [over.match.oper]).
7171void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
7172 SourceLocation OpLoc,
Richard Smithe54c3072013-05-05 15:51:06 +00007173 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007174 OverloadCandidateSet& CandidateSet,
7175 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00007176 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7177
7178 // C++ [over.match.oper]p3:
7179 // For a unary operator @ with an operand of a type whose
7180 // cv-unqualified version is T1, and for a binary operator @ with
7181 // a left operand of a type whose cv-unqualified version is T1 and
7182 // a right operand of a type whose cv-unqualified version is T2,
7183 // three sets of candidate functions, designated member
7184 // candidates, non-member candidates and built-in candidates, are
7185 // constructed as follows:
7186 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00007187
Richard Smith0feaf0c2013-04-20 12:41:22 +00007188 // -- If T1 is a complete class type or a class currently being
7189 // defined, the set of member candidates is the result of the
7190 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
7191 // the set of member candidates is empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007192 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Richard Smith0feaf0c2013-04-20 12:41:22 +00007193 // Complete the type if it can be completed.
Richard Smithdb0ac552015-12-18 22:40:25 +00007194 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
Richard Smith82b8d4e2015-12-18 22:19:11 +00007195 return;
Richard Smith0feaf0c2013-04-20 12:41:22 +00007196 // If the type is neither complete nor being defined, bail out now.
7197 if (!T1Rec->getDecl()->getDefinition())
Douglas Gregor6a1f9652009-08-27 23:35:55 +00007198 return;
Mike Stump11289f42009-09-09 15:08:12 +00007199
John McCall27b18f82009-11-17 02:14:36 +00007200 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
7201 LookupQualifiedName(Operators, T1Rec->getDecl());
7202 Operators.suppressDiagnostics();
7203
Mike Stump11289f42009-09-09 15:08:12 +00007204 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00007205 OperEnd = Operators.end();
7206 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00007207 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00007208 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
George Burgess IVce6284b2017-01-28 02:19:40 +00007209 Args[0]->Classify(Context), Args.slice(1),
George Burgess IV177399e2017-01-09 04:12:14 +00007210 CandidateSet, /*SuppressUserConversions=*/false);
Douglas Gregor436424c2008-11-18 23:14:02 +00007211 }
Douglas Gregor436424c2008-11-18 23:14:02 +00007212}
7213
Douglas Gregora11693b2008-11-12 17:17:38 +00007214/// AddBuiltinCandidate - Add a candidate for a built-in
7215/// operator. ResultTy and ParamTys are the result and parameter types
7216/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00007217/// arguments being passed to the candidate. IsAssignmentOperator
7218/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00007219/// operator. NumContextualBoolArguments is the number of arguments
7220/// (at the beginning of the argument list) that will be contextually
7221/// converted to bool.
George Burgess IVc07c3892017-06-08 18:19:25 +00007222void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
Douglas Gregorc5e61072009-01-13 00:52:54 +00007223 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00007224 bool IsAssignmentOperator,
7225 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00007226 // Overload resolution is always an unevaluated context.
Faisal Valid143a0c2017-04-01 21:30:49 +00007227 EnterExpressionEvaluationContext Unevaluated(
7228 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00007229
Douglas Gregora11693b2008-11-12 17:17:38 +00007230 // Add this candidate
Richard Smithe54c3072013-05-05 15:51:06 +00007231 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
Craig Topperc3ec1492014-05-26 06:22:03 +00007232 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
7233 Candidate.Function = nullptr;
Douglas Gregor1d248c52008-12-12 02:00:36 +00007234 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007235 Candidate.IgnoreObjectArgument = false;
George Burgess IV5f6ab9a2017-06-08 20:55:21 +00007236 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
Douglas Gregora11693b2008-11-12 17:17:38 +00007237
7238 // Determine the implicit conversion sequences for each of the
7239 // arguments.
7240 Candidate.Viable = true;
Richard Smithe54c3072013-05-05 15:51:06 +00007241 Candidate.ExplicitCallArguments = Args.size();
7242 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00007243 // C++ [over.match.oper]p4:
7244 // For the built-in assignment operators, conversions of the
7245 // left operand are restricted as follows:
7246 // -- no temporaries are introduced to hold the left operand, and
7247 // -- no user-defined conversions are applied to the left
7248 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00007249 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00007250 //
7251 // We block these conversions by turning off user-defined
7252 // conversions, since that is the only way that initialization of
7253 // a reference to a non-class type can occur from something that
7254 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00007255 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00007256 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00007257 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00007258 Candidate.Conversions[ArgIdx]
7259 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00007260 } else {
Mike Stump11289f42009-09-09 15:08:12 +00007261 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00007262 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00007263 ArgIdx == 0 && IsAssignmentOperator,
John McCall31168b02011-06-15 23:02:42 +00007264 /*InOverloadResolution=*/false,
7265 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00007266 getLangOpts().ObjCAutoRefCount);
Douglas Gregor5fb53972009-01-14 15:45:31 +00007267 }
John McCall0d1da222010-01-12 00:44:57 +00007268 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007269 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00007270 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00007271 break;
7272 }
Douglas Gregora11693b2008-11-12 17:17:38 +00007273 }
7274}
7275
Craig Toppercd7b0332013-07-01 06:29:40 +00007276namespace {
7277
Douglas Gregora11693b2008-11-12 17:17:38 +00007278/// BuiltinCandidateTypeSet - A set of types that will be used for the
7279/// candidate operator functions for built-in operators (C++
7280/// [over.built]). The types are separated into pointer types and
7281/// enumeration types.
7282class BuiltinCandidateTypeSet {
7283 /// TypeSet - A set of types.
Richard Smith95853072016-03-25 00:08:53 +00007284 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
7285 llvm::SmallPtrSet<QualType, 8>> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00007286
7287 /// PointerTypes - The set of pointer types that will be used in the
7288 /// built-in candidates.
7289 TypeSet PointerTypes;
7290
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007291 /// MemberPointerTypes - The set of member pointer types that will be
7292 /// used in the built-in candidates.
7293 TypeSet MemberPointerTypes;
7294
Douglas Gregora11693b2008-11-12 17:17:38 +00007295 /// EnumerationTypes - The set of enumeration types that will be
7296 /// used in the built-in candidates.
7297 TypeSet EnumerationTypes;
7298
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007299 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007300 /// candidates.
7301 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00007302
7303 /// \brief A flag indicating non-record types are viable candidates
7304 bool HasNonRecordTypes;
7305
7306 /// \brief A flag indicating whether either arithmetic or enumeration types
7307 /// were present in the candidate set.
7308 bool HasArithmeticOrEnumeralTypes;
7309
Douglas Gregor80af3132011-05-21 23:15:46 +00007310 /// \brief A flag indicating whether the nullptr type was present in the
7311 /// candidate set.
7312 bool HasNullPtrType;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00007313
Douglas Gregor8a2e6012009-08-24 15:23:48 +00007314 /// Sema - The semantic analysis instance where we are building the
7315 /// candidate type set.
7316 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00007317
Douglas Gregora11693b2008-11-12 17:17:38 +00007318 /// Context - The AST context in which we will build the type sets.
7319 ASTContext &Context;
7320
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007321 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7322 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007323 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00007324
7325public:
7326 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00007327 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00007328
Mike Stump11289f42009-09-09 15:08:12 +00007329 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00007330 : HasNonRecordTypes(false),
7331 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor80af3132011-05-21 23:15:46 +00007332 HasNullPtrType(false),
Chandler Carruth00a38332010-12-13 01:44:01 +00007333 SemaRef(SemaRef),
7334 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00007335
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007336 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007337 SourceLocation Loc,
7338 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007339 bool AllowExplicitConversions,
7340 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00007341
7342 /// pointer_begin - First pointer type found;
7343 iterator pointer_begin() { return PointerTypes.begin(); }
7344
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007345 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00007346 iterator pointer_end() { return PointerTypes.end(); }
7347
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007348 /// member_pointer_begin - First member pointer type found;
7349 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
7350
7351 /// member_pointer_end - Past the last member pointer type found;
7352 iterator member_pointer_end() { return MemberPointerTypes.end(); }
7353
Douglas Gregora11693b2008-11-12 17:17:38 +00007354 /// enumeration_begin - First enumeration type found;
7355 iterator enumeration_begin() { return EnumerationTypes.begin(); }
7356
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007357 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00007358 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007359
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007360 iterator vector_begin() { return VectorTypes.begin(); }
7361 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00007362
7363 bool hasNonRecordTypes() { return HasNonRecordTypes; }
7364 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor80af3132011-05-21 23:15:46 +00007365 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregora11693b2008-11-12 17:17:38 +00007366};
7367
Craig Toppercd7b0332013-07-01 06:29:40 +00007368} // end anonymous namespace
7369
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007370/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00007371/// the set of pointer types along with any more-qualified variants of
7372/// that type. For example, if @p Ty is "int const *", this routine
7373/// will add "int const *", "int const volatile *", "int const
7374/// restrict *", and "int const volatile restrict *" to the set of
7375/// pointer types. Returns true if the add of @p Ty itself succeeded,
7376/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00007377///
7378/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007379bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007380BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7381 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00007382
Douglas Gregora11693b2008-11-12 17:17:38 +00007383 // Insert this type.
Richard Smith95853072016-03-25 00:08:53 +00007384 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00007385 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007386
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00007387 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00007388 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00007389 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00007390 if (!PointerTy) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00007391 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7392 PointeeTy = PTy->getPointeeType();
7393 buildObjCPtr = true;
7394 } else {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00007395 PointeeTy = PointerTy->getPointeeType();
Douglas Gregor5bee2582012-06-04 00:15:09 +00007396 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00007397
Sebastian Redl4990a632009-11-18 20:39:26 +00007398 // Don't add qualified variants of arrays. For one, they're not allowed
7399 // (the qualifier would sink to the element type), and for another, the
7400 // only overload situation where it matters is subscript or pointer +- int,
7401 // and those shouldn't have qualifier variants anyway.
7402 if (PointeeTy->isArrayType())
7403 return true;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00007404
John McCall8ccfcb52009-09-24 19:53:00 +00007405 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007406 bool hasVolatile = VisibleQuals.hasVolatile();
7407 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007408
John McCall8ccfcb52009-09-24 19:53:00 +00007409 // Iterate through all strict supersets of BaseCVR.
7410 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7411 if ((CVR | BaseCVR) != CVR) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00007412 // Skip over volatile if no volatile found anywhere in the types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007413 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00007414
Douglas Gregor5bee2582012-06-04 00:15:09 +00007415 // Skip over restrict if no restrict found anywhere in the types, or if
7416 // the type cannot be restrict-qualified.
7417 if ((CVR & Qualifiers::Restrict) &&
7418 (!hasRestrict ||
7419 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7420 continue;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00007421
Douglas Gregor5bee2582012-06-04 00:15:09 +00007422 // Build qualified pointee type.
John McCall8ccfcb52009-09-24 19:53:00 +00007423 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00007424
Douglas Gregor5bee2582012-06-04 00:15:09 +00007425 // Build qualified pointer type.
7426 QualType QPointerTy;
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00007427 if (!buildObjCPtr)
Douglas Gregor5bee2582012-06-04 00:15:09 +00007428 QPointerTy = Context.getPointerType(QPointeeTy);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00007429 else
Douglas Gregor5bee2582012-06-04 00:15:09 +00007430 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00007431
Douglas Gregor5bee2582012-06-04 00:15:09 +00007432 // Insert qualified pointer type.
7433 PointerTypes.insert(QPointerTy);
Douglas Gregora11693b2008-11-12 17:17:38 +00007434 }
7435
7436 return true;
7437}
7438
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007439/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7440/// to the set of pointer types along with any more-qualified variants of
7441/// that type. For example, if @p Ty is "int const *", this routine
7442/// will add "int const *", "int const volatile *", "int const
7443/// restrict *", and "int const volatile restrict *" to the set of
7444/// pointer types. Returns true if the add of @p Ty itself succeeded,
7445/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00007446///
7447/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007448bool
7449BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7450 QualType Ty) {
7451 // Insert this type.
Richard Smith95853072016-03-25 00:08:53 +00007452 if (!MemberPointerTypes.insert(Ty))
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007453 return false;
7454
John McCall8ccfcb52009-09-24 19:53:00 +00007455 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
7456 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007457
John McCall8ccfcb52009-09-24 19:53:00 +00007458 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00007459 // Don't add qualified variants of arrays. For one, they're not allowed
7460 // (the qualifier would sink to the element type), and for another, the
7461 // only overload situation where it matters is subscript or pointer +- int,
7462 // and those shouldn't have qualifier variants anyway.
7463 if (PointeeTy->isArrayType())
7464 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00007465 const Type *ClassTy = PointerTy->getClass();
7466
7467 // Iterate through all strict supersets of the pointee type's CVR
7468 // qualifiers.
7469 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7470 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7471 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007472
John McCall8ccfcb52009-09-24 19:53:00 +00007473 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00007474 MemberPointerTypes.insert(
7475 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007476 }
7477
7478 return true;
7479}
7480
Douglas Gregora11693b2008-11-12 17:17:38 +00007481/// AddTypesConvertedFrom - Add each of the types to which the type @p
7482/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007483/// primarily interested in pointer types and enumeration types. We also
7484/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00007485/// AllowUserConversions is true if we should look at the conversion
7486/// functions of a class type, and AllowExplicitConversions if we
7487/// should also include the explicit conversion functions of a class
7488/// type.
Mike Stump11289f42009-09-09 15:08:12 +00007489void
Douglas Gregor5fb53972009-01-14 15:45:31 +00007490BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007491 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00007492 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007493 bool AllowExplicitConversions,
7494 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007495 // Only deal with canonical types.
7496 Ty = Context.getCanonicalType(Ty);
7497
7498 // Look through reference types; they aren't part of the type of an
7499 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007500 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00007501 Ty = RefTy->getPointeeType();
7502
John McCall33ddac02011-01-19 10:06:00 +00007503 // If we're dealing with an array type, decay to the pointer.
7504 if (Ty->isArrayType())
7505 Ty = SemaRef.Context.getArrayDecayedType(Ty);
7506
7507 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007508 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00007509
Chandler Carruth00a38332010-12-13 01:44:01 +00007510 // Flag if we ever add a non-record type.
7511 const RecordType *TyRec = Ty->getAs<RecordType>();
7512 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7513
Chandler Carruth00a38332010-12-13 01:44:01 +00007514 // Flag if we encounter an arithmetic type.
7515 HasArithmeticOrEnumeralTypes =
7516 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7517
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00007518 if (Ty->isObjCIdType() || Ty->isObjCClassType())
7519 PointerTypes.insert(Ty);
7520 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007521 // Insert our type, and its more-qualified variants, into the set
7522 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007523 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00007524 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007525 } else if (Ty->isMemberPointerType()) {
7526 // Member pointers are far easier, since the pointee can't be converted.
7527 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7528 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00007529 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007530 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00007531 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007532 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007533 // We treat vector types as arithmetic types in many contexts as an
7534 // extension.
7535 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007536 VectorTypes.insert(Ty);
Douglas Gregor80af3132011-05-21 23:15:46 +00007537 } else if (Ty->isNullPtrType()) {
7538 HasNullPtrType = true;
Chandler Carruth00a38332010-12-13 01:44:01 +00007539 } else if (AllowUserConversions && TyRec) {
7540 // No conversion functions in incomplete types.
Richard Smithdb0ac552015-12-18 22:40:25 +00007541 if (!SemaRef.isCompleteType(Loc, Ty))
Chandler Carruth00a38332010-12-13 01:44:01 +00007542 return;
Mike Stump11289f42009-09-09 15:08:12 +00007543
Chandler Carruth00a38332010-12-13 01:44:01 +00007544 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00007545 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007546 if (isa<UsingShadowDecl>(D))
7547 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00007548
Chandler Carruth00a38332010-12-13 01:44:01 +00007549 // Skip conversion function templates; they don't tell us anything
7550 // about which builtin types we can convert to.
7551 if (isa<FunctionTemplateDecl>(D))
7552 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00007553
Chandler Carruth00a38332010-12-13 01:44:01 +00007554 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7555 if (AllowExplicitConversions || !Conv->isExplicit()) {
7556 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7557 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00007558 }
7559 }
7560 }
7561}
7562
Douglas Gregor84605ae2009-08-24 13:43:27 +00007563/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
7564/// the volatile- and non-volatile-qualified assignment operators for the
7565/// given type to the candidate set.
7566static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7567 QualType T,
Richard Smithe54c3072013-05-05 15:51:06 +00007568 ArrayRef<Expr *> Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00007569 OverloadCandidateSet &CandidateSet) {
7570 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00007571
Douglas Gregor84605ae2009-08-24 13:43:27 +00007572 // T& operator=(T&, T)
7573 ParamTypes[0] = S.Context.getLValueReferenceType(T);
7574 ParamTypes[1] = T;
George Burgess IVc07c3892017-06-08 18:19:25 +00007575 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Douglas Gregor84605ae2009-08-24 13:43:27 +00007576 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00007577
Douglas Gregor84605ae2009-08-24 13:43:27 +00007578 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7579 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00007580 ParamTypes[0]
7581 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00007582 ParamTypes[1] = T;
George Burgess IVc07c3892017-06-08 18:19:25 +00007583 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00007584 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00007585 }
7586}
Mike Stump11289f42009-09-09 15:08:12 +00007587
Sebastian Redl1054fae2009-10-25 17:03:50 +00007588/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7589/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007590static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7591 Qualifiers VRQuals;
7592 const RecordType *TyRec;
7593 if (const MemberPointerType *RHSMPType =
7594 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00007595 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007596 else
7597 TyRec = ArgExpr->getType()->getAs<RecordType>();
7598 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007599 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007600 VRQuals.addVolatile();
7601 VRQuals.addRestrict();
7602 return VRQuals;
7603 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007604
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007605 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00007606 if (!ClassDecl->hasDefinition())
7607 return VRQuals;
7608
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00007609 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
John McCallda4458e2010-03-31 01:36:47 +00007610 if (isa<UsingShadowDecl>(D))
7611 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7612 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007613 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7614 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7615 CanTy = ResTypeRef->getPointeeType();
7616 // Need to go down the pointer/mempointer chain and add qualifiers
7617 // as see them.
7618 bool done = false;
7619 while (!done) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00007620 if (CanTy.isRestrictQualified())
7621 VRQuals.addRestrict();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007622 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7623 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007624 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007625 CanTy->getAs<MemberPointerType>())
7626 CanTy = ResTypeMPtr->getPointeeType();
7627 else
7628 done = true;
7629 if (CanTy.isVolatileQualified())
7630 VRQuals.addVolatile();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007631 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7632 return VRQuals;
7633 }
7634 }
7635 }
7636 return VRQuals;
7637}
John McCall52872982010-11-13 05:51:15 +00007638
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007639namespace {
John McCall52872982010-11-13 05:51:15 +00007640
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007641/// \brief Helper class to manage the addition of builtin operator overload
7642/// candidates. It provides shared state and utility methods used throughout
7643/// the process, as well as a helper method to add each group of builtin
7644/// operator overloads from the standard to a candidate set.
7645class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007646 // Common instance state available to all overload candidate addition methods.
7647 Sema &S;
Richard Smithe54c3072013-05-05 15:51:06 +00007648 ArrayRef<Expr *> Args;
Chandler Carruthc6586e52010-12-12 10:35:00 +00007649 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00007650 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007651 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruthc6586e52010-12-12 10:35:00 +00007652 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007653
Hans Wennborg82371412017-11-15 17:11:53 +00007654 static constexpr int ArithmeticTypesCap = 24;
7655 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
7656
7657 // Define some indices used to iterate over the arithemetic types in
7658 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic
John McCall52872982010-11-13 05:51:15 +00007659 // types are that preserved by promotion (C++ [over.built]p2).
Hans Wennborg82371412017-11-15 17:11:53 +00007660 unsigned FirstIntegralType,
7661 LastIntegralType;
7662 unsigned FirstPromotedIntegralType,
7663 LastPromotedIntegralType;
7664 unsigned FirstPromotedArithmeticType,
7665 LastPromotedArithmeticType;
7666 unsigned NumArithmeticTypes;
John McCall52872982010-11-13 05:51:15 +00007667
Hans Wennborg82371412017-11-15 17:11:53 +00007668 void InitArithmeticTypes() {
7669 // Start of promoted types.
7670 FirstPromotedArithmeticType = 0;
7671 ArithmeticTypes.push_back(S.Context.FloatTy);
7672 ArithmeticTypes.push_back(S.Context.DoubleTy);
7673 ArithmeticTypes.push_back(S.Context.LongDoubleTy);
7674 if (S.Context.getTargetInfo().hasFloat128Type())
7675 ArithmeticTypes.push_back(S.Context.Float128Ty);
John McCall52872982010-11-13 05:51:15 +00007676
Hans Wennborg82371412017-11-15 17:11:53 +00007677 // Start of integral types.
7678 FirstIntegralType = ArithmeticTypes.size();
7679 FirstPromotedIntegralType = ArithmeticTypes.size();
7680 ArithmeticTypes.push_back(S.Context.IntTy);
7681 ArithmeticTypes.push_back(S.Context.LongTy);
7682 ArithmeticTypes.push_back(S.Context.LongLongTy);
7683 if (S.Context.getTargetInfo().hasInt128Type())
7684 ArithmeticTypes.push_back(S.Context.Int128Ty);
7685 ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
7686 ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
7687 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
7688 if (S.Context.getTargetInfo().hasInt128Type())
7689 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
7690 LastPromotedIntegralType = ArithmeticTypes.size();
7691 LastPromotedArithmeticType = ArithmeticTypes.size();
7692 // End of promoted types.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007693
Hans Wennborg82371412017-11-15 17:11:53 +00007694 ArithmeticTypes.push_back(S.Context.BoolTy);
7695 ArithmeticTypes.push_back(S.Context.CharTy);
7696 ArithmeticTypes.push_back(S.Context.WCharTy);
7697 ArithmeticTypes.push_back(S.Context.Char16Ty);
7698 ArithmeticTypes.push_back(S.Context.Char32Ty);
7699 ArithmeticTypes.push_back(S.Context.SignedCharTy);
7700 ArithmeticTypes.push_back(S.Context.ShortTy);
7701 ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
7702 ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
7703 LastIntegralType = ArithmeticTypes.size();
7704 NumArithmeticTypes = ArithmeticTypes.size();
7705 // End of integral types.
7706 // FIXME: What about complex? What about half?
7707
7708 assert(ArithmeticTypes.size() <= ArithmeticTypesCap &&
7709 "Enough inline storage for all arithmetic types.");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007710 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007711
Chandler Carruth5659c0c2010-12-12 09:22:45 +00007712 /// \brief Helper method to factor out the common pattern of adding overloads
7713 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007714 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007715 bool HasVolatile,
7716 bool HasRestrict) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007717 QualType ParamTypes[2] = {
7718 S.Context.getLValueReferenceType(CandidateTy),
7719 S.Context.IntTy
7720 };
7721
7722 // Non-volatile version.
George Burgess IVc07c3892017-06-08 18:19:25 +00007723 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007724
7725 // Use a heuristic to reduce number of builtin candidates in the set:
7726 // add volatile version only if there are conversions to a volatile type.
7727 if (HasVolatile) {
7728 ParamTypes[0] =
7729 S.Context.getLValueReferenceType(
7730 S.Context.getVolatileType(CandidateTy));
George Burgess IVc07c3892017-06-08 18:19:25 +00007731 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007732 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00007733
Douglas Gregor5bee2582012-06-04 00:15:09 +00007734 // Add restrict version only if there are conversions to a restrict type
7735 // and our candidate type is a non-restrict-qualified pointer.
7736 if (HasRestrict && CandidateTy->isAnyPointerType() &&
7737 !CandidateTy.isRestrictQualified()) {
7738 ParamTypes[0]
7739 = S.Context.getLValueReferenceType(
7740 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
George Burgess IVc07c3892017-06-08 18:19:25 +00007741 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00007742
Douglas Gregor5bee2582012-06-04 00:15:09 +00007743 if (HasVolatile) {
7744 ParamTypes[0]
7745 = S.Context.getLValueReferenceType(
7746 S.Context.getCVRQualifiedType(CandidateTy,
7747 (Qualifiers::Volatile |
7748 Qualifiers::Restrict)));
George Burgess IVc07c3892017-06-08 18:19:25 +00007749 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007750 }
7751 }
7752
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007753 }
7754
7755public:
7756 BuiltinOperatorOverloadBuilder(
Richard Smithe54c3072013-05-05 15:51:06 +00007757 Sema &S, ArrayRef<Expr *> Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007758 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00007759 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007760 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007761 OverloadCandidateSet &CandidateSet)
Richard Smithe54c3072013-05-05 15:51:06 +00007762 : S(S), Args(Args),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007763 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00007764 HasArithmeticOrEnumeralCandidateType(
7765 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007766 CandidateTypes(CandidateTypes),
7767 CandidateSet(CandidateSet) {
Hans Wennborg82371412017-11-15 17:11:53 +00007768
7769 InitArithmeticTypes();
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007770 }
7771
7772 // C++ [over.built]p3:
7773 //
7774 // For every pair (T, VQ), where T is an arithmetic type, and VQ
7775 // is either volatile or empty, there exist candidate operator
7776 // functions of the form
7777 //
7778 // VQ T& operator++(VQ T&);
7779 // T operator++(VQ T&, int);
7780 //
7781 // C++ [over.built]p4:
7782 //
7783 // For every pair (T, VQ), where T is an arithmetic type other
7784 // than bool, and VQ is either volatile or empty, there exist
7785 // candidate operator functions of the form
7786 //
7787 // VQ T& operator--(VQ T&);
7788 // T operator--(VQ T&, int);
7789 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007790 if (!HasArithmeticOrEnumeralCandidateType)
7791 return;
7792
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007793 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
7794 Arith < NumArithmeticTypes; ++Arith) {
7795 addPlusPlusMinusMinusStyleOverloads(
Hans Wennborg82371412017-11-15 17:11:53 +00007796 ArithmeticTypes[Arith],
Douglas Gregor5bee2582012-06-04 00:15:09 +00007797 VisibleTypeConversionsQuals.hasVolatile(),
7798 VisibleTypeConversionsQuals.hasRestrict());
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007799 }
7800 }
7801
7802 // C++ [over.built]p5:
7803 //
7804 // For every pair (T, VQ), where T is a cv-qualified or
7805 // cv-unqualified object type, and VQ is either volatile or
7806 // empty, there exist candidate operator functions of the form
7807 //
7808 // T*VQ& operator++(T*VQ&);
7809 // T*VQ& operator--(T*VQ&);
7810 // T* operator++(T*VQ&, int);
7811 // T* operator--(T*VQ&, int);
7812 void addPlusPlusMinusMinusPointerOverloads() {
7813 for (BuiltinCandidateTypeSet::iterator
7814 Ptr = CandidateTypes[0].pointer_begin(),
7815 PtrEnd = CandidateTypes[0].pointer_end();
7816 Ptr != PtrEnd; ++Ptr) {
7817 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00007818 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007819 continue;
7820
7821 addPlusPlusMinusMinusStyleOverloads(*Ptr,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007822 (!(*Ptr).isVolatileQualified() &&
7823 VisibleTypeConversionsQuals.hasVolatile()),
7824 (!(*Ptr).isRestrictQualified() &&
7825 VisibleTypeConversionsQuals.hasRestrict()));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007826 }
7827 }
7828
7829 // C++ [over.built]p6:
7830 // For every cv-qualified or cv-unqualified object type T, there
7831 // exist candidate operator functions of the form
7832 //
7833 // T& operator*(T*);
7834 //
7835 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007836 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00007837 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007838 // T& operator*(T*);
7839 void addUnaryStarPointerOverloads() {
7840 for (BuiltinCandidateTypeSet::iterator
7841 Ptr = CandidateTypes[0].pointer_begin(),
7842 PtrEnd = CandidateTypes[0].pointer_end();
7843 Ptr != PtrEnd; ++Ptr) {
7844 QualType ParamTy = *Ptr;
7845 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007846 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7847 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007848
Douglas Gregor02824322011-01-26 19:30:28 +00007849 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7850 if (Proto->getTypeQuals() || Proto->getRefQualifier())
7851 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007852
George Burgess IVc07c3892017-06-08 18:19:25 +00007853 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007854 }
7855 }
7856
7857 // C++ [over.built]p9:
7858 // For every promoted arithmetic type T, there exist candidate
7859 // operator functions of the form
7860 //
7861 // T operator+(T);
7862 // T operator-(T);
7863 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007864 if (!HasArithmeticOrEnumeralCandidateType)
7865 return;
7866
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007867 for (unsigned Arith = FirstPromotedArithmeticType;
7868 Arith < LastPromotedArithmeticType; ++Arith) {
Hans Wennborg82371412017-11-15 17:11:53 +00007869 QualType ArithTy = ArithmeticTypes[Arith];
George Burgess IVc07c3892017-06-08 18:19:25 +00007870 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007871 }
7872
7873 // Extension: We also add these operators for vector types.
7874 for (BuiltinCandidateTypeSet::iterator
7875 Vec = CandidateTypes[0].vector_begin(),
7876 VecEnd = CandidateTypes[0].vector_end();
7877 Vec != VecEnd; ++Vec) {
7878 QualType VecTy = *Vec;
George Burgess IVc07c3892017-06-08 18:19:25 +00007879 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007880 }
7881 }
7882
7883 // C++ [over.built]p8:
7884 // For every type T, there exist candidate operator functions of
7885 // the form
7886 //
7887 // T* operator+(T*);
7888 void addUnaryPlusPointerOverloads() {
7889 for (BuiltinCandidateTypeSet::iterator
7890 Ptr = CandidateTypes[0].pointer_begin(),
7891 PtrEnd = CandidateTypes[0].pointer_end();
7892 Ptr != PtrEnd; ++Ptr) {
7893 QualType ParamTy = *Ptr;
George Burgess IVc07c3892017-06-08 18:19:25 +00007894 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007895 }
7896 }
7897
7898 // C++ [over.built]p10:
7899 // For every promoted integral type T, there exist candidate
7900 // operator functions of the form
7901 //
7902 // T operator~(T);
7903 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007904 if (!HasArithmeticOrEnumeralCandidateType)
7905 return;
7906
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007907 for (unsigned Int = FirstPromotedIntegralType;
7908 Int < LastPromotedIntegralType; ++Int) {
Hans Wennborg82371412017-11-15 17:11:53 +00007909 QualType IntTy = ArithmeticTypes[Int];
George Burgess IVc07c3892017-06-08 18:19:25 +00007910 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007911 }
7912
7913 // Extension: We also add this operator for vector types.
7914 for (BuiltinCandidateTypeSet::iterator
7915 Vec = CandidateTypes[0].vector_begin(),
7916 VecEnd = CandidateTypes[0].vector_end();
7917 Vec != VecEnd; ++Vec) {
7918 QualType VecTy = *Vec;
George Burgess IVc07c3892017-06-08 18:19:25 +00007919 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007920 }
7921 }
7922
7923 // C++ [over.match.oper]p16:
Richard Smith5e9746f2016-10-21 22:00:42 +00007924 // For every pointer to member type T or type std::nullptr_t, there
7925 // exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007926 //
7927 // bool operator==(T,T);
7928 // bool operator!=(T,T);
Richard Smith5e9746f2016-10-21 22:00:42 +00007929 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007930 /// Set of (canonical) types that we've already handled.
7931 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7932
Richard Smithe54c3072013-05-05 15:51:06 +00007933 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007934 for (BuiltinCandidateTypeSet::iterator
7935 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7936 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7937 MemPtr != MemPtrEnd;
7938 ++MemPtr) {
7939 // Don't add the same builtin candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007940 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007941 continue;
7942
7943 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
George Burgess IVc07c3892017-06-08 18:19:25 +00007944 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007945 }
Richard Smith5e9746f2016-10-21 22:00:42 +00007946
7947 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7948 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7949 if (AddedTypes.insert(NullPtrTy).second) {
7950 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
George Burgess IVc07c3892017-06-08 18:19:25 +00007951 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Richard Smith5e9746f2016-10-21 22:00:42 +00007952 }
7953 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007954 }
7955 }
7956
7957 // C++ [over.built]p15:
7958 //
Richard Smith5e9746f2016-10-21 22:00:42 +00007959 // For every T, where T is an enumeration type or a pointer type,
7960 // there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007961 //
7962 // bool operator<(T, T);
7963 // bool operator>(T, T);
7964 // bool operator<=(T, T);
7965 // bool operator>=(T, T);
7966 // bool operator==(T, T);
7967 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007968 void addRelationalPointerOrEnumeralOverloads() {
Eli Friedman14f082b2012-09-18 21:52:24 +00007969 // C++ [over.match.oper]p3:
7970 // [...]the built-in candidates include all of the candidate operator
7971 // functions defined in 13.6 that, compared to the given operator, [...]
7972 // do not have the same parameter-type-list as any non-template non-member
7973 // candidate.
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007974 //
Eli Friedman14f082b2012-09-18 21:52:24 +00007975 // Note that in practice, this only affects enumeration types because there
7976 // aren't any built-in candidates of record type, and a user-defined operator
7977 // must have an operand of record or enumeration type. Also, the only other
7978 // overloaded operator with enumeration arguments, operator=,
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007979 // cannot be overloaded for enumeration types, so this is the only place
7980 // where we must suppress candidates like this.
7981 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7982 UserDefinedBinaryOperators;
7983
Richard Smithe54c3072013-05-05 15:51:06 +00007984 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007985 if (CandidateTypes[ArgIdx].enumeration_begin() !=
7986 CandidateTypes[ArgIdx].enumeration_end()) {
7987 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7988 CEnd = CandidateSet.end();
7989 C != CEnd; ++C) {
7990 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7991 continue;
7992
Eli Friedman14f082b2012-09-18 21:52:24 +00007993 if (C->Function->isFunctionTemplateSpecialization())
7994 continue;
7995
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007996 QualType FirstParamType =
7997 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7998 QualType SecondParamType =
7999 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
8000
8001 // Skip if either parameter isn't of enumeral type.
8002 if (!FirstParamType->isEnumeralType() ||
8003 !SecondParamType->isEnumeralType())
8004 continue;
8005
8006 // Add this operator to the set of known user-defined operators.
8007 UserDefinedBinaryOperators.insert(
8008 std::make_pair(S.Context.getCanonicalType(FirstParamType),
8009 S.Context.getCanonicalType(SecondParamType)));
8010 }
8011 }
8012 }
8013
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008014 /// Set of (canonical) types that we've already handled.
8015 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8016
Richard Smithe54c3072013-05-05 15:51:06 +00008017 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008018 for (BuiltinCandidateTypeSet::iterator
8019 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8020 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8021 Ptr != PtrEnd; ++Ptr) {
8022 // Don't add the same builtin candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00008023 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008024 continue;
8025
8026 QualType ParamTypes[2] = { *Ptr, *Ptr };
George Burgess IVc07c3892017-06-08 18:19:25 +00008027 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008028 }
8029 for (BuiltinCandidateTypeSet::iterator
8030 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8031 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8032 Enum != EnumEnd; ++Enum) {
8033 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
8034
Chandler Carruthc02db8c2010-12-12 09:14:11 +00008035 // Don't add the same builtin candidate twice, or if a user defined
8036 // candidate exists.
David Blaikie82e95a32014-11-19 07:49:47 +00008037 if (!AddedTypes.insert(CanonType).second ||
Chandler Carruthc02db8c2010-12-12 09:14:11 +00008038 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
8039 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008040 continue;
8041
8042 QualType ParamTypes[2] = { *Enum, *Enum };
George Burgess IVc07c3892017-06-08 18:19:25 +00008043 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008044 }
8045 }
8046 }
8047
8048 // C++ [over.built]p13:
8049 //
8050 // For every cv-qualified or cv-unqualified object type T
8051 // there exist candidate operator functions of the form
8052 //
8053 // T* operator+(T*, ptrdiff_t);
8054 // T& operator[](T*, ptrdiff_t); [BELOW]
8055 // T* operator-(T*, ptrdiff_t);
8056 // T* operator+(ptrdiff_t, T*);
8057 // T& operator[](ptrdiff_t, T*); [BELOW]
8058 //
8059 // C++ [over.built]p14:
8060 //
8061 // For every T, where T is a pointer to object type, there
8062 // exist candidate operator functions of the form
8063 //
8064 // ptrdiff_t operator-(T, T);
8065 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
8066 /// Set of (canonical) types that we've already handled.
8067 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8068
8069 for (int Arg = 0; Arg < 2; ++Arg) {
Eric Christopher9207a522015-08-21 16:24:01 +00008070 QualType AsymmetricParamTypes[2] = {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008071 S.Context.getPointerDiffType(),
8072 S.Context.getPointerDiffType(),
8073 };
8074 for (BuiltinCandidateTypeSet::iterator
8075 Ptr = CandidateTypes[Arg].pointer_begin(),
8076 PtrEnd = CandidateTypes[Arg].pointer_end();
8077 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00008078 QualType PointeeTy = (*Ptr)->getPointeeType();
8079 if (!PointeeTy->isObjectType())
8080 continue;
8081
Eric Christopher9207a522015-08-21 16:24:01 +00008082 AsymmetricParamTypes[Arg] = *Ptr;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008083 if (Arg == 0 || Op == OO_Plus) {
8084 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
8085 // T* operator+(ptrdiff_t, T*);
George Burgess IVc07c3892017-06-08 18:19:25 +00008086 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008087 }
8088 if (Op == OO_Minus) {
8089 // ptrdiff_t operator-(T, T);
David Blaikie82e95a32014-11-19 07:49:47 +00008090 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008091 continue;
8092
8093 QualType ParamTypes[2] = { *Ptr, *Ptr };
George Burgess IVc07c3892017-06-08 18:19:25 +00008094 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008095 }
8096 }
8097 }
8098 }
8099
8100 // C++ [over.built]p12:
8101 //
8102 // For every pair of promoted arithmetic types L and R, there
8103 // exist candidate operator functions of the form
8104 //
8105 // LR operator*(L, R);
8106 // LR operator/(L, R);
8107 // LR operator+(L, R);
8108 // LR operator-(L, R);
8109 // bool operator<(L, R);
8110 // bool operator>(L, R);
8111 // bool operator<=(L, R);
8112 // bool operator>=(L, R);
8113 // bool operator==(L, R);
8114 // bool operator!=(L, R);
8115 //
8116 // where LR is the result of the usual arithmetic conversions
8117 // between types L and R.
8118 //
8119 // C++ [over.built]p24:
8120 //
8121 // For every pair of promoted arithmetic types L and R, there exist
8122 // candidate operator functions of the form
8123 //
8124 // LR operator?(bool, L, R);
8125 //
8126 // where LR is the result of the usual arithmetic conversions
8127 // between types L and R.
8128 // Our candidates ignore the first parameter.
George Burgess IVc07c3892017-06-08 18:19:25 +00008129 void addGenericBinaryArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00008130 if (!HasArithmeticOrEnumeralCandidateType)
8131 return;
8132
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008133 for (unsigned Left = FirstPromotedArithmeticType;
8134 Left < LastPromotedArithmeticType; ++Left) {
8135 for (unsigned Right = FirstPromotedArithmeticType;
8136 Right < LastPromotedArithmeticType; ++Right) {
Hans Wennborg82371412017-11-15 17:11:53 +00008137 QualType LandR[2] = { ArithmeticTypes[Left],
8138 ArithmeticTypes[Right] };
George Burgess IVc07c3892017-06-08 18:19:25 +00008139 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008140 }
8141 }
8142
8143 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
8144 // conditional operator for vector types.
8145 for (BuiltinCandidateTypeSet::iterator
8146 Vec1 = CandidateTypes[0].vector_begin(),
8147 Vec1End = CandidateTypes[0].vector_end();
8148 Vec1 != Vec1End; ++Vec1) {
8149 for (BuiltinCandidateTypeSet::iterator
8150 Vec2 = CandidateTypes[1].vector_begin(),
8151 Vec2End = CandidateTypes[1].vector_end();
8152 Vec2 != Vec2End; ++Vec2) {
8153 QualType LandR[2] = { *Vec1, *Vec2 };
George Burgess IVc07c3892017-06-08 18:19:25 +00008154 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008155 }
8156 }
8157 }
8158
8159 // C++ [over.built]p17:
8160 //
8161 // For every pair of promoted integral types L and R, there
8162 // exist candidate operator functions of the form
8163 //
8164 // LR operator%(L, R);
8165 // LR operator&(L, R);
8166 // LR operator^(L, R);
8167 // LR operator|(L, R);
8168 // L operator<<(L, R);
8169 // L operator>>(L, R);
8170 //
8171 // where LR is the result of the usual arithmetic conversions
8172 // between types L and R.
8173 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00008174 if (!HasArithmeticOrEnumeralCandidateType)
8175 return;
8176
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008177 for (unsigned Left = FirstPromotedIntegralType;
8178 Left < LastPromotedIntegralType; ++Left) {
8179 for (unsigned Right = FirstPromotedIntegralType;
8180 Right < LastPromotedIntegralType; ++Right) {
Hans Wennborg82371412017-11-15 17:11:53 +00008181 QualType LandR[2] = { ArithmeticTypes[Left],
8182 ArithmeticTypes[Right] };
George Burgess IVc07c3892017-06-08 18:19:25 +00008183 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008184 }
8185 }
8186 }
8187
8188 // C++ [over.built]p20:
8189 //
8190 // For every pair (T, VQ), where T is an enumeration or
8191 // pointer to member type and VQ is either volatile or
8192 // empty, there exist candidate operator functions of the form
8193 //
8194 // VQ T& operator=(VQ T&, T);
8195 void addAssignmentMemberPointerOrEnumeralOverloads() {
8196 /// Set of (canonical) types that we've already handled.
8197 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8198
8199 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8200 for (BuiltinCandidateTypeSet::iterator
8201 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8202 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8203 Enum != EnumEnd; ++Enum) {
David Blaikie82e95a32014-11-19 07:49:47 +00008204 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008205 continue;
8206
Richard Smithe54c3072013-05-05 15:51:06 +00008207 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008208 }
8209
8210 for (BuiltinCandidateTypeSet::iterator
8211 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8212 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8213 MemPtr != MemPtrEnd; ++MemPtr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008214 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008215 continue;
8216
Richard Smithe54c3072013-05-05 15:51:06 +00008217 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008218 }
8219 }
8220 }
8221
8222 // C++ [over.built]p19:
8223 //
8224 // For every pair (T, VQ), where T is any type and VQ is either
8225 // volatile or empty, there exist candidate operator functions
8226 // of the form
8227 //
8228 // T*VQ& operator=(T*VQ&, T*);
8229 //
8230 // C++ [over.built]p21:
8231 //
8232 // For every pair (T, VQ), where T is a cv-qualified or
8233 // cv-unqualified object type and VQ is either volatile or
8234 // empty, there exist candidate operator functions of the form
8235 //
8236 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
8237 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
8238 void addAssignmentPointerOverloads(bool isEqualOp) {
8239 /// Set of (canonical) types that we've already handled.
8240 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8241
8242 for (BuiltinCandidateTypeSet::iterator
8243 Ptr = CandidateTypes[0].pointer_begin(),
8244 PtrEnd = CandidateTypes[0].pointer_end();
8245 Ptr != PtrEnd; ++Ptr) {
8246 // If this is operator=, keep track of the builtin candidates we added.
8247 if (isEqualOp)
8248 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00008249 else if (!(*Ptr)->getPointeeType()->isObjectType())
8250 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008251
8252 // non-volatile version
8253 QualType ParamTypes[2] = {
8254 S.Context.getLValueReferenceType(*Ptr),
8255 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
8256 };
George Burgess IVc07c3892017-06-08 18:19:25 +00008257 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008258 /*IsAssigmentOperator=*/ isEqualOp);
8259
Douglas Gregor5bee2582012-06-04 00:15:09 +00008260 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8261 VisibleTypeConversionsQuals.hasVolatile();
8262 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008263 // volatile version
8264 ParamTypes[0] =
8265 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
George Burgess IVc07c3892017-06-08 18:19:25 +00008266 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008267 /*IsAssigmentOperator=*/isEqualOp);
8268 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00008269
Douglas Gregor5bee2582012-06-04 00:15:09 +00008270 if (!(*Ptr).isRestrictQualified() &&
8271 VisibleTypeConversionsQuals.hasRestrict()) {
8272 // restrict version
8273 ParamTypes[0]
8274 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
George Burgess IVc07c3892017-06-08 18:19:25 +00008275 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00008276 /*IsAssigmentOperator=*/isEqualOp);
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00008277
Douglas Gregor5bee2582012-06-04 00:15:09 +00008278 if (NeedVolatile) {
8279 // volatile restrict version
8280 ParamTypes[0]
8281 = S.Context.getLValueReferenceType(
8282 S.Context.getCVRQualifiedType(*Ptr,
8283 (Qualifiers::Volatile |
8284 Qualifiers::Restrict)));
George Burgess IVc07c3892017-06-08 18:19:25 +00008285 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00008286 /*IsAssigmentOperator=*/isEqualOp);
8287 }
8288 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008289 }
8290
8291 if (isEqualOp) {
8292 for (BuiltinCandidateTypeSet::iterator
8293 Ptr = CandidateTypes[1].pointer_begin(),
8294 PtrEnd = CandidateTypes[1].pointer_end();
8295 Ptr != PtrEnd; ++Ptr) {
8296 // Make sure we don't add the same candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00008297 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008298 continue;
8299
Chandler Carruth8e543b32010-12-12 08:17:55 +00008300 QualType ParamTypes[2] = {
8301 S.Context.getLValueReferenceType(*Ptr),
8302 *Ptr,
8303 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008304
8305 // non-volatile version
George Burgess IVc07c3892017-06-08 18:19:25 +00008306 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008307 /*IsAssigmentOperator=*/true);
8308
Douglas Gregor5bee2582012-06-04 00:15:09 +00008309 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8310 VisibleTypeConversionsQuals.hasVolatile();
8311 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008312 // volatile version
8313 ParamTypes[0] =
8314 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
George Burgess IVc07c3892017-06-08 18:19:25 +00008315 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Richard Smithe54c3072013-05-05 15:51:06 +00008316 /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008317 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00008318
Douglas Gregor5bee2582012-06-04 00:15:09 +00008319 if (!(*Ptr).isRestrictQualified() &&
8320 VisibleTypeConversionsQuals.hasRestrict()) {
8321 // restrict version
8322 ParamTypes[0]
8323 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
George Burgess IVc07c3892017-06-08 18:19:25 +00008324 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Richard Smithe54c3072013-05-05 15:51:06 +00008325 /*IsAssigmentOperator=*/true);
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00008326
Douglas Gregor5bee2582012-06-04 00:15:09 +00008327 if (NeedVolatile) {
8328 // volatile restrict version
8329 ParamTypes[0]
8330 = S.Context.getLValueReferenceType(
8331 S.Context.getCVRQualifiedType(*Ptr,
8332 (Qualifiers::Volatile |
8333 Qualifiers::Restrict)));
George Burgess IVc07c3892017-06-08 18:19:25 +00008334 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Richard Smithe54c3072013-05-05 15:51:06 +00008335 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00008336 }
8337 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008338 }
8339 }
8340 }
8341
8342 // C++ [over.built]p18:
8343 //
8344 // For every triple (L, VQ, R), where L is an arithmetic type,
8345 // VQ is either volatile or empty, and R is a promoted
8346 // arithmetic type, there exist candidate operator functions of
8347 // the form
8348 //
8349 // VQ L& operator=(VQ L&, R);
8350 // VQ L& operator*=(VQ L&, R);
8351 // VQ L& operator/=(VQ L&, R);
8352 // VQ L& operator+=(VQ L&, R);
8353 // VQ L& operator-=(VQ L&, R);
8354 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00008355 if (!HasArithmeticOrEnumeralCandidateType)
8356 return;
8357
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008358 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
8359 for (unsigned Right = FirstPromotedArithmeticType;
8360 Right < LastPromotedArithmeticType; ++Right) {
8361 QualType ParamTypes[2];
Hans Wennborg82371412017-11-15 17:11:53 +00008362 ParamTypes[1] = ArithmeticTypes[Right];
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008363
8364 // Add this built-in operator as a candidate (VQ is empty).
8365 ParamTypes[0] =
Hans Wennborg82371412017-11-15 17:11:53 +00008366 S.Context.getLValueReferenceType(ArithmeticTypes[Left]);
George Burgess IVc07c3892017-06-08 18:19:25 +00008367 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008368 /*IsAssigmentOperator=*/isEqualOp);
8369
8370 // Add this built-in operator as a candidate (VQ is 'volatile').
8371 if (VisibleTypeConversionsQuals.hasVolatile()) {
8372 ParamTypes[0] =
Hans Wennborg82371412017-11-15 17:11:53 +00008373 S.Context.getVolatileType(ArithmeticTypes[Left]);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008374 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
George Burgess IVc07c3892017-06-08 18:19:25 +00008375 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008376 /*IsAssigmentOperator=*/isEqualOp);
8377 }
8378 }
8379 }
8380
8381 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8382 for (BuiltinCandidateTypeSet::iterator
8383 Vec1 = CandidateTypes[0].vector_begin(),
8384 Vec1End = CandidateTypes[0].vector_end();
8385 Vec1 != Vec1End; ++Vec1) {
8386 for (BuiltinCandidateTypeSet::iterator
8387 Vec2 = CandidateTypes[1].vector_begin(),
8388 Vec2End = CandidateTypes[1].vector_end();
8389 Vec2 != Vec2End; ++Vec2) {
8390 QualType ParamTypes[2];
8391 ParamTypes[1] = *Vec2;
8392 // Add this built-in operator as a candidate (VQ is empty).
8393 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
George Burgess IVc07c3892017-06-08 18:19:25 +00008394 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008395 /*IsAssigmentOperator=*/isEqualOp);
8396
8397 // Add this built-in operator as a candidate (VQ is 'volatile').
8398 if (VisibleTypeConversionsQuals.hasVolatile()) {
8399 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
8400 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
George Burgess IVc07c3892017-06-08 18:19:25 +00008401 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008402 /*IsAssigmentOperator=*/isEqualOp);
8403 }
8404 }
8405 }
8406 }
8407
8408 // C++ [over.built]p22:
8409 //
8410 // For every triple (L, VQ, R), where L is an integral type, VQ
8411 // is either volatile or empty, and R is a promoted integral
8412 // type, there exist candidate operator functions of the form
8413 //
8414 // VQ L& operator%=(VQ L&, R);
8415 // VQ L& operator<<=(VQ L&, R);
8416 // VQ L& operator>>=(VQ L&, R);
8417 // VQ L& operator&=(VQ L&, R);
8418 // VQ L& operator^=(VQ L&, R);
8419 // VQ L& operator|=(VQ L&, R);
8420 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00008421 if (!HasArithmeticOrEnumeralCandidateType)
8422 return;
8423
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008424 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8425 for (unsigned Right = FirstPromotedIntegralType;
8426 Right < LastPromotedIntegralType; ++Right) {
8427 QualType ParamTypes[2];
Hans Wennborg82371412017-11-15 17:11:53 +00008428 ParamTypes[1] = ArithmeticTypes[Right];
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008429
8430 // Add this built-in operator as a candidate (VQ is empty).
8431 ParamTypes[0] =
Hans Wennborg82371412017-11-15 17:11:53 +00008432 S.Context.getLValueReferenceType(ArithmeticTypes[Left]);
George Burgess IVc07c3892017-06-08 18:19:25 +00008433 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008434 if (VisibleTypeConversionsQuals.hasVolatile()) {
8435 // Add this built-in operator as a candidate (VQ is 'volatile').
Hans Wennborg82371412017-11-15 17:11:53 +00008436 ParamTypes[0] = ArithmeticTypes[Left];
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008437 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8438 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
George Burgess IVc07c3892017-06-08 18:19:25 +00008439 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008440 }
8441 }
8442 }
8443 }
8444
8445 // C++ [over.operator]p23:
8446 //
8447 // There also exist candidate operator functions of the form
8448 //
8449 // bool operator!(bool);
8450 // bool operator&&(bool, bool);
8451 // bool operator||(bool, bool);
8452 void addExclaimOverload() {
8453 QualType ParamTy = S.Context.BoolTy;
George Burgess IVc07c3892017-06-08 18:19:25 +00008454 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008455 /*IsAssignmentOperator=*/false,
8456 /*NumContextualBoolArguments=*/1);
8457 }
8458 void addAmpAmpOrPipePipeOverload() {
8459 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
George Burgess IVc07c3892017-06-08 18:19:25 +00008460 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008461 /*IsAssignmentOperator=*/false,
8462 /*NumContextualBoolArguments=*/2);
8463 }
8464
8465 // C++ [over.built]p13:
8466 //
8467 // For every cv-qualified or cv-unqualified object type T there
8468 // exist candidate operator functions of the form
8469 //
8470 // T* operator+(T*, ptrdiff_t); [ABOVE]
8471 // T& operator[](T*, ptrdiff_t);
8472 // T* operator-(T*, ptrdiff_t); [ABOVE]
8473 // T* operator+(ptrdiff_t, T*); [ABOVE]
8474 // T& operator[](ptrdiff_t, T*);
8475 void addSubscriptOverloads() {
8476 for (BuiltinCandidateTypeSet::iterator
8477 Ptr = CandidateTypes[0].pointer_begin(),
8478 PtrEnd = CandidateTypes[0].pointer_end();
8479 Ptr != PtrEnd; ++Ptr) {
8480 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8481 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00008482 if (!PointeeType->isObjectType())
8483 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008484
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008485 // T& operator[](T*, ptrdiff_t)
George Burgess IVc07c3892017-06-08 18:19:25 +00008486 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008487 }
8488
8489 for (BuiltinCandidateTypeSet::iterator
8490 Ptr = CandidateTypes[1].pointer_begin(),
8491 PtrEnd = CandidateTypes[1].pointer_end();
8492 Ptr != PtrEnd; ++Ptr) {
8493 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8494 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00008495 if (!PointeeType->isObjectType())
8496 continue;
8497
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008498 // T& operator[](ptrdiff_t, T*)
George Burgess IVc07c3892017-06-08 18:19:25 +00008499 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008500 }
8501 }
8502
8503 // C++ [over.built]p11:
8504 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8505 // C1 is the same type as C2 or is a derived class of C2, T is an object
8506 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8507 // there exist candidate operator functions of the form
8508 //
8509 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8510 //
8511 // where CV12 is the union of CV1 and CV2.
8512 void addArrowStarOverloads() {
8513 for (BuiltinCandidateTypeSet::iterator
8514 Ptr = CandidateTypes[0].pointer_begin(),
8515 PtrEnd = CandidateTypes[0].pointer_end();
8516 Ptr != PtrEnd; ++Ptr) {
8517 QualType C1Ty = (*Ptr);
8518 QualType C1;
8519 QualifierCollector Q1;
8520 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8521 if (!isa<RecordType>(C1))
8522 continue;
8523 // heuristic to reduce number of builtin candidates in the set.
8524 // Add volatile/restrict version only if there are conversions to a
8525 // volatile/restrict type.
8526 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8527 continue;
8528 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8529 continue;
8530 for (BuiltinCandidateTypeSet::iterator
8531 MemPtr = CandidateTypes[1].member_pointer_begin(),
8532 MemPtrEnd = CandidateTypes[1].member_pointer_end();
8533 MemPtr != MemPtrEnd; ++MemPtr) {
8534 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8535 QualType C2 = QualType(mptr->getClass(), 0);
8536 C2 = C2.getUnqualifiedType();
Richard Smith0f59cb32015-12-18 21:45:41 +00008537 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008538 break;
8539 QualType ParamTypes[2] = { *Ptr, *MemPtr };
8540 // build CV12 T&
8541 QualType T = mptr->getPointeeType();
8542 if (!VisibleTypeConversionsQuals.hasVolatile() &&
8543 T.isVolatileQualified())
8544 continue;
8545 if (!VisibleTypeConversionsQuals.hasRestrict() &&
8546 T.isRestrictQualified())
8547 continue;
8548 T = Q1.apply(S.Context, T);
George Burgess IVc07c3892017-06-08 18:19:25 +00008549 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008550 }
8551 }
8552 }
8553
8554 // Note that we don't consider the first argument, since it has been
8555 // contextually converted to bool long ago. The candidates below are
8556 // therefore added as binary.
8557 //
8558 // C++ [over.built]p25:
8559 // For every type T, where T is a pointer, pointer-to-member, or scoped
8560 // enumeration type, there exist candidate operator functions of the form
8561 //
8562 // T operator?(bool, T, T);
8563 //
8564 void addConditionalOperatorOverloads() {
8565 /// Set of (canonical) types that we've already handled.
8566 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8567
8568 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8569 for (BuiltinCandidateTypeSet::iterator
8570 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8571 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8572 Ptr != PtrEnd; ++Ptr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008573 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008574 continue;
8575
8576 QualType ParamTypes[2] = { *Ptr, *Ptr };
George Burgess IVc07c3892017-06-08 18:19:25 +00008577 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008578 }
8579
8580 for (BuiltinCandidateTypeSet::iterator
8581 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8582 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8583 MemPtr != MemPtrEnd; ++MemPtr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008584 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008585 continue;
8586
8587 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
George Burgess IVc07c3892017-06-08 18:19:25 +00008588 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008589 }
8590
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008591 if (S.getLangOpts().CPlusPlus11) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008592 for (BuiltinCandidateTypeSet::iterator
8593 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8594 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8595 Enum != EnumEnd; ++Enum) {
8596 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8597 continue;
8598
David Blaikie82e95a32014-11-19 07:49:47 +00008599 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008600 continue;
8601
8602 QualType ParamTypes[2] = { *Enum, *Enum };
George Burgess IVc07c3892017-06-08 18:19:25 +00008603 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008604 }
8605 }
8606 }
8607 }
8608};
8609
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008610} // end anonymous namespace
8611
8612/// AddBuiltinOperatorCandidates - Add the appropriate built-in
8613/// operator overloads to the candidate set (C++ [over.built]), based
8614/// on the operator @p Op and the arguments given. For example, if the
8615/// operator is a binary '+', this routine might add "int
8616/// operator+(int, int)" to cover integer addition.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00008617void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8618 SourceLocation OpLoc,
8619 ArrayRef<Expr *> Args,
8620 OverloadCandidateSet &CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00008621 // Find all of the types that the arguments can convert to, but only
8622 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00008623 // that make use of these types. Also record whether we encounter non-record
8624 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00008625 Qualifiers VisibleTypeConversionsQuals;
8626 VisibleTypeConversionsQuals.addConst();
Richard Smithe54c3072013-05-05 15:51:06 +00008627 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00008628 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00008629
8630 bool HasNonRecordCandidateType = false;
8631 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008632 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Richard Smithe54c3072013-05-05 15:51:06 +00008633 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Benjamin Kramer57dddd482015-02-17 21:55:18 +00008634 CandidateTypes.emplace_back(*this);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00008635 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8636 OpLoc,
8637 true,
8638 (Op == OO_Exclaim ||
8639 Op == OO_AmpAmp ||
8640 Op == OO_PipePipe),
8641 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00008642 HasNonRecordCandidateType = HasNonRecordCandidateType ||
8643 CandidateTypes[ArgIdx].hasNonRecordTypes();
8644 HasArithmeticOrEnumeralCandidateType =
8645 HasArithmeticOrEnumeralCandidateType ||
8646 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00008647 }
Douglas Gregora11693b2008-11-12 17:17:38 +00008648
Chandler Carruth00a38332010-12-13 01:44:01 +00008649 // Exit early when no non-record types have been added to the candidate set
8650 // for any of the arguments to the operator.
Douglas Gregor877d4eb2011-10-10 14:05:31 +00008651 //
8652 // We can't exit early for !, ||, or &&, since there we have always have
8653 // 'bool' overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00008654 if (!HasNonRecordCandidateType &&
Douglas Gregor877d4eb2011-10-10 14:05:31 +00008655 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth00a38332010-12-13 01:44:01 +00008656 return;
8657
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008658 // Setup an object to manage the common state for building overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00008659 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008660 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00008661 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008662 CandidateTypes, CandidateSet);
8663
8664 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00008665 switch (Op) {
8666 case OO_None:
8667 case NUM_OVERLOADED_OPERATORS:
David Blaikie83d382b2011-09-23 05:06:16 +00008668 llvm_unreachable("Expected an overloaded operator");
Douglas Gregora11693b2008-11-12 17:17:38 +00008669
Chandler Carruth5184de02010-12-12 08:51:33 +00008670 case OO_New:
8671 case OO_Delete:
8672 case OO_Array_New:
8673 case OO_Array_Delete:
8674 case OO_Call:
David Blaikie83d382b2011-09-23 05:06:16 +00008675 llvm_unreachable(
8676 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruth5184de02010-12-12 08:51:33 +00008677
8678 case OO_Comma:
8679 case OO_Arrow:
Richard Smith9f690bd2015-10-27 06:02:45 +00008680 case OO_Coawait:
Chandler Carruth5184de02010-12-12 08:51:33 +00008681 // C++ [over.match.oper]p3:
Richard Smith9f690bd2015-10-27 06:02:45 +00008682 // -- For the operator ',', the unary operator '&', the
8683 // operator '->', or the operator 'co_await', the
8684 // built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00008685 break;
8686
8687 case OO_Plus: // '+' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008688 if (Args.size() == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008689 OpBuilder.addUnaryPlusPointerOverloads();
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00008690 LLVM_FALLTHROUGH;
Douglas Gregord08452f2008-11-19 15:42:04 +00008691
8692 case OO_Minus: // '-' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008693 if (Args.size() == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008694 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008695 } else {
8696 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
George Burgess IVc07c3892017-06-08 18:19:25 +00008697 OpBuilder.addGenericBinaryArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008698 }
Douglas Gregord08452f2008-11-19 15:42:04 +00008699 break;
8700
Chandler Carruth5184de02010-12-12 08:51:33 +00008701 case OO_Star: // '*' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008702 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008703 OpBuilder.addUnaryStarPointerOverloads();
8704 else
George Burgess IVc07c3892017-06-08 18:19:25 +00008705 OpBuilder.addGenericBinaryArithmeticOverloads();
Chandler Carruth5184de02010-12-12 08:51:33 +00008706 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008707
Chandler Carruth5184de02010-12-12 08:51:33 +00008708 case OO_Slash:
George Burgess IVc07c3892017-06-08 18:19:25 +00008709 OpBuilder.addGenericBinaryArithmeticOverloads();
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008710 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008711
8712 case OO_PlusPlus:
8713 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008714 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8715 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00008716 break;
8717
Douglas Gregor84605ae2009-08-24 13:43:27 +00008718 case OO_EqualEqual:
8719 case OO_ExclaimEqual:
Richard Smith5e9746f2016-10-21 22:00:42 +00008720 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00008721 LLVM_FALLTHROUGH;
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008722
Douglas Gregora11693b2008-11-12 17:17:38 +00008723 case OO_Less:
8724 case OO_Greater:
8725 case OO_LessEqual:
8726 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00008727 OpBuilder.addRelationalPointerOrEnumeralOverloads();
George Burgess IVc07c3892017-06-08 18:19:25 +00008728 OpBuilder.addGenericBinaryArithmeticOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00008729 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008730
Richard Smithd30b23d2017-12-01 02:13:10 +00008731 case OO_Spaceship:
8732 llvm_unreachable("<=> expressions not supported yet");
8733
Douglas Gregora11693b2008-11-12 17:17:38 +00008734 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00008735 case OO_Caret:
8736 case OO_Pipe:
8737 case OO_LessLess:
8738 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008739 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00008740 break;
8741
Chandler Carruth5184de02010-12-12 08:51:33 +00008742 case OO_Amp: // '&' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008743 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008744 // C++ [over.match.oper]p3:
8745 // -- For the operator ',', the unary operator '&', or the
8746 // operator '->', the built-in candidates set is empty.
8747 break;
8748
8749 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8750 break;
8751
8752 case OO_Tilde:
8753 OpBuilder.addUnaryTildePromotedIntegralOverloads();
8754 break;
8755
Douglas Gregora11693b2008-11-12 17:17:38 +00008756 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008757 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00008758 LLVM_FALLTHROUGH;
Douglas Gregora11693b2008-11-12 17:17:38 +00008759
8760 case OO_PlusEqual:
8761 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008762 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00008763 LLVM_FALLTHROUGH;
Douglas Gregora11693b2008-11-12 17:17:38 +00008764
8765 case OO_StarEqual:
8766 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008767 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008768 break;
8769
8770 case OO_PercentEqual:
8771 case OO_LessLessEqual:
8772 case OO_GreaterGreaterEqual:
8773 case OO_AmpEqual:
8774 case OO_CaretEqual:
8775 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008776 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008777 break;
8778
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008779 case OO_Exclaim:
8780 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00008781 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008782
Douglas Gregora11693b2008-11-12 17:17:38 +00008783 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008784 case OO_PipePipe:
8785 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00008786 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008787
8788 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008789 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008790 break;
8791
8792 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008793 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008794 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00008795
8796 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008797 OpBuilder.addConditionalOperatorOverloads();
George Burgess IVc07c3892017-06-08 18:19:25 +00008798 OpBuilder.addGenericBinaryArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008799 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008800 }
8801}
8802
Douglas Gregore254f902009-02-04 00:32:51 +00008803/// \brief Add function candidates found via argument-dependent lookup
8804/// to the set of overloading candidates.
8805///
8806/// This routine performs argument-dependent name lookup based on the
8807/// given function name (which may also be an operator name) and adds
8808/// all of the overload candidates found by ADL to the overload
8809/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00008810void
Douglas Gregore254f902009-02-04 00:32:51 +00008811Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smith100b24a2014-04-17 01:52:14 +00008812 SourceLocation Loc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008813 ArrayRef<Expr *> Args,
Douglas Gregor739b107a2011-03-03 02:41:12 +00008814 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008815 OverloadCandidateSet& CandidateSet,
Richard Smithb6626742012-10-18 17:56:02 +00008816 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00008817 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00008818
John McCall91f61fc2010-01-26 06:04:06 +00008819 // FIXME: This approach for uniquing ADL results (and removing
8820 // redundant candidates from the set) relies on pointer-equality,
8821 // which means we need to key off the canonical decl. However,
8822 // always going back to the canonical decl might not get us the
8823 // right set of default arguments. What default arguments are
8824 // we supposed to consider on ADL candidates, anyway?
8825
Douglas Gregorcabea402009-09-22 15:41:20 +00008826 // FIXME: Pass in the explicit template arguments?
Richard Smith100b24a2014-04-17 01:52:14 +00008827 ArgumentDependentLookup(Name, Loc, Args, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00008828
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008829 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008830 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8831 CandEnd = CandidateSet.end();
8832 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00008833 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00008834 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00008835 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00008836 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00008837 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008838
8839 // For each of the ADL candidates we found, add it to the overload
8840 // set.
John McCall8fe68082010-01-26 07:16:45 +00008841 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00008842 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00008843 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00008844 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00008845 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008846
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008847 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8848 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00008849 } else
John McCall4c4c1df2010-01-26 03:27:55 +00008850 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00008851 FoundDecl, ExplicitTemplateArgs,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00008852 Args, CandidateSet, PartialOverloading);
Douglas Gregor15448f82009-06-27 21:05:07 +00008853 }
Douglas Gregore254f902009-02-04 00:32:51 +00008854}
8855
George Burgess IV3dc166912016-05-10 01:59:34 +00008856namespace {
8857enum class Comparison { Equal, Better, Worse };
8858}
8859
8860/// Compares the enable_if attributes of two FunctionDecls, for the purposes of
8861/// overload resolution.
8862///
8863/// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
8864/// Cand1's first N enable_if attributes have precisely the same conditions as
8865/// Cand2's first N enable_if attributes (where N = the number of enable_if
8866/// attributes on Cand2), and Cand1 has more than N enable_if attributes.
8867///
8868/// Note that you can have a pair of candidates such that Cand1's enable_if
8869/// attributes are worse than Cand2's, and Cand2's enable_if attributes are
8870/// worse than Cand1's.
8871static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
8872 const FunctionDecl *Cand2) {
8873 // Common case: One (or both) decls don't have enable_if attrs.
8874 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
8875 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
8876 if (!Cand1Attr || !Cand2Attr) {
8877 if (Cand1Attr == Cand2Attr)
8878 return Comparison::Equal;
8879 return Cand1Attr ? Comparison::Better : Comparison::Worse;
8880 }
George Burgess IV2a6150d2015-10-16 01:17:38 +00008881
8882 // FIXME: The next several lines are just
8883 // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8884 // instead of reverse order which is how they're stored in the AST.
8885 auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1);
8886 auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2);
8887
George Burgess IV3dc166912016-05-10 01:59:34 +00008888 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
8889 // has fewer enable_if attributes than Cand2.
8890 if (Cand1Attrs.size() < Cand2Attrs.size())
8891 return Comparison::Worse;
George Burgess IV2a6150d2015-10-16 01:17:38 +00008892
8893 auto Cand1I = Cand1Attrs.begin();
8894 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
8895 for (auto &Cand2A : Cand2Attrs) {
8896 Cand1ID.clear();
8897 Cand2ID.clear();
8898
8899 auto &Cand1A = *Cand1I++;
8900 Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true);
8901 Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true);
8902 if (Cand1ID != Cand2ID)
George Burgess IV3dc166912016-05-10 01:59:34 +00008903 return Comparison::Worse;
George Burgess IV2a6150d2015-10-16 01:17:38 +00008904 }
8905
George Burgess IV3dc166912016-05-10 01:59:34 +00008906 return Cand1I == Cand1Attrs.end() ? Comparison::Equal : Comparison::Better;
George Burgess IV2a6150d2015-10-16 01:17:38 +00008907}
8908
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008909/// isBetterOverloadCandidate - Determines whether the first overload
8910/// candidate is a better candidate than the second (C++ 13.3.3p1).
Richard Smith67ef14f2017-09-26 18:37:55 +00008911bool clang::isBetterOverloadCandidate(
8912 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
8913 SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008914 // Define viable functions to be better candidates than non-viable
8915 // functions.
8916 if (!Cand2.Viable)
8917 return Cand1.Viable;
8918 else if (!Cand1.Viable)
8919 return false;
8920
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008921 // C++ [over.match.best]p1:
8922 //
8923 // -- if F is a static member function, ICS1(F) is defined such
8924 // that ICS1(F) is neither better nor worse than ICS1(G) for
8925 // any function G, and, symmetrically, ICS1(G) is neither
8926 // better nor worse than ICS1(F).
8927 unsigned StartArg = 0;
8928 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8929 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008930
George Burgess IVfbad5b22016-09-07 20:03:19 +00008931 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
8932 // We don't allow incompatible pointer conversions in C++.
8933 if (!S.getLangOpts().CPlusPlus)
8934 return ICS.isStandard() &&
8935 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
8936
8937 // The only ill-formed conversion we allow in C++ is the string literal to
8938 // char* conversion, which is only considered ill-formed after C++11.
8939 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
8940 hasDeprecatedStringLiteralToCharPtrConversion(ICS);
8941 };
8942
8943 // Define functions that don't require ill-formed conversions for a given
8944 // argument to be better candidates than functions that do.
Richard Smith6eedfe72017-01-09 08:01:21 +00008945 unsigned NumArgs = Cand1.Conversions.size();
8946 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
George Burgess IVfbad5b22016-09-07 20:03:19 +00008947 bool HasBetterConversion = false;
8948 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
8949 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
8950 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
8951 if (Cand1Bad != Cand2Bad) {
8952 if (Cand1Bad)
8953 return false;
8954 HasBetterConversion = true;
8955 }
8956 }
8957
8958 if (HasBetterConversion)
8959 return true;
8960
Douglas Gregord3cb3562009-07-07 23:38:56 +00008961 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00008962 // A viable function F1 is defined to be a better function than another
8963 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00008964 // conversion sequence than ICSi(F2), and then...
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008965 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Richard Smith0f59cb32015-12-18 21:45:41 +00008966 switch (CompareImplicitConversionSequences(S, Loc,
John McCall5c32be02010-08-24 20:38:10 +00008967 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008968 Cand2.Conversions[ArgIdx])) {
8969 case ImplicitConversionSequence::Better:
8970 // Cand1 has a better conversion sequence.
8971 HasBetterConversion = true;
8972 break;
8973
8974 case ImplicitConversionSequence::Worse:
8975 // Cand1 can't be better than Cand2.
8976 return false;
8977
8978 case ImplicitConversionSequence::Indistinguishable:
8979 // Do nothing.
8980 break;
8981 }
8982 }
8983
Mike Stump11289f42009-09-09 15:08:12 +00008984 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00008985 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008986 if (HasBetterConversion)
8987 return true;
8988
Douglas Gregora1f013e2008-11-07 22:36:19 +00008989 // -- the context is an initialization by user-defined conversion
8990 // (see 8.5, 13.3.1.5) and the standard conversion sequence
8991 // from the return type of F1 to the destination type (i.e.,
8992 // the type of the entity being initialized) is a better
8993 // conversion sequence than the standard conversion sequence
8994 // from the return type of F2 to the destination type.
Richard Smith67ef14f2017-09-26 18:37:55 +00008995 if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
8996 Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00008997 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00008998 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregor2837aa22012-02-22 17:32:19 +00008999 // First check whether we prefer one of the conversion functions over the
9000 // other. This only distinguishes the results in non-standard, extension
9001 // cases such as the conversion from a lambda closure type to a function
9002 // pointer or block.
Richard Smithec2748a2014-05-17 04:36:39 +00009003 ImplicitConversionSequence::CompareKind Result =
9004 compareConversionFunctions(S, Cand1.Function, Cand2.Function);
9005 if (Result == ImplicitConversionSequence::Indistinguishable)
Richard Smith0f59cb32015-12-18 21:45:41 +00009006 Result = CompareStandardConversionSequences(S, Loc,
Richard Smithec2748a2014-05-17 04:36:39 +00009007 Cand1.FinalConversion,
9008 Cand2.FinalConversion);
Richard Smith6fdeaab2014-05-17 01:58:45 +00009009
Richard Smithec2748a2014-05-17 04:36:39 +00009010 if (Result != ImplicitConversionSequence::Indistinguishable)
9011 return Result == ImplicitConversionSequence::Better;
Richard Smith6fdeaab2014-05-17 01:58:45 +00009012
9013 // FIXME: Compare kind of reference binding if conversion functions
9014 // convert to a reference type used in direct reference binding, per
9015 // C++14 [over.match.best]p1 section 2 bullet 3.
9016 }
9017
Richard Smith51731362017-11-01 01:37:11 +00009018 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
9019 // as combined with the resolution to CWG issue 243.
9020 //
9021 // When the context is initialization by constructor ([over.match.ctor] or
9022 // either phase of [over.match.list]), a constructor is preferred over
9023 // a conversion function.
9024 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
9025 Cand1.Function && Cand2.Function &&
9026 isa<CXXConstructorDecl>(Cand1.Function) !=
9027 isa<CXXConstructorDecl>(Cand2.Function))
9028 return isa<CXXConstructorDecl>(Cand1.Function);
9029
Richard Smith6fdeaab2014-05-17 01:58:45 +00009030 // -- F1 is a non-template function and F2 is a function template
9031 // specialization, or, if not that,
9032 bool Cand1IsSpecialization = Cand1.Function &&
9033 Cand1.Function->getPrimaryTemplate();
9034 bool Cand2IsSpecialization = Cand2.Function &&
9035 Cand2.Function->getPrimaryTemplate();
9036 if (Cand1IsSpecialization != Cand2IsSpecialization)
9037 return Cand2IsSpecialization;
9038
9039 // -- F1 and F2 are function template specializations, and the function
9040 // template for F1 is more specialized than the template for F2
9041 // according to the partial ordering rules described in 14.5.5.2, or,
9042 // if not that,
9043 if (Cand1IsSpecialization && Cand2IsSpecialization) {
9044 if (FunctionTemplateDecl *BetterTemplate
9045 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
9046 Cand2.Function->getPrimaryTemplate(),
9047 Loc,
9048 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
9049 : TPOC_Call,
9050 Cand1.ExplicitCallArguments,
9051 Cand2.ExplicitCallArguments))
9052 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregora1f013e2008-11-07 22:36:19 +00009053 }
9054
Richard Smith5179eb72016-06-28 19:03:57 +00009055 // FIXME: Work around a defect in the C++17 inheriting constructor wording.
9056 // A derived-class constructor beats an (inherited) base class constructor.
9057 bool Cand1IsInherited =
9058 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
9059 bool Cand2IsInherited =
9060 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
9061 if (Cand1IsInherited != Cand2IsInherited)
9062 return Cand2IsInherited;
9063 else if (Cand1IsInherited) {
9064 assert(Cand2IsInherited);
9065 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
9066 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
9067 if (Cand1Class->isDerivedFrom(Cand2Class))
9068 return true;
9069 if (Cand2Class->isDerivedFrom(Cand1Class))
9070 return false;
9071 // Inherited from sibling base classes: still ambiguous.
9072 }
9073
Faisal Vali81b756e2017-10-22 14:45:08 +00009074 // Check C++17 tie-breakers for deduction guides.
9075 {
9076 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
9077 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
9078 if (Guide1 && Guide2) {
9079 // -- F1 is generated from a deduction-guide and F2 is not
9080 if (Guide1->isImplicit() != Guide2->isImplicit())
9081 return Guide2->isImplicit();
9082
9083 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
9084 if (Guide1->isCopyDeductionCandidate())
9085 return true;
9086 }
9087 }
Richard Smith67ef14f2017-09-26 18:37:55 +00009088
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009089 // Check for enable_if value-based overload resolution.
George Burgess IV3dc166912016-05-10 01:59:34 +00009090 if (Cand1.Function && Cand2.Function) {
9091 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
9092 if (Cmp != Comparison::Equal)
9093 return Cmp == Comparison::Better;
9094 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009095
Justin Lebar25c4a812016-03-29 16:24:16 +00009096 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
Artem Belevich94a55e82015-09-22 17:22:59 +00009097 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9098 return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
9099 S.IdentifyCUDAPreference(Caller, Cand2.Function);
9100 }
9101
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009102 bool HasPS1 = Cand1.Function != nullptr &&
9103 functionHasPassObjectSizeParams(Cand1.Function);
9104 bool HasPS2 = Cand2.Function != nullptr &&
9105 functionHasPassObjectSizeParams(Cand2.Function);
9106 return HasPS1 != HasPS2 && HasPS1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009107}
9108
Richard Smith2dbe4042015-11-04 19:26:32 +00009109/// Determine whether two declarations are "equivalent" for the purposes of
Richard Smith26210db2015-11-13 03:52:13 +00009110/// name lookup and overload resolution. This applies when the same internal/no
9111/// linkage entity is defined by two modules (probably by textually including
Richard Smith2dbe4042015-11-04 19:26:32 +00009112/// the same header). In such a case, we don't consider the declarations to
9113/// declare the same entity, but we also don't want lookups with both
9114/// declarations visible to be ambiguous in some cases (this happens when using
9115/// a modularized libstdc++).
9116bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
9117 const NamedDecl *B) {
Richard Smith26210db2015-11-13 03:52:13 +00009118 auto *VA = dyn_cast_or_null<ValueDecl>(A);
9119 auto *VB = dyn_cast_or_null<ValueDecl>(B);
9120 if (!VA || !VB)
9121 return false;
9122
9123 // The declarations must be declaring the same name as an internal linkage
9124 // entity in different modules.
9125 if (!VA->getDeclContext()->getRedeclContext()->Equals(
9126 VB->getDeclContext()->getRedeclContext()) ||
9127 getOwningModule(const_cast<ValueDecl *>(VA)) ==
9128 getOwningModule(const_cast<ValueDecl *>(VB)) ||
9129 VA->isExternallyVisible() || VB->isExternallyVisible())
9130 return false;
9131
9132 // Check that the declarations appear to be equivalent.
9133 //
9134 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
9135 // For constants and functions, we should check the initializer or body is
9136 // the same. For non-constant variables, we shouldn't allow it at all.
9137 if (Context.hasSameType(VA->getType(), VB->getType()))
9138 return true;
9139
9140 // Enum constants within unnamed enumerations will have different types, but
9141 // may still be similar enough to be interchangeable for our purposes.
9142 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
9143 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
9144 // Only handle anonymous enums. If the enumerations were named and
9145 // equivalent, they would have been merged to the same type.
9146 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
9147 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
9148 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
9149 !Context.hasSameType(EnumA->getIntegerType(),
9150 EnumB->getIntegerType()))
9151 return false;
9152 // Allow this only if the value is the same for both enumerators.
9153 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
9154 }
9155 }
9156
9157 // Nothing else is sufficiently similar.
9158 return false;
Richard Smith2dbe4042015-11-04 19:26:32 +00009159}
9160
9161void Sema::diagnoseEquivalentInternalLinkageDeclarations(
9162 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
9163 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
9164
9165 Module *M = getOwningModule(const_cast<NamedDecl*>(D));
9166 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
9167 << !M << (M ? M->getFullModuleName() : "");
9168
9169 for (auto *E : Equiv) {
9170 Module *M = getOwningModule(const_cast<NamedDecl*>(E));
9171 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
9172 << !M << (M ? M->getFullModuleName() : "");
9173 }
Richard Smith896c66e2015-10-21 07:13:52 +00009174}
9175
Mike Stump11289f42009-09-09 15:08:12 +00009176/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009177/// within an overload candidate set.
9178///
James Dennettffad8b72012-06-22 08:10:18 +00009179/// \param Loc The location of the function name (or operator symbol) for
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009180/// which overload resolution occurs.
9181///
James Dennettffad8b72012-06-22 08:10:18 +00009182/// \param Best If overload resolution was successful or found a deleted
9183/// function, \p Best points to the candidate function found.
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009184///
9185/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00009186OverloadingResult
9187OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Richard Smith67ef14f2017-09-26 18:37:55 +00009188 iterator &Best) {
Artem Belevich18609102016-02-12 18:29:18 +00009189 llvm::SmallVector<OverloadCandidate *, 16> Candidates;
9190 std::transform(begin(), end(), std::back_inserter(Candidates),
9191 [](OverloadCandidate &Cand) { return &Cand; });
9192
Justin Lebar66a2ab92016-08-10 00:40:43 +00009193 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
9194 // are accepted by both clang and NVCC. However, during a particular
Artem Belevich18609102016-02-12 18:29:18 +00009195 // compilation mode only one call variant is viable. We need to
9196 // exclude non-viable overload candidates from consideration based
9197 // only on their host/device attributes. Specifically, if one
9198 // candidate call is WrongSide and the other is SameSide, we ignore
9199 // the WrongSide candidate.
Justin Lebar25c4a812016-03-29 16:24:16 +00009200 if (S.getLangOpts().CUDA) {
Artem Belevich18609102016-02-12 18:29:18 +00009201 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9202 bool ContainsSameSideCandidate =
9203 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
9204 return Cand->Function &&
9205 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9206 Sema::CFP_SameSide;
9207 });
9208 if (ContainsSameSideCandidate) {
9209 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
9210 return Cand->Function &&
9211 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9212 Sema::CFP_WrongSide;
9213 };
George Burgess IV8684b032017-01-04 19:16:29 +00009214 llvm::erase_if(Candidates, IsWrongSideCandidate);
Artem Belevich18609102016-02-12 18:29:18 +00009215 }
9216 }
9217
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009218 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00009219 Best = end();
Artem Belevich18609102016-02-12 18:29:18 +00009220 for (auto *Cand : Candidates)
John McCall5c32be02010-08-24 20:38:10 +00009221 if (Cand->Viable)
Richard Smith67ef14f2017-09-26 18:37:55 +00009222 if (Best == end() ||
9223 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009224 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009225
9226 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00009227 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009228 return OR_No_Viable_Function;
9229
Richard Smith2dbe4042015-11-04 19:26:32 +00009230 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
Richard Smith896c66e2015-10-21 07:13:52 +00009231
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009232 // Make sure that this function is better than every other viable
9233 // function. If not, we have an ambiguity.
Artem Belevich18609102016-02-12 18:29:18 +00009234 for (auto *Cand : Candidates) {
Richard Smith67ef14f2017-09-26 18:37:55 +00009235 if (Cand->Viable && Cand != Best &&
9236 !isBetterOverloadCandidate(S, *Best, *Cand, Loc, Kind)) {
Richard Smith2dbe4042015-11-04 19:26:32 +00009237 if (S.isEquivalentInternalLinkageDeclaration(Best->Function,
9238 Cand->Function)) {
9239 EquivalentCands.push_back(Cand->Function);
Richard Smith896c66e2015-10-21 07:13:52 +00009240 continue;
9241 }
9242
John McCall5c32be02010-08-24 20:38:10 +00009243 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009244 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00009245 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009246 }
Mike Stump11289f42009-09-09 15:08:12 +00009247
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009248 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00009249 if (Best->Function &&
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00009250 (Best->Function->isDeleted() ||
George Burgess IVce6284b2017-01-28 02:19:40 +00009251 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor171c45a2009-02-18 21:56:37 +00009252 return OR_Deleted;
9253
Richard Smith2dbe4042015-11-04 19:26:32 +00009254 if (!EquivalentCands.empty())
9255 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
9256 EquivalentCands);
Richard Smith896c66e2015-10-21 07:13:52 +00009257
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009258 return OR_Success;
9259}
9260
John McCall53262c92010-01-12 02:15:36 +00009261namespace {
9262
9263enum OverloadCandidateKind {
9264 oc_function,
9265 oc_method,
9266 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00009267 oc_function_template,
9268 oc_method_template,
9269 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00009270 oc_implicit_default_constructor,
9271 oc_implicit_copy_constructor,
Alexis Hunt119c10e2011-05-25 23:16:36 +00009272 oc_implicit_move_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00009273 oc_implicit_copy_assignment,
Alexis Hunt119c10e2011-05-25 23:16:36 +00009274 oc_implicit_move_assignment,
Richard Smith5179eb72016-06-28 19:03:57 +00009275 oc_inherited_constructor,
9276 oc_inherited_constructor_template
John McCall53262c92010-01-12 02:15:36 +00009277};
9278
George Burgess IVd66d37c2016-10-28 21:42:06 +00009279static OverloadCandidateKind
9280ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
9281 std::string &Description) {
John McCalle1ac8d12010-01-13 00:25:19 +00009282 bool isTemplate = false;
9283
9284 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
9285 isTemplate = true;
9286 Description = S.getTemplateArgumentBindingsText(
9287 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
9288 }
John McCallfd0b2f82010-01-06 09:43:14 +00009289
9290 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
Richard Smith5179eb72016-06-28 19:03:57 +00009291 if (!Ctor->isImplicit()) {
9292 if (isa<ConstructorUsingShadowDecl>(Found))
9293 return isTemplate ? oc_inherited_constructor_template
9294 : oc_inherited_constructor;
9295 else
9296 return isTemplate ? oc_constructor_template : oc_constructor;
9297 }
Sebastian Redl08905022011-02-05 19:23:19 +00009298
Alexis Hunt119c10e2011-05-25 23:16:36 +00009299 if (Ctor->isDefaultConstructor())
9300 return oc_implicit_default_constructor;
9301
9302 if (Ctor->isMoveConstructor())
9303 return oc_implicit_move_constructor;
9304
9305 assert(Ctor->isCopyConstructor() &&
9306 "unexpected sort of implicit constructor");
9307 return oc_implicit_copy_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00009308 }
9309
9310 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
9311 // This actually gets spelled 'candidate function' for now, but
9312 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00009313 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00009314 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00009315
Alexis Hunt119c10e2011-05-25 23:16:36 +00009316 if (Meth->isMoveAssignmentOperator())
9317 return oc_implicit_move_assignment;
9318
Douglas Gregor12695102012-02-10 08:36:38 +00009319 if (Meth->isCopyAssignmentOperator())
9320 return oc_implicit_copy_assignment;
9321
9322 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
9323 return oc_method;
John McCall53262c92010-01-12 02:15:36 +00009324 }
9325
John McCalle1ac8d12010-01-13 00:25:19 +00009326 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00009327}
9328
Richard Smith5179eb72016-06-28 19:03:57 +00009329void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
9330 // FIXME: It'd be nice to only emit a note once per using-decl per overload
9331 // set.
9332 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
9333 S.Diag(FoundDecl->getLocation(),
9334 diag::note_ovl_candidate_inherited_constructor)
9335 << Shadow->getNominatedBaseClass();
Sebastian Redl08905022011-02-05 19:23:19 +00009336}
9337
John McCall53262c92010-01-12 02:15:36 +00009338} // end anonymous namespace
9339
George Burgess IV5f21c712015-10-12 19:57:04 +00009340static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
9341 const FunctionDecl *FD) {
9342 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
9343 bool AlwaysTrue;
9344 if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
9345 return false;
9346 if (!AlwaysTrue)
9347 return false;
9348 }
9349 return true;
9350}
9351
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009352/// \brief Returns true if we can take the address of the function.
9353///
9354/// \param Complain - If true, we'll emit a diagnostic
9355/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
9356/// we in overload resolution?
9357/// \param Loc - The location of the statement we're complaining about. Ignored
9358/// if we're not complaining, or if we're in overload resolution.
9359static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
9360 bool Complain,
9361 bool InOverloadResolution,
9362 SourceLocation Loc) {
9363 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
9364 if (Complain) {
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009365 if (InOverloadResolution)
9366 S.Diag(FD->getLocStart(),
9367 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
9368 else
9369 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
9370 }
9371 return false;
9372 }
9373
George Burgess IV21081362016-07-24 23:12:40 +00009374 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
9375 return P->hasAttr<PassObjectSizeAttr>();
9376 });
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009377 if (I == FD->param_end())
9378 return true;
9379
9380 if (Complain) {
9381 // Add one to ParamNo because it's user-facing
9382 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
9383 if (InOverloadResolution)
9384 S.Diag(FD->getLocation(),
9385 diag::note_ovl_candidate_has_pass_object_size_params)
9386 << ParamNo;
9387 else
9388 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
9389 << FD << ParamNo;
9390 }
9391 return false;
9392}
9393
9394static bool checkAddressOfCandidateIsAvailable(Sema &S,
9395 const FunctionDecl *FD) {
9396 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
9397 /*InOverloadResolution=*/true,
9398 /*Loc=*/SourceLocation());
9399}
9400
9401bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
9402 bool Complain,
9403 SourceLocation Loc) {
9404 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
9405 /*InOverloadResolution=*/false,
9406 Loc);
9407}
9408
John McCall53262c92010-01-12 02:15:36 +00009409// Notes the location of an overload candidate.
Richard Smithc2bebe92016-05-11 20:37:46 +00009410void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
9411 QualType DestType, bool TakingAddress) {
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009412 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
9413 return;
Erich Keane281d20b2018-01-08 21:34:17 +00009414 if (Fn->isMultiVersion() && !Fn->getAttr<TargetAttr>()->isDefaultVersion())
9415 return;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009416
John McCalle1ac8d12010-01-13 00:25:19 +00009417 std::string FnDesc;
Richard Smithc2bebe92016-05-11 20:37:46 +00009418 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Found, Fn, FnDesc);
Richard Trieucaff2472011-11-23 22:32:32 +00009419 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
Saleem Abdulrasool78704fb2016-12-22 04:26:57 +00009420 << (unsigned) K << Fn << FnDesc;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009421
9422 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
Richard Trieucaff2472011-11-23 22:32:32 +00009423 Diag(Fn->getLocation(), PD);
Richard Smith5179eb72016-06-28 19:03:57 +00009424 MaybeEmitInheritedConstructorNote(*this, Found);
John McCallfd0b2f82010-01-06 09:43:14 +00009425}
9426
Nick Lewyckyed4265c2013-09-22 10:06:01 +00009427// Notes the location of all overload candidates designated through
Douglas Gregorb491ed32011-02-19 21:32:49 +00009428// OverloadedExpr
George Burgess IV5f21c712015-10-12 19:57:04 +00009429void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
9430 bool TakingAddress) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009431 assert(OverloadedExpr->getType() == Context.OverloadTy);
9432
9433 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
9434 OverloadExpr *OvlExpr = Ovl.Expression;
9435
9436 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00009437 IEnd = OvlExpr->decls_end();
Douglas Gregorb491ed32011-02-19 21:32:49 +00009438 I != IEnd; ++I) {
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00009439 if (FunctionTemplateDecl *FunTmpl =
Douglas Gregorb491ed32011-02-19 21:32:49 +00009440 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Smithc2bebe92016-05-11 20:37:46 +00009441 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType,
George Burgess IV5f21c712015-10-12 19:57:04 +00009442 TakingAddress);
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00009443 } else if (FunctionDecl *Fun
Douglas Gregorb491ed32011-02-19 21:32:49 +00009444 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Smithc2bebe92016-05-11 20:37:46 +00009445 NoteOverloadCandidate(*I, Fun, DestType, TakingAddress);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009446 }
9447 }
9448}
9449
John McCall0d1da222010-01-12 00:44:57 +00009450/// Diagnoses an ambiguous conversion. The partial diagnostic is the
9451/// "lead" diagnostic; it will be given two arguments, the source and
9452/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00009453void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
9454 Sema &S,
9455 SourceLocation CaretLoc,
9456 const PartialDiagnostic &PDiag) const {
9457 S.Diag(CaretLoc, PDiag)
9458 << Ambiguous.getFromType() << Ambiguous.getToType();
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00009459 // FIXME: The note limiting machinery is borrowed from
9460 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
9461 // refactoring here.
9462 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9463 unsigned CandsShown = 0;
9464 AmbiguousConversionSequence::const_iterator I, E;
9465 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
9466 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9467 break;
9468 ++CandsShown;
Richard Smithc2bebe92016-05-11 20:37:46 +00009469 S.NoteOverloadCandidate(I->first, I->second);
John McCall0d1da222010-01-12 00:44:57 +00009470 }
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00009471 if (I != E)
9472 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
John McCall12f97bc2010-01-08 04:41:39 +00009473}
9474
Richard Smith17c00b42014-11-12 01:24:00 +00009475static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009476 unsigned I, bool TakingCandidateAddress) {
John McCall6a61b522010-01-13 09:16:55 +00009477 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
9478 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00009479 assert(Cand->Function && "for now, candidate must be a function");
9480 FunctionDecl *Fn = Cand->Function;
9481
9482 // There's a conversion slot for the object argument if this is a
9483 // non-constructor method. Note that 'I' corresponds the
9484 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00009485 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00009486 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00009487 if (I == 0)
9488 isObjectArgument = true;
9489 else
9490 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00009491 }
9492
John McCalle1ac8d12010-01-13 00:25:19 +00009493 std::string FnDesc;
Richard Smithc2bebe92016-05-11 20:37:46 +00009494 OverloadCandidateKind FnKind =
9495 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
John McCalle1ac8d12010-01-13 00:25:19 +00009496
John McCall6a61b522010-01-13 09:16:55 +00009497 Expr *FromExpr = Conv.Bad.FromExpr;
9498 QualType FromTy = Conv.Bad.getFromType();
9499 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00009500
John McCallfb7ad0f2010-02-02 02:42:52 +00009501 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00009502 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00009503 Expr *E = FromExpr->IgnoreParens();
9504 if (isa<UnaryOperator>(E))
9505 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00009506 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00009507
9508 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
9509 << (unsigned) FnKind << FnDesc
9510 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9511 << ToTy << Name << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009512 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCallfb7ad0f2010-02-02 02:42:52 +00009513 return;
9514 }
9515
John McCall6d174642010-01-23 08:10:49 +00009516 // Do some hand-waving analysis to see if the non-viability is due
9517 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00009518 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
9519 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
9520 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
9521 CToTy = RT->getPointeeType();
9522 else {
9523 // TODO: detect and diagnose the full richness of const mismatches.
9524 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
Richard Trieucc3949d2016-02-18 22:34:54 +00009525 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
9526 CFromTy = FromPT->getPointeeType();
9527 CToTy = ToPT->getPointeeType();
9528 }
John McCall47000992010-01-14 03:28:57 +00009529 }
9530
9531 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
9532 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall47000992010-01-14 03:28:57 +00009533 Qualifiers FromQs = CFromTy.getQualifiers();
9534 Qualifiers ToQs = CToTy.getQualifiers();
9535
9536 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
9537 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
9538 << (unsigned) FnKind << FnDesc
9539 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9540 << FromTy
Yaxun Liub34ec822017-04-11 17:24:23 +00009541 << FromQs.getAddressSpaceAttributePrintValue()
9542 << ToQs.getAddressSpaceAttributePrintValue()
John McCall47000992010-01-14 03:28:57 +00009543 << (unsigned) isObjectArgument << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009544 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall47000992010-01-14 03:28:57 +00009545 return;
9546 }
9547
John McCall31168b02011-06-15 23:02:42 +00009548 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00009549 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCall31168b02011-06-15 23:02:42 +00009550 << (unsigned) FnKind << FnDesc
9551 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9552 << FromTy
9553 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
9554 << (unsigned) isObjectArgument << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009555 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall31168b02011-06-15 23:02:42 +00009556 return;
9557 }
9558
Douglas Gregoraec25842011-04-26 23:16:46 +00009559 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
9560 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
9561 << (unsigned) FnKind << FnDesc
9562 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9563 << FromTy
9564 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
9565 << (unsigned) isObjectArgument << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009566 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Douglas Gregoraec25842011-04-26 23:16:46 +00009567 return;
9568 }
9569
Andrey Bokhanko45d41322016-05-11 18:38:21 +00009570 if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
9571 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
9572 << (unsigned) FnKind << FnDesc
9573 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9574 << FromTy << FromQs.hasUnaligned() << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009575 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Andrey Bokhanko45d41322016-05-11 18:38:21 +00009576 return;
9577 }
9578
John McCall47000992010-01-14 03:28:57 +00009579 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
9580 assert(CVR && "unexpected qualifiers mismatch");
9581
9582 if (isObjectArgument) {
9583 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
9584 << (unsigned) FnKind << FnDesc
9585 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9586 << FromTy << (CVR - 1);
9587 } else {
9588 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
9589 << (unsigned) FnKind << FnDesc
9590 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9591 << FromTy << (CVR - 1) << I+1;
9592 }
Richard Smith5179eb72016-06-28 19:03:57 +00009593 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall47000992010-01-14 03:28:57 +00009594 return;
9595 }
9596
Sebastian Redla72462c2011-09-24 17:48:32 +00009597 // Special diagnostic for failure to convert an initializer list, since
9598 // telling the user that it has type void is not useful.
9599 if (FromExpr && isa<InitListExpr>(FromExpr)) {
9600 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
9601 << (unsigned) FnKind << FnDesc
9602 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9603 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009604 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Sebastian Redla72462c2011-09-24 17:48:32 +00009605 return;
9606 }
9607
John McCall6d174642010-01-23 08:10:49 +00009608 // Diagnose references or pointers to incomplete types differently,
9609 // since it's far from impossible that the incompleteness triggered
9610 // the failure.
9611 QualType TempFromTy = FromTy.getNonReferenceType();
9612 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
9613 TempFromTy = PTy->getPointeeType();
9614 if (TempFromTy->isIncompleteType()) {
David Blaikieac928932016-03-04 22:29:11 +00009615 // Emit the generic diagnostic and, optionally, add the hints to it.
John McCall6d174642010-01-23 08:10:49 +00009616 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
9617 << (unsigned) FnKind << FnDesc
9618 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
David Blaikieac928932016-03-04 22:29:11 +00009619 << FromTy << ToTy << (unsigned) isObjectArgument << I+1
9620 << (unsigned) (Cand->Fix.Kind);
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00009621
Richard Smith5179eb72016-06-28 19:03:57 +00009622 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall6d174642010-01-23 08:10:49 +00009623 return;
9624 }
9625
Douglas Gregor56f2e342010-06-30 23:01:39 +00009626 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009627 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00009628 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
9629 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
9630 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9631 FromPtrTy->getPointeeType()) &&
9632 !FromPtrTy->getPointeeType()->isIncompleteType() &&
9633 !ToPtrTy->getPointeeType()->isIncompleteType() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00009634 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00009635 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009636 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00009637 }
9638 } else if (const ObjCObjectPointerType *FromPtrTy
9639 = FromTy->getAs<ObjCObjectPointerType>()) {
9640 if (const ObjCObjectPointerType *ToPtrTy
9641 = ToTy->getAs<ObjCObjectPointerType>())
9642 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
9643 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
9644 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9645 FromPtrTy->getPointeeType()) &&
9646 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009647 BaseToDerivedConversion = 2;
9648 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009649 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
9650 !FromTy->isIncompleteType() &&
9651 !ToRefTy->getPointeeType()->isIncompleteType() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00009652 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009653 BaseToDerivedConversion = 3;
9654 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
9655 ToTy.getNonReferenceType().getCanonicalType() ==
9656 FromTy.getNonReferenceType().getCanonicalType()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009657 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
9658 << (unsigned) FnKind << FnDesc
9659 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9660 << (unsigned) isObjectArgument << I + 1;
Richard Smith5179eb72016-06-28 19:03:57 +00009661 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009662 return;
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009663 }
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009664 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009665
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009666 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009667 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009668 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00009669 << (unsigned) FnKind << FnDesc
9670 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009671 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009672 << FromTy << ToTy << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009673 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Douglas Gregor56f2e342010-06-30 23:01:39 +00009674 return;
9675 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009676
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00009677 if (isa<ObjCObjectPointerType>(CFromTy) &&
9678 isa<PointerType>(CToTy)) {
9679 Qualifiers FromQs = CFromTy.getQualifiers();
9680 Qualifiers ToQs = CToTy.getQualifiers();
9681 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9682 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
9683 << (unsigned) FnKind << FnDesc
9684 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9685 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009686 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00009687 return;
9688 }
9689 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009690
9691 if (TakingCandidateAddress &&
9692 !checkAddressOfCandidateIsAvailable(S, Cand->Function))
9693 return;
9694
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009695 // Emit the generic diagnostic and, optionally, add the hints to it.
9696 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
9697 FDiag << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00009698 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009699 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
9700 << (unsigned) (Cand->Fix.Kind);
9701
9702 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer490afa62012-01-14 21:05:10 +00009703 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
9704 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009705 FDiag << *HI;
9706 S.Diag(Fn->getLocation(), FDiag);
9707
Richard Smith5179eb72016-06-28 19:03:57 +00009708 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall6a61b522010-01-13 09:16:55 +00009709}
9710
Larisse Voufo98b20f12013-07-19 23:00:19 +00009711/// Additional arity mismatch diagnosis specific to a function overload
9712/// candidates. This is not covered by the more general DiagnoseArityMismatch()
9713/// over a candidate in any candidate set.
Richard Smith17c00b42014-11-12 01:24:00 +00009714static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
9715 unsigned NumArgs) {
John McCall6a61b522010-01-13 09:16:55 +00009716 FunctionDecl *Fn = Cand->Function;
John McCall6a61b522010-01-13 09:16:55 +00009717 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009718
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009719 // With invalid overloaded operators, it's possible that we think we
Larisse Voufo98b20f12013-07-19 23:00:19 +00009720 // have an arity mismatch when in fact it looks like we have the
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009721 // right number of arguments, because only overloaded operators have
9722 // the weird behavior of overloading member and non-member functions.
9723 // Just don't report anything.
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00009724 if (Fn->isInvalidDecl() &&
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009725 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009726 return true;
9727
9728 if (NumArgs < MinParams) {
9729 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
9730 (Cand->FailureKind == ovl_fail_bad_deduction &&
9731 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
9732 } else {
9733 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
9734 (Cand->FailureKind == ovl_fail_bad_deduction &&
9735 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
9736 }
9737
9738 return false;
9739}
9740
9741/// General arity mismatch diagnosis over a candidate in a candidate set.
Richard Smithc2bebe92016-05-11 20:37:46 +00009742static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
9743 unsigned NumFormalArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009744 assert(isa<FunctionDecl>(D) &&
9745 "The templated declaration should at least be a function"
9746 " when diagnosing bad template argument deduction due to too many"
9747 " or too few arguments");
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00009748
Larisse Voufo98b20f12013-07-19 23:00:19 +00009749 FunctionDecl *Fn = cast<FunctionDecl>(D);
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00009750
Larisse Voufo98b20f12013-07-19 23:00:19 +00009751 // TODO: treat calls to a missing default constructor as a special case
9752 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
9753 unsigned MinParams = Fn->getMinRequiredArguments();
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009754
John McCall6a61b522010-01-13 09:16:55 +00009755 // at least / at most / exactly
9756 unsigned mode, modeCount;
9757 if (NumFormalArgs < MinParams) {
Alp Toker9cacbab2014-01-20 20:26:09 +00009758 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
9759 FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00009760 mode = 0; // "at least"
9761 else
9762 mode = 2; // "exactly"
9763 modeCount = MinParams;
9764 } else {
Alp Toker9cacbab2014-01-20 20:26:09 +00009765 if (MinParams != FnTy->getNumParams())
John McCall6a61b522010-01-13 09:16:55 +00009766 mode = 1; // "at most"
9767 else
9768 mode = 2; // "exactly"
Alp Toker9cacbab2014-01-20 20:26:09 +00009769 modeCount = FnTy->getNumParams();
John McCall6a61b522010-01-13 09:16:55 +00009770 }
9771
9772 std::string Description;
Richard Smithc2bebe92016-05-11 20:37:46 +00009773 OverloadCandidateKind FnKind =
9774 ClassifyOverloadCandidate(S, Found, Fn, Description);
John McCall6a61b522010-01-13 09:16:55 +00009775
Richard Smith10ff50d2012-05-11 05:16:41 +00009776 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
9777 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
Craig Topperc3ec1492014-05-26 06:22:03 +00009778 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9779 << mode << Fn->getParamDecl(0) << NumFormalArgs;
Richard Smith10ff50d2012-05-11 05:16:41 +00009780 else
9781 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Craig Topperc3ec1492014-05-26 06:22:03 +00009782 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9783 << mode << modeCount << NumFormalArgs;
Richard Smith5179eb72016-06-28 19:03:57 +00009784 MaybeEmitInheritedConstructorNote(S, Found);
John McCalle1ac8d12010-01-13 00:25:19 +00009785}
9786
Larisse Voufo98b20f12013-07-19 23:00:19 +00009787/// Arity mismatch diagnosis specific to a function overload candidate.
Richard Smith17c00b42014-11-12 01:24:00 +00009788static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
9789 unsigned NumFormalArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009790 if (!CheckArityMismatch(S, Cand, NumFormalArgs))
Richard Smithc2bebe92016-05-11 20:37:46 +00009791 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
Larisse Voufo98b20f12013-07-19 23:00:19 +00009792}
Larisse Voufo47c08452013-07-19 22:53:23 +00009793
Richard Smith17c00b42014-11-12 01:24:00 +00009794static TemplateDecl *getDescribedTemplate(Decl *Templated) {
Serge Pavlov7dcc97e2016-04-19 06:19:52 +00009795 if (TemplateDecl *TD = Templated->getDescribedTemplate())
9796 return TD;
Larisse Voufo98b20f12013-07-19 23:00:19 +00009797 llvm_unreachable("Unsupported: Getting the described template declaration"
9798 " for bad deduction diagnosis");
9799}
9800
9801/// Diagnose a failed template-argument deduction.
Richard Smithc2bebe92016-05-11 20:37:46 +00009802static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
Richard Smith17c00b42014-11-12 01:24:00 +00009803 DeductionFailureInfo &DeductionFailure,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009804 unsigned NumArgs,
9805 bool TakingCandidateAddress) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009806 TemplateParameter Param = DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009807 NamedDecl *ParamD;
9808 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
9809 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
9810 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
Larisse Voufo98b20f12013-07-19 23:00:19 +00009811 switch (DeductionFailure.Result) {
John McCall8b9ed552010-02-01 18:53:26 +00009812 case Sema::TDK_Success:
9813 llvm_unreachable("TDK_success while diagnosing bad deduction");
9814
9815 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00009816 assert(ParamD && "no parameter found for incomplete deduction result");
Larisse Voufo98b20f12013-07-19 23:00:19 +00009817 S.Diag(Templated->getLocation(),
9818 diag::note_ovl_candidate_incomplete_deduction)
9819 << ParamD->getDeclName();
Richard Smith5179eb72016-06-28 19:03:57 +00009820 MaybeEmitInheritedConstructorNote(S, Found);
John McCall8b9ed552010-02-01 18:53:26 +00009821 return;
9822 }
9823
John McCall42d7d192010-08-05 09:05:08 +00009824 case Sema::TDK_Underqualified: {
9825 assert(ParamD && "no parameter found for bad qualifiers deduction result");
9826 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
9827
Larisse Voufo98b20f12013-07-19 23:00:19 +00009828 QualType Param = DeductionFailure.getFirstArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00009829
9830 // Param will have been canonicalized, but it should just be a
9831 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00009832 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00009833 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00009834 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00009835 assert(S.Context.hasSameType(Param, NonCanonParam));
9836
9837 // Arg has also been canonicalized, but there's nothing we can do
9838 // about that. It also doesn't matter as much, because it won't
9839 // have any template parameters in it (because deduction isn't
9840 // done on dependent types).
Larisse Voufo98b20f12013-07-19 23:00:19 +00009841 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00009842
Larisse Voufo98b20f12013-07-19 23:00:19 +00009843 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
9844 << ParamD->getDeclName() << Arg << NonCanonParam;
Richard Smith5179eb72016-06-28 19:03:57 +00009845 MaybeEmitInheritedConstructorNote(S, Found);
John McCall42d7d192010-08-05 09:05:08 +00009846 return;
9847 }
9848
9849 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00009850 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009851 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009852 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009853 which = 0;
Richard Smith593d6a12016-12-23 01:30:39 +00009854 else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
9855 // Deduction might have failed because we deduced arguments of two
9856 // different types for a non-type template parameter.
9857 // FIXME: Use a different TDK value for this.
9858 QualType T1 =
9859 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
9860 QualType T2 =
9861 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
9862 if (!S.Context.hasSameType(T1, T2)) {
9863 S.Diag(Templated->getLocation(),
9864 diag::note_ovl_candidate_inconsistent_deduction_types)
9865 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
9866 << *DeductionFailure.getSecondArg() << T2;
9867 MaybeEmitInheritedConstructorNote(S, Found);
9868 return;
9869 }
9870
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009871 which = 1;
Richard Smith593d6a12016-12-23 01:30:39 +00009872 } else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009873 which = 2;
9874 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009875
Larisse Voufo98b20f12013-07-19 23:00:19 +00009876 S.Diag(Templated->getLocation(),
9877 diag::note_ovl_candidate_inconsistent_deduction)
9878 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
9879 << *DeductionFailure.getSecondArg();
Richard Smith5179eb72016-06-28 19:03:57 +00009880 MaybeEmitInheritedConstructorNote(S, Found);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009881 return;
9882 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00009883
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009884 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009885 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009886 if (ParamD->getDeclName())
Larisse Voufo98b20f12013-07-19 23:00:19 +00009887 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009888 diag::note_ovl_candidate_explicit_arg_mismatch_named)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009889 << ParamD->getDeclName();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009890 else {
9891 int index = 0;
9892 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
9893 index = TTP->getIndex();
9894 else if (NonTypeTemplateParmDecl *NTTP
9895 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
9896 index = NTTP->getIndex();
9897 else
9898 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
Larisse Voufo98b20f12013-07-19 23:00:19 +00009899 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009900 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009901 << (index + 1);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009902 }
Richard Smith5179eb72016-06-28 19:03:57 +00009903 MaybeEmitInheritedConstructorNote(S, Found);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009904 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009905
Douglas Gregor02eb4832010-05-08 18:13:28 +00009906 case Sema::TDK_TooManyArguments:
9907 case Sema::TDK_TooFewArguments:
Richard Smithc2bebe92016-05-11 20:37:46 +00009908 DiagnoseArityMismatch(S, Found, Templated, NumArgs);
Douglas Gregor02eb4832010-05-08 18:13:28 +00009909 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00009910
9911 case Sema::TDK_InstantiationDepth:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009912 S.Diag(Templated->getLocation(),
9913 diag::note_ovl_candidate_instantiation_depth);
Richard Smith5179eb72016-06-28 19:03:57 +00009914 MaybeEmitInheritedConstructorNote(S, Found);
Douglas Gregord09efd42010-05-08 20:07:26 +00009915 return;
9916
9917 case Sema::TDK_SubstitutionFailure: {
Richard Smith9ca64612012-05-07 09:03:25 +00009918 // Format the template argument list into the argument string.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009919 SmallString<128> TemplateArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00009920 if (TemplateArgumentList *Args =
Larisse Voufo98b20f12013-07-19 23:00:19 +00009921 DeductionFailure.getTemplateArgumentList()) {
Richard Smith9ca64612012-05-07 09:03:25 +00009922 TemplateArgString = " ";
9923 TemplateArgString += S.getTemplateArgumentBindingsText(
Larisse Voufo98b20f12013-07-19 23:00:19 +00009924 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
Richard Smith9ca64612012-05-07 09:03:25 +00009925 }
9926
Richard Smith6f8d2c62012-05-09 05:17:00 +00009927 // If this candidate was disabled by enable_if, say so.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009928 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
Richard Smith6f8d2c62012-05-09 05:17:00 +00009929 if (PDiag && PDiag->second.getDiagID() ==
9930 diag::err_typename_nested_not_found_enable_if) {
9931 // FIXME: Use the source range of the condition, and the fully-qualified
9932 // name of the enable_if template. These are both present in PDiag.
9933 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
9934 << "'enable_if'" << TemplateArgString;
9935 return;
9936 }
9937
Douglas Gregor00fa10b2017-07-05 20:20:14 +00009938 // We found a specific requirement that disabled the enable_if.
9939 if (PDiag && PDiag->second.getDiagID() ==
9940 diag::err_typename_nested_not_found_requirement) {
9941 S.Diag(Templated->getLocation(),
9942 diag::note_ovl_candidate_disabled_by_requirement)
9943 << PDiag->second.getStringArg(0) << TemplateArgString;
9944 return;
9945 }
9946
Richard Smith9ca64612012-05-07 09:03:25 +00009947 // Format the SFINAE diagnostic into the argument string.
9948 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
9949 // formatted message in another diagnostic.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009950 SmallString<128> SFINAEArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00009951 SourceRange R;
Richard Smith6f8d2c62012-05-09 05:17:00 +00009952 if (PDiag) {
Richard Smith9ca64612012-05-07 09:03:25 +00009953 SFINAEArgString = ": ";
9954 R = SourceRange(PDiag->first, PDiag->first);
9955 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
9956 }
9957
Larisse Voufo98b20f12013-07-19 23:00:19 +00009958 S.Diag(Templated->getLocation(),
9959 diag::note_ovl_candidate_substitution_failure)
9960 << TemplateArgString << SFINAEArgString << R;
Richard Smith5179eb72016-06-28 19:03:57 +00009961 MaybeEmitInheritedConstructorNote(S, Found);
Douglas Gregord09efd42010-05-08 20:07:26 +00009962 return;
9963 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009964
Richard Smithc92d2062017-01-05 23:02:44 +00009965 case Sema::TDK_DeducedMismatch:
9966 case Sema::TDK_DeducedMismatchNested: {
Richard Smith9b534542015-12-31 02:02:54 +00009967 // Format the template argument list into the argument string.
9968 SmallString<128> TemplateArgString;
9969 if (TemplateArgumentList *Args =
9970 DeductionFailure.getTemplateArgumentList()) {
9971 TemplateArgString = " ";
9972 TemplateArgString += S.getTemplateArgumentBindingsText(
9973 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9974 }
9975
9976 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
9977 << (*DeductionFailure.getCallArgIndex() + 1)
9978 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
Richard Smithc92d2062017-01-05 23:02:44 +00009979 << TemplateArgString
9980 << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
Richard Smith9b534542015-12-31 02:02:54 +00009981 break;
9982 }
9983
Richard Trieue3732352013-04-08 21:11:40 +00009984 case Sema::TDK_NonDeducedMismatch: {
Richard Smith44ecdbd2013-01-31 05:19:49 +00009985 // FIXME: Provide a source location to indicate what we couldn't match.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009986 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
9987 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
Richard Trieue3732352013-04-08 21:11:40 +00009988 if (FirstTA.getKind() == TemplateArgument::Template &&
9989 SecondTA.getKind() == TemplateArgument::Template) {
9990 TemplateName FirstTN = FirstTA.getAsTemplate();
9991 TemplateName SecondTN = SecondTA.getAsTemplate();
9992 if (FirstTN.getKind() == TemplateName::Template &&
9993 SecondTN.getKind() == TemplateName::Template) {
9994 if (FirstTN.getAsTemplateDecl()->getName() ==
9995 SecondTN.getAsTemplateDecl()->getName()) {
9996 // FIXME: This fixes a bad diagnostic where both templates are named
9997 // the same. This particular case is a bit difficult since:
9998 // 1) It is passed as a string to the diagnostic printer.
9999 // 2) The diagnostic printer only attempts to find a better
10000 // name for types, not decls.
10001 // Ideally, this should folded into the diagnostic printer.
Larisse Voufo98b20f12013-07-19 23:00:19 +000010002 S.Diag(Templated->getLocation(),
Richard Trieue3732352013-04-08 21:11:40 +000010003 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
10004 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
10005 return;
10006 }
10007 }
10008 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010009
10010 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
10011 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
10012 return;
10013
Faisal Vali2b391ab2013-09-26 19:54:12 +000010014 // FIXME: For generic lambda parameters, check if the function is a lambda
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010015 // call operator, and if so, emit a prettier and more informative
10016 // diagnostic that mentions 'auto' and lambda in addition to
Faisal Vali2b391ab2013-09-26 19:54:12 +000010017 // (or instead of?) the canonical template type parameters.
Larisse Voufo98b20f12013-07-19 23:00:19 +000010018 S.Diag(Templated->getLocation(),
10019 diag::note_ovl_candidate_non_deduced_mismatch)
10020 << FirstTA << SecondTA;
Richard Smith44ecdbd2013-01-31 05:19:49 +000010021 return;
Richard Trieue3732352013-04-08 21:11:40 +000010022 }
John McCall8b9ed552010-02-01 18:53:26 +000010023 // TODO: diagnose these individually, then kill off
10024 // note_ovl_candidate_bad_deduction, which is uselessly vague.
Richard Smith44ecdbd2013-01-31 05:19:49 +000010025 case Sema::TDK_MiscellaneousDeductionFailure:
Larisse Voufo98b20f12013-07-19 23:00:19 +000010026 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
Richard Smith5179eb72016-06-28 19:03:57 +000010027 MaybeEmitInheritedConstructorNote(S, Found);
John McCall8b9ed552010-02-01 18:53:26 +000010028 return;
Artem Belevich13e9b4d2016-12-07 19:27:16 +000010029 case Sema::TDK_CUDATargetMismatch:
10030 S.Diag(Templated->getLocation(),
10031 diag::note_cuda_ovl_candidate_target_mismatch);
10032 return;
John McCall8b9ed552010-02-01 18:53:26 +000010033 }
10034}
10035
Larisse Voufo98b20f12013-07-19 23:00:19 +000010036/// Diagnose a failed template-argument deduction, for function calls.
Richard Smith17c00b42014-11-12 01:24:00 +000010037static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010038 unsigned NumArgs,
10039 bool TakingCandidateAddress) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010040 unsigned TDK = Cand->DeductionFailure.Result;
10041 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
10042 if (CheckArityMismatch(S, Cand, NumArgs))
10043 return;
10044 }
Richard Smithc2bebe92016-05-11 20:37:46 +000010045 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010046 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010047}
10048
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010049/// CUDA: diagnose an invalid call across targets.
Richard Smith17c00b42014-11-12 01:24:00 +000010050static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010051 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
10052 FunctionDecl *Callee = Cand->Function;
10053
10054 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
10055 CalleeTarget = S.IdentifyCUDATarget(Callee);
10056
10057 std::string FnDesc;
Richard Smithc2bebe92016-05-11 20:37:46 +000010058 OverloadCandidateKind FnKind =
10059 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc);
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010060
10061 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
Eli Bendersky9a220fc2014-09-29 20:38:29 +000010062 << (unsigned)FnKind << CalleeTarget << CallerTarget;
10063
10064 // This could be an implicit constructor for which we could not infer the
10065 // target due to a collsion. Diagnose that case.
10066 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
10067 if (Meth != nullptr && Meth->isImplicit()) {
10068 CXXRecordDecl *ParentClass = Meth->getParent();
10069 Sema::CXXSpecialMember CSM;
10070
10071 switch (FnKind) {
10072 default:
10073 return;
10074 case oc_implicit_default_constructor:
10075 CSM = Sema::CXXDefaultConstructor;
10076 break;
10077 case oc_implicit_copy_constructor:
10078 CSM = Sema::CXXCopyConstructor;
10079 break;
10080 case oc_implicit_move_constructor:
10081 CSM = Sema::CXXMoveConstructor;
10082 break;
10083 case oc_implicit_copy_assignment:
10084 CSM = Sema::CXXCopyAssignment;
10085 break;
10086 case oc_implicit_move_assignment:
10087 CSM = Sema::CXXMoveAssignment;
10088 break;
10089 };
10090
10091 bool ConstRHS = false;
10092 if (Meth->getNumParams()) {
10093 if (const ReferenceType *RT =
10094 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
10095 ConstRHS = RT->getPointeeType().isConstQualified();
10096 }
10097 }
10098
10099 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
10100 /* ConstRHS */ ConstRHS,
10101 /* Diagnose */ true);
10102 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010103}
10104
Richard Smith17c00b42014-11-12 01:24:00 +000010105static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010106 FunctionDecl *Callee = Cand->Function;
10107 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
10108
10109 S.Diag(Callee->getLocation(),
George Burgess IV177399e2017-01-09 04:12:14 +000010110 diag::note_ovl_candidate_disabled_by_function_cond_attr)
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010111 << Attr->getCond()->getSourceRange() << Attr->getMessage();
10112}
10113
Yaxun Liu5b746652016-12-18 05:18:55 +000010114static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) {
10115 FunctionDecl *Callee = Cand->Function;
10116
10117 S.Diag(Callee->getLocation(),
10118 diag::note_ovl_candidate_disabled_by_extension);
10119}
10120
John McCall8b9ed552010-02-01 18:53:26 +000010121/// Generates a 'note' diagnostic for an overload candidate. We've
10122/// already generated a primary error at the call site.
10123///
10124/// It really does need to be a single diagnostic with its caret
10125/// pointed at the candidate declaration. Yes, this creates some
10126/// major challenges of technical writing. Yes, this makes pointing
10127/// out problems with specific arguments quite awkward. It's still
10128/// better than generating twenty screens of text for every failed
10129/// overload.
10130///
10131/// It would be great to be able to express per-candidate problems
10132/// more richly for those diagnostic clients that cared, but we'd
10133/// still have to be just as careful with the default diagnostics.
Richard Smith17c00b42014-11-12 01:24:00 +000010134static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010135 unsigned NumArgs,
10136 bool TakingCandidateAddress) {
John McCall53262c92010-01-12 02:15:36 +000010137 FunctionDecl *Fn = Cand->Function;
10138
John McCall12f97bc2010-01-08 04:41:39 +000010139 // Note deleted candidates, but only if they're viable.
George Burgess IV177399e2017-01-09 04:12:14 +000010140 if (Cand->Viable) {
10141 if (Fn->isDeleted() || S.isFunctionConsideredUnavailable(Fn)) {
10142 std::string FnDesc;
10143 OverloadCandidateKind FnKind =
Richard Smithc2bebe92016-05-11 20:37:46 +000010144 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +000010145
George Burgess IV177399e2017-01-09 04:12:14 +000010146 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
10147 << FnKind << FnDesc
10148 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
10149 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10150 return;
10151 }
John McCall12f97bc2010-01-08 04:41:39 +000010152
George Burgess IV177399e2017-01-09 04:12:14 +000010153 // We don't really have anything else to say about viable candidates.
Richard Smithc2bebe92016-05-11 20:37:46 +000010154 S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +000010155 return;
10156 }
John McCall0d1da222010-01-12 00:44:57 +000010157
John McCall6a61b522010-01-13 09:16:55 +000010158 switch (Cand->FailureKind) {
10159 case ovl_fail_too_many_arguments:
10160 case ovl_fail_too_few_arguments:
10161 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +000010162
John McCall6a61b522010-01-13 09:16:55 +000010163 case ovl_fail_bad_deduction:
Richard Smithc2bebe92016-05-11 20:37:46 +000010164 return DiagnoseBadDeduction(S, Cand, NumArgs,
10165 TakingCandidateAddress);
John McCall8b9ed552010-02-01 18:53:26 +000010166
John McCall578a1f82014-12-14 01:46:53 +000010167 case ovl_fail_illegal_constructor: {
10168 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
10169 << (Fn->getPrimaryTemplate() ? 1 : 0);
Richard Smith5179eb72016-06-28 19:03:57 +000010170 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall578a1f82014-12-14 01:46:53 +000010171 return;
10172 }
10173
John McCallfe796dd2010-01-23 05:17:32 +000010174 case ovl_fail_trivial_conversion:
10175 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +000010176 case ovl_fail_final_conversion_not_exact:
Richard Smithc2bebe92016-05-11 20:37:46 +000010177 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +000010178
John McCall65eb8792010-02-25 01:37:24 +000010179 case ovl_fail_bad_conversion: {
10180 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Richard Smith6eedfe72017-01-09 08:01:21 +000010181 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +000010182 if (Cand->Conversions[I].isBad())
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010183 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010184
John McCall6a61b522010-01-13 09:16:55 +000010185 // FIXME: this currently happens when we're called from SemaInit
10186 // when user-conversion overload fails. Figure out how to handle
10187 // those conditions and diagnose them well.
Richard Smithc2bebe92016-05-11 20:37:46 +000010188 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +000010189 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010190
10191 case ovl_fail_bad_target:
10192 return DiagnoseBadTarget(S, Cand);
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010193
10194 case ovl_fail_enable_if:
10195 return DiagnoseFailedEnableIfAttr(S, Cand);
George Burgess IV7204ed92016-01-07 02:26:57 +000010196
Yaxun Liu5b746652016-12-18 05:18:55 +000010197 case ovl_fail_ext_disabled:
10198 return DiagnoseOpenCLExtensionDisabled(S, Cand);
10199
Richard Smithf9c59b72017-01-08 21:45:44 +000010200 case ovl_fail_inhctor_slice:
Richard Smith836a3b42017-01-13 20:46:54 +000010201 // It's generally not interesting to note copy/move constructors here.
10202 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
10203 return;
Richard Smithf9c59b72017-01-08 21:45:44 +000010204 S.Diag(Fn->getLocation(),
Richard Smith836a3b42017-01-13 20:46:54 +000010205 diag::note_ovl_candidate_inherited_constructor_slice)
10206 << (Fn->getPrimaryTemplate() ? 1 : 0)
10207 << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
Richard Smithf9c59b72017-01-08 21:45:44 +000010208 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10209 return;
10210
George Burgess IV7204ed92016-01-07 02:26:57 +000010211 case ovl_fail_addr_not_available: {
10212 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
10213 (void)Available;
10214 assert(!Available);
10215 break;
10216 }
Erich Keane281d20b2018-01-08 21:34:17 +000010217 case ovl_non_default_multiversion_function:
10218 // Do nothing, these should simply be ignored.
10219 break;
John McCall65eb8792010-02-25 01:37:24 +000010220 }
John McCalld3224162010-01-08 00:58:21 +000010221}
10222
Richard Smith17c00b42014-11-12 01:24:00 +000010223static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
John McCalld3224162010-01-08 00:58:21 +000010224 // Desugar the type of the surrogate down to a function type,
10225 // retaining as many typedefs as possible while still showing
10226 // the function type (and, therefore, its parameter types).
10227 QualType FnType = Cand->Surrogate->getConversionType();
10228 bool isLValueReference = false;
10229 bool isRValueReference = false;
10230 bool isPointer = false;
10231 if (const LValueReferenceType *FnTypeRef =
10232 FnType->getAs<LValueReferenceType>()) {
10233 FnType = FnTypeRef->getPointeeType();
10234 isLValueReference = true;
10235 } else if (const RValueReferenceType *FnTypeRef =
10236 FnType->getAs<RValueReferenceType>()) {
10237 FnType = FnTypeRef->getPointeeType();
10238 isRValueReference = true;
10239 }
10240 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
10241 FnType = FnTypePtr->getPointeeType();
10242 isPointer = true;
10243 }
10244 // Desugar down to a function type.
10245 FnType = QualType(FnType->getAs<FunctionType>(), 0);
10246 // Reconstruct the pointer/reference as appropriate.
10247 if (isPointer) FnType = S.Context.getPointerType(FnType);
10248 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
10249 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
10250
10251 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
10252 << FnType;
10253}
10254
Richard Smith17c00b42014-11-12 01:24:00 +000010255static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
10256 SourceLocation OpLoc,
10257 OverloadCandidate *Cand) {
Richard Smith6eedfe72017-01-09 08:01:21 +000010258 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
John McCalld3224162010-01-08 00:58:21 +000010259 std::string TypeStr("operator");
10260 TypeStr += Opc;
10261 TypeStr += "(";
George Burgess IV5f6ab9a2017-06-08 20:55:21 +000010262 TypeStr += Cand->BuiltinParamTypes[0].getAsString();
Richard Smith6eedfe72017-01-09 08:01:21 +000010263 if (Cand->Conversions.size() == 1) {
John McCalld3224162010-01-08 00:58:21 +000010264 TypeStr += ")";
10265 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
10266 } else {
10267 TypeStr += ", ";
George Burgess IV5f6ab9a2017-06-08 20:55:21 +000010268 TypeStr += Cand->BuiltinParamTypes[1].getAsString();
John McCalld3224162010-01-08 00:58:21 +000010269 TypeStr += ")";
10270 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
10271 }
10272}
10273
Richard Smith17c00b42014-11-12 01:24:00 +000010274static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
10275 OverloadCandidate *Cand) {
Richard Smith6eedfe72017-01-09 08:01:21 +000010276 for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
John McCall0d1da222010-01-12 00:44:57 +000010277 if (ICS.isBad()) break; // all meaningless after first invalid
10278 if (!ICS.isAmbiguous()) continue;
10279
Richard Smithc2bebe92016-05-11 20:37:46 +000010280 ICS.DiagnoseAmbiguousConversion(
10281 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +000010282 }
10283}
10284
Larisse Voufo98b20f12013-07-19 23:00:19 +000010285static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
John McCall3712d9e2010-01-15 23:32:50 +000010286 if (Cand->Function)
10287 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +000010288 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +000010289 return Cand->Surrogate->getLocation();
10290 return SourceLocation();
10291}
10292
Larisse Voufo98b20f12013-07-19 23:00:19 +000010293static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
Chandler Carruth73fddfe2011-09-10 00:51:24 +000010294 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010295 case Sema::TDK_Success:
Richard Smith6eedfe72017-01-09 08:01:21 +000010296 case Sema::TDK_NonDependentConversionFailure:
10297 llvm_unreachable("non-deduction failure while diagnosing bad deduction");
Benjamin Kramer8a8051f2011-09-10 21:52:04 +000010298
Douglas Gregorc5c01a62012-09-13 21:01:57 +000010299 case Sema::TDK_Invalid:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010300 case Sema::TDK_Incomplete:
10301 return 1;
10302
10303 case Sema::TDK_Underqualified:
10304 case Sema::TDK_Inconsistent:
10305 return 2;
10306
10307 case Sema::TDK_SubstitutionFailure:
Richard Smith9b534542015-12-31 02:02:54 +000010308 case Sema::TDK_DeducedMismatch:
Richard Smithc92d2062017-01-05 23:02:44 +000010309 case Sema::TDK_DeducedMismatchNested:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010310 case Sema::TDK_NonDeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +000010311 case Sema::TDK_MiscellaneousDeductionFailure:
Artem Belevich13e9b4d2016-12-07 19:27:16 +000010312 case Sema::TDK_CUDATargetMismatch:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010313 return 3;
10314
10315 case Sema::TDK_InstantiationDepth:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010316 return 4;
10317
10318 case Sema::TDK_InvalidExplicitArguments:
10319 return 5;
10320
10321 case Sema::TDK_TooManyArguments:
10322 case Sema::TDK_TooFewArguments:
10323 return 6;
10324 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +000010325 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010326}
10327
Richard Smith17c00b42014-11-12 01:24:00 +000010328namespace {
John McCallad2587a2010-01-12 00:48:53 +000010329struct CompareOverloadCandidatesForDisplay {
10330 Sema &S;
Richard Smith0f59cb32015-12-18 21:45:41 +000010331 SourceLocation Loc;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +000010332 size_t NumArgs;
Richard Smith67ef14f2017-09-26 18:37:55 +000010333 OverloadCandidateSet::CandidateSetKind CSK;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +000010334
Richard Smith67ef14f2017-09-26 18:37:55 +000010335 CompareOverloadCandidatesForDisplay(
10336 Sema &S, SourceLocation Loc, size_t NArgs,
10337 OverloadCandidateSet::CandidateSetKind CSK)
Richard Smithfd544352017-09-26 21:33:43 +000010338 : S(S), NumArgs(NArgs), CSK(CSK) {}
John McCall12f97bc2010-01-08 04:41:39 +000010339
10340 bool operator()(const OverloadCandidate *L,
10341 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +000010342 // Fast-path this check.
10343 if (L == R) return false;
10344
John McCall12f97bc2010-01-08 04:41:39 +000010345 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +000010346 if (L->Viable) {
10347 if (!R->Viable) return true;
10348
10349 // TODO: introduce a tri-valued comparison for overload
10350 // candidates. Would be more worthwhile if we had a sort
10351 // that could exploit it.
Richard Smith67ef14f2017-09-26 18:37:55 +000010352 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK))
10353 return true;
10354 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK))
10355 return false;
John McCallad2587a2010-01-12 00:48:53 +000010356 } else if (R->Viable)
10357 return false;
John McCall12f97bc2010-01-08 04:41:39 +000010358
John McCall3712d9e2010-01-15 23:32:50 +000010359 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +000010360
John McCall3712d9e2010-01-15 23:32:50 +000010361 // Criteria by which we can sort non-viable candidates:
10362 if (!L->Viable) {
10363 // 1. Arity mismatches come after other candidates.
10364 if (L->FailureKind == ovl_fail_too_many_arguments ||
Kaelyn Takatab96b3be2014-05-01 21:15:24 +000010365 L->FailureKind == ovl_fail_too_few_arguments) {
10366 if (R->FailureKind == ovl_fail_too_many_arguments ||
10367 R->FailureKind == ovl_fail_too_few_arguments) {
Kaelyn Takata50c4ffc2014-05-07 00:43:38 +000010368 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
10369 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
10370 if (LDist == RDist) {
10371 if (L->FailureKind == R->FailureKind)
10372 // Sort non-surrogates before surrogates.
10373 return !L->IsSurrogate && R->IsSurrogate;
10374 // Sort candidates requiring fewer parameters than there were
10375 // arguments given after candidates requiring more parameters
10376 // than there were arguments given.
10377 return L->FailureKind == ovl_fail_too_many_arguments;
10378 }
Kaelyn Takatab96b3be2014-05-01 21:15:24 +000010379 return LDist < RDist;
10380 }
John McCall3712d9e2010-01-15 23:32:50 +000010381 return false;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +000010382 }
John McCall3712d9e2010-01-15 23:32:50 +000010383 if (R->FailureKind == ovl_fail_too_many_arguments ||
10384 R->FailureKind == ovl_fail_too_few_arguments)
10385 return true;
John McCall12f97bc2010-01-08 04:41:39 +000010386
John McCallfe796dd2010-01-23 05:17:32 +000010387 // 2. Bad conversions come first and are ordered by the number
10388 // of bad conversions and quality of good conversions.
10389 if (L->FailureKind == ovl_fail_bad_conversion) {
10390 if (R->FailureKind != ovl_fail_bad_conversion)
10391 return true;
10392
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010393 // The conversion that can be fixed with a smaller number of changes,
10394 // comes first.
10395 unsigned numLFixes = L->Fix.NumConversionsFixed;
10396 unsigned numRFixes = R->Fix.NumConversionsFixed;
10397 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
10398 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +000010399 if (numLFixes != numRFixes) {
David Blaikie7a3cbb22015-03-09 02:02:07 +000010400 return numLFixes < numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +000010401 }
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010402
John McCallfe796dd2010-01-23 05:17:32 +000010403 // If there's any ordering between the defined conversions...
10404 // FIXME: this might not be transitive.
Richard Smith6eedfe72017-01-09 08:01:21 +000010405 assert(L->Conversions.size() == R->Conversions.size());
John McCallfe796dd2010-01-23 05:17:32 +000010406
10407 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +000010408 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Richard Smith6eedfe72017-01-09 08:01:21 +000010409 for (unsigned E = L->Conversions.size(); I != E; ++I) {
Richard Smith0f59cb32015-12-18 21:45:41 +000010410 switch (CompareImplicitConversionSequences(S, Loc,
John McCall5c32be02010-08-24 20:38:10 +000010411 L->Conversions[I],
10412 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +000010413 case ImplicitConversionSequence::Better:
10414 leftBetter++;
10415 break;
10416
10417 case ImplicitConversionSequence::Worse:
10418 leftBetter--;
10419 break;
10420
10421 case ImplicitConversionSequence::Indistinguishable:
10422 break;
10423 }
10424 }
10425 if (leftBetter > 0) return true;
10426 if (leftBetter < 0) return false;
10427
10428 } else if (R->FailureKind == ovl_fail_bad_conversion)
10429 return false;
10430
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010431 if (L->FailureKind == ovl_fail_bad_deduction) {
10432 if (R->FailureKind != ovl_fail_bad_deduction)
10433 return true;
10434
10435 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10436 return RankDeductionFailure(L->DeductionFailure)
Eli Friedman1e7a0c62011-10-14 23:10:30 +000010437 < RankDeductionFailure(R->DeductionFailure);
Eli Friedmane2c600c2011-10-14 21:52:24 +000010438 } else if (R->FailureKind == ovl_fail_bad_deduction)
10439 return false;
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010440
John McCall3712d9e2010-01-15 23:32:50 +000010441 // TODO: others?
10442 }
10443
10444 // Sort everything else by location.
10445 SourceLocation LLoc = GetLocationForCandidate(L);
10446 SourceLocation RLoc = GetLocationForCandidate(R);
10447
10448 // Put candidates without locations (e.g. builtins) at the end.
10449 if (LLoc.isInvalid()) return false;
10450 if (RLoc.isInvalid()) return true;
10451
10452 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +000010453 }
10454};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010455}
John McCall12f97bc2010-01-08 04:41:39 +000010456
John McCallfe796dd2010-01-23 05:17:32 +000010457/// CompleteNonViableCandidate - Normally, overload resolution only
Richard Smith6eedfe72017-01-09 08:01:21 +000010458/// computes up to the first bad conversion. Produces the FixIt set if
10459/// possible.
Richard Smith17c00b42014-11-12 01:24:00 +000010460static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
10461 ArrayRef<Expr *> Args) {
John McCallfe796dd2010-01-23 05:17:32 +000010462 assert(!Cand->Viable);
10463
10464 // Don't do anything on failures other than bad conversion.
10465 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
10466
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010467 // We only want the FixIts if all the arguments can be corrected.
10468 bool Unfixable = false;
Anna Zaks1b068122011-07-28 19:46:48 +000010469 // Use a implicit copy initialization to check conversion fixes.
10470 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010471
Richard Smith6eedfe72017-01-09 08:01:21 +000010472 // Attempt to fix the bad conversion.
10473 unsigned ConvCount = Cand->Conversions.size();
10474 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
10475 ++ConvIdx) {
John McCallfe796dd2010-01-23 05:17:32 +000010476 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
Richard Smith6eedfe72017-01-09 08:01:21 +000010477 if (Cand->Conversions[ConvIdx].isInitialized() &&
10478 Cand->Conversions[ConvIdx].isBad()) {
10479 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
John McCallfe796dd2010-01-23 05:17:32 +000010480 break;
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010481 }
John McCallfe796dd2010-01-23 05:17:32 +000010482 }
10483
Douglas Gregoradc7a702010-04-16 17:45:54 +000010484 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +000010485 // operation somehow.
10486 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +000010487
Richard Smith14ead302017-01-10 20:19:21 +000010488 unsigned ConvIdx = 0;
10489 ArrayRef<QualType> ParamTypes;
John McCallfe796dd2010-01-23 05:17:32 +000010490
10491 if (Cand->IsSurrogate) {
10492 QualType ConvType
10493 = Cand->Surrogate->getConversionType().getNonReferenceType();
10494 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10495 ConvType = ConvPtrType->getPointeeType();
Richard Smith14ead302017-01-10 20:19:21 +000010496 ParamTypes = ConvType->getAs<FunctionProtoType>()->getParamTypes();
10497 // Conversion 0 is 'this', which doesn't have a corresponding argument.
10498 ConvIdx = 1;
John McCallfe796dd2010-01-23 05:17:32 +000010499 } else if (Cand->Function) {
Richard Smith14ead302017-01-10 20:19:21 +000010500 ParamTypes =
10501 Cand->Function->getType()->getAs<FunctionProtoType>()->getParamTypes();
John McCallfe796dd2010-01-23 05:17:32 +000010502 if (isa<CXXMethodDecl>(Cand->Function) &&
Richard Smith14ead302017-01-10 20:19:21 +000010503 !isa<CXXConstructorDecl>(Cand->Function)) {
10504 // Conversion 0 is 'this', which doesn't have a corresponding argument.
10505 ConvIdx = 1;
Richard Smith6eedfe72017-01-09 08:01:21 +000010506 }
Richard Smith14ead302017-01-10 20:19:21 +000010507 } else {
10508 // Builtin operator.
10509 assert(ConvCount <= 3);
George Burgess IV5f6ab9a2017-06-08 20:55:21 +000010510 ParamTypes = Cand->BuiltinParamTypes;
John McCallfe796dd2010-01-23 05:17:32 +000010511 }
10512
10513 // Fill in the rest of the conversions.
Richard Smith14ead302017-01-10 20:19:21 +000010514 for (unsigned ArgIdx = 0; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Richard Smith6eedfe72017-01-09 08:01:21 +000010515 if (Cand->Conversions[ConvIdx].isInitialized()) {
Richard Smith14ead302017-01-10 20:19:21 +000010516 // We've already checked this conversion.
10517 } else if (ArgIdx < ParamTypes.size()) {
10518 if (ParamTypes[ArgIdx]->isDependentType())
Richard Smith6eedfe72017-01-09 08:01:21 +000010519 Cand->Conversions[ConvIdx].setAsIdentityConversion(
10520 Args[ArgIdx]->getType());
10521 else {
10522 Cand->Conversions[ConvIdx] =
Richard Smith14ead302017-01-10 20:19:21 +000010523 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ArgIdx],
Richard Smith6eedfe72017-01-09 08:01:21 +000010524 SuppressUserConversions,
10525 /*InOverloadResolution=*/true,
10526 /*AllowObjCWritebackConversion=*/
10527 S.getLangOpts().ObjCAutoRefCount);
10528 // Store the FixIt in the candidate if it exists.
10529 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
10530 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10531 }
10532 } else
John McCallfe796dd2010-01-23 05:17:32 +000010533 Cand->Conversions[ConvIdx].setEllipsis();
10534 }
10535}
10536
Douglas Gregor5251f1b2008-10-21 16:13:35 +000010537/// PrintOverloadCandidates - When overload resolution fails, prints
10538/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +000010539/// set.
Richard Smithb2f0f052016-10-10 18:54:32 +000010540void OverloadCandidateSet::NoteCandidates(
10541 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
10542 StringRef Opc, SourceLocation OpLoc,
10543 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
John McCall12f97bc2010-01-08 04:41:39 +000010544 // Sort the candidates by viability and position. Sorting directly would
10545 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010546 SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +000010547 if (OCD == OCD_AllCandidates) Cands.reserve(size());
10548 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
Richard Smithb2f0f052016-10-10 18:54:32 +000010549 if (!Filter(*Cand))
10550 continue;
John McCallfe796dd2010-01-23 05:17:32 +000010551 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +000010552 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +000010553 else if (OCD == OCD_AllCandidates) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010554 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010555 if (Cand->Function || Cand->IsSurrogate)
10556 Cands.push_back(Cand);
10557 // Otherwise, this a non-viable builtin candidate. We do not, in general,
10558 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +000010559 }
10560 }
10561
Mandeep Singh Grange66d2322017-11-14 00:22:24 +000010562 std::stable_sort(Cands.begin(), Cands.end(),
Richard Smith67ef14f2017-09-26 18:37:55 +000010563 CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010564
John McCall0d1da222010-01-12 00:44:57 +000010565 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +000010566
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010567 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Douglas Gregor79591782012-10-23 23:11:23 +000010568 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010569 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +000010570 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10571 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +000010572
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010573 // Set an arbitrary limit on the number of candidate functions we'll spam
10574 // the user with. FIXME: This limit should depend on details of the
10575 // candidate list.
Douglas Gregor79591782012-10-23 23:11:23 +000010576 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010577 break;
10578 }
10579 ++CandsShown;
10580
John McCalld3224162010-01-08 00:58:21 +000010581 if (Cand->Function)
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010582 NoteFunctionCandidate(S, Cand, Args.size(),
10583 /*TakingCandidateAddress=*/false);
John McCalld3224162010-01-08 00:58:21 +000010584 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +000010585 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010586 else {
10587 assert(Cand->Viable &&
10588 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +000010589 // Generally we only see ambiguities including viable builtin
10590 // operators if overload resolution got screwed up by an
10591 // ambiguous user-defined conversion.
10592 //
10593 // FIXME: It's quite possible for different conversions to see
10594 // different ambiguities, though.
10595 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +000010596 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +000010597 ReportedAmbiguousConversions = true;
10598 }
John McCalld3224162010-01-08 00:58:21 +000010599
John McCall0d1da222010-01-12 00:44:57 +000010600 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +000010601 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +000010602 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +000010603 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010604
10605 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +000010606 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +000010607}
10608
Larisse Voufo98b20f12013-07-19 23:00:19 +000010609static SourceLocation
10610GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
10611 return Cand->Specialization ? Cand->Specialization->getLocation()
10612 : SourceLocation();
10613}
10614
Richard Smith17c00b42014-11-12 01:24:00 +000010615namespace {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010616struct CompareTemplateSpecCandidatesForDisplay {
10617 Sema &S;
10618 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
10619
10620 bool operator()(const TemplateSpecCandidate *L,
10621 const TemplateSpecCandidate *R) {
10622 // Fast-path this check.
10623 if (L == R)
10624 return false;
10625
10626 // Assuming that both candidates are not matches...
10627
10628 // Sort by the ranking of deduction failures.
10629 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10630 return RankDeductionFailure(L->DeductionFailure) <
10631 RankDeductionFailure(R->DeductionFailure);
10632
10633 // Sort everything else by location.
10634 SourceLocation LLoc = GetLocationForCandidate(L);
10635 SourceLocation RLoc = GetLocationForCandidate(R);
10636
10637 // Put candidates without locations (e.g. builtins) at the end.
10638 if (LLoc.isInvalid())
10639 return false;
10640 if (RLoc.isInvalid())
10641 return true;
10642
10643 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10644 }
10645};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010646}
Larisse Voufo98b20f12013-07-19 23:00:19 +000010647
10648/// Diagnose a template argument deduction failure.
10649/// We are treating these failures as overload failures due to bad
10650/// deductions.
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010651void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
10652 bool ForTakingAddress) {
Richard Smithc2bebe92016-05-11 20:37:46 +000010653 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010654 DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010655}
10656
10657void TemplateSpecCandidateSet::destroyCandidates() {
10658 for (iterator i = begin(), e = end(); i != e; ++i) {
10659 i->DeductionFailure.Destroy();
10660 }
10661}
10662
10663void TemplateSpecCandidateSet::clear() {
10664 destroyCandidates();
10665 Candidates.clear();
10666}
10667
10668/// NoteCandidates - When no template specialization match is found, prints
10669/// diagnostic messages containing the non-matching specializations that form
10670/// the candidate set.
10671/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
10672/// OCD == OCD_AllCandidates and Cand->Viable == false.
10673void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
10674 // Sort the candidates by position (assuming no candidate is a match).
10675 // Sorting directly would be prohibitive, so we make a set of pointers
10676 // and sort those.
10677 SmallVector<TemplateSpecCandidate *, 32> Cands;
10678 Cands.reserve(size());
10679 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10680 if (Cand->Specialization)
10681 Cands.push_back(Cand);
Alp Tokerd4733632013-12-05 04:47:09 +000010682 // Otherwise, this is a non-matching builtin candidate. We do not,
Larisse Voufo98b20f12013-07-19 23:00:19 +000010683 // in general, want to list every possible builtin candidate.
10684 }
10685
10686 std::sort(Cands.begin(), Cands.end(),
10687 CompareTemplateSpecCandidatesForDisplay(S));
10688
10689 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
10690 // for generalization purposes (?).
10691 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10692
10693 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
10694 unsigned CandsShown = 0;
10695 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10696 TemplateSpecCandidate *Cand = *I;
10697
10698 // Set an arbitrary limit on the number of candidates we'll spam
10699 // the user with. FIXME: This limit should depend on details of the
10700 // candidate list.
10701 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10702 break;
10703 ++CandsShown;
10704
10705 assert(Cand->Specialization &&
10706 "Non-matching built-in candidates are not added to Cands.");
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010707 Cand->NoteDeductionFailure(S, ForTakingAddress);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010708 }
10709
10710 if (I != E)
10711 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
10712}
10713
Douglas Gregorb491ed32011-02-19 21:32:49 +000010714// [PossiblyAFunctionType] --> [Return]
10715// NonFunctionType --> NonFunctionType
10716// R (A) --> R(A)
10717// R (*)(A) --> R (A)
10718// R (&)(A) --> R (A)
10719// R (S::*)(A) --> R (A)
10720QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
10721 QualType Ret = PossiblyAFunctionType;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010722 if (const PointerType *ToTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +000010723 PossiblyAFunctionType->getAs<PointerType>())
10724 Ret = ToTypePtr->getPointeeType();
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010725 else if (const ReferenceType *ToTypeRef =
Douglas Gregorb491ed32011-02-19 21:32:49 +000010726 PossiblyAFunctionType->getAs<ReferenceType>())
10727 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +000010728 else if (const MemberPointerType *MemTypePtr =
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010729 PossiblyAFunctionType->getAs<MemberPointerType>())
10730 Ret = MemTypePtr->getPointeeType();
10731 Ret =
Douglas Gregorb491ed32011-02-19 21:32:49 +000010732 Context.getCanonicalType(Ret).getUnqualifiedType();
10733 return Ret;
10734}
Douglas Gregorcd695e52008-11-10 20:40:00 +000010735
Richard Smith9095e5b2016-11-01 01:31:23 +000010736static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
10737 bool Complain = true) {
10738 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
10739 S.DeduceReturnType(FD, Loc, Complain))
10740 return true;
10741
10742 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
Aaron Ballmanc351fba2017-12-04 20:27:34 +000010743 if (S.getLangOpts().CPlusPlus17 &&
Richard Smith9095e5b2016-11-01 01:31:23 +000010744 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
10745 !S.ResolveExceptionSpec(Loc, FPT))
10746 return true;
10747
10748 return false;
10749}
10750
Richard Smith17c00b42014-11-12 01:24:00 +000010751namespace {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010752// A helper class to help with address of function resolution
10753// - allows us to avoid passing around all those ugly parameters
Richard Smith17c00b42014-11-12 01:24:00 +000010754class AddressOfFunctionResolver {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010755 Sema& S;
10756 Expr* SourceExpr;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010757 const QualType& TargetType;
10758 QualType TargetFunctionType; // Extracted function type from target type
10759
Douglas Gregorb491ed32011-02-19 21:32:49 +000010760 bool Complain;
10761 //DeclAccessPair& ResultFunctionAccessPair;
10762 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010763
Douglas Gregorb491ed32011-02-19 21:32:49 +000010764 bool TargetTypeIsNonStaticMemberFunction;
10765 bool FoundNonTemplateFunction;
David Majnemera4f7c7a2013-08-01 06:13:59 +000010766 bool StaticMemberFunctionFromBoundPointer;
George Burgess IV5f2ef452015-10-12 18:40:58 +000010767 bool HasComplained;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010768
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010769 OverloadExpr::FindResult OvlExprInfo;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010770 OverloadExpr *OvlExpr;
10771 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010772 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Larisse Voufo98b20f12013-07-19 23:00:19 +000010773 TemplateSpecCandidateSet FailedCandidates;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010774
Douglas Gregorb491ed32011-02-19 21:32:49 +000010775public:
Larisse Voufo98b20f12013-07-19 23:00:19 +000010776 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
10777 const QualType &TargetType, bool Complain)
10778 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
10779 Complain(Complain), Context(S.getASTContext()),
10780 TargetTypeIsNonStaticMemberFunction(
10781 !!TargetType->getAs<MemberPointerType>()),
10782 FoundNonTemplateFunction(false),
David Majnemera4f7c7a2013-08-01 06:13:59 +000010783 StaticMemberFunctionFromBoundPointer(false),
George Burgess IV5f2ef452015-10-12 18:40:58 +000010784 HasComplained(false),
Larisse Voufo98b20f12013-07-19 23:00:19 +000010785 OvlExprInfo(OverloadExpr::find(SourceExpr)),
10786 OvlExpr(OvlExprInfo.Expression),
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010787 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010788 ExtractUnqualifiedFunctionTypeFromTargetType();
Chandler Carruthffce2452011-03-29 08:08:18 +000010789
David Majnemera4f7c7a2013-08-01 06:13:59 +000010790 if (TargetFunctionType->isFunctionType()) {
10791 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
10792 if (!UME->isImplicitAccess() &&
10793 !S.ResolveSingleFunctionTemplateSpecialization(UME))
10794 StaticMemberFunctionFromBoundPointer = true;
10795 } else if (OvlExpr->hasExplicitTemplateArgs()) {
10796 DeclAccessPair dap;
10797 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
10798 OvlExpr, false, &dap)) {
10799 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
10800 if (!Method->isStatic()) {
10801 // If the target type is a non-function type and the function found
10802 // is a non-static member function, pretend as if that was the
10803 // target, it's the only possible type to end up with.
10804 TargetTypeIsNonStaticMemberFunction = true;
Chandler Carruthffce2452011-03-29 08:08:18 +000010805
David Majnemera4f7c7a2013-08-01 06:13:59 +000010806 // And skip adding the function if its not in the proper form.
10807 // We'll diagnose this due to an empty set of functions.
10808 if (!OvlExprInfo.HasFormOfMemberPointer)
10809 return;
Chandler Carruthffce2452011-03-29 08:08:18 +000010810 }
10811
David Majnemera4f7c7a2013-08-01 06:13:59 +000010812 Matches.push_back(std::make_pair(dap, Fn));
Douglas Gregor9b146582009-07-08 20:55:45 +000010813 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010814 return;
Douglas Gregor9b146582009-07-08 20:55:45 +000010815 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010816
Douglas Gregorb491ed32011-02-19 21:32:49 +000010817 if (OvlExpr->hasExplicitTemplateArgs())
James Y Knight04ec5bf2015-12-24 02:59:37 +000010818 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +000010819
Douglas Gregorb491ed32011-02-19 21:32:49 +000010820 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
10821 // C++ [over.over]p4:
10822 // If more than one function is selected, [...]
George Burgess IV2a6150d2015-10-16 01:17:38 +000010823 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010824 if (FoundNonTemplateFunction)
10825 EliminateAllTemplateMatches();
10826 else
10827 EliminateAllExceptMostSpecializedTemplate();
10828 }
10829 }
Artem Belevich94a55e82015-09-22 17:22:59 +000010830
Justin Lebar25c4a812016-03-29 16:24:16 +000010831 if (S.getLangOpts().CUDA && Matches.size() > 1)
Artem Belevich94a55e82015-09-22 17:22:59 +000010832 EliminateSuboptimalCudaMatches();
Douglas Gregorb491ed32011-02-19 21:32:49 +000010833 }
George Burgess IV5f2ef452015-10-12 18:40:58 +000010834
10835 bool hasComplained() const { return HasComplained; }
10836
Douglas Gregorb491ed32011-02-19 21:32:49 +000010837private:
George Burgess IV6da4c202016-03-23 02:33:58 +000010838 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
10839 QualType Discard;
10840 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
Richard Smith3c4f8d22016-10-16 17:54:23 +000010841 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
George Burgess IV2a6150d2015-10-16 01:17:38 +000010842 }
10843
George Burgess IV6da4c202016-03-23 02:33:58 +000010844 /// \return true if A is considered a better overload candidate for the
10845 /// desired type than B.
10846 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
10847 // If A doesn't have exactly the correct type, we don't want to classify it
10848 // as "better" than anything else. This way, the user is required to
10849 // disambiguate for us if there are multiple candidates and no exact match.
10850 return candidateHasExactlyCorrectType(A) &&
10851 (!candidateHasExactlyCorrectType(B) ||
George Burgess IV3dc166912016-05-10 01:59:34 +000010852 compareEnableIfAttrs(S, A, B) == Comparison::Better);
George Burgess IV6da4c202016-03-23 02:33:58 +000010853 }
10854
10855 /// \return true if we were able to eliminate all but one overload candidate,
10856 /// false otherwise.
George Burgess IV2a6150d2015-10-16 01:17:38 +000010857 bool eliminiateSuboptimalOverloadCandidates() {
10858 // Same algorithm as overload resolution -- one pass to pick the "best",
10859 // another pass to be sure that nothing is better than the best.
10860 auto Best = Matches.begin();
10861 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
10862 if (isBetterCandidate(I->second, Best->second))
10863 Best = I;
10864
10865 const FunctionDecl *BestFn = Best->second;
10866 auto IsBestOrInferiorToBest = [this, BestFn](
10867 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
10868 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
10869 };
10870
10871 // Note: We explicitly leave Matches unmodified if there isn't a clear best
10872 // option, so we can potentially give the user a better error
10873 if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest))
10874 return false;
10875 Matches[0] = *Best;
10876 Matches.resize(1);
10877 return true;
10878 }
10879
Douglas Gregorb491ed32011-02-19 21:32:49 +000010880 bool isTargetTypeAFunction() const {
10881 return TargetFunctionType->isFunctionType();
10882 }
10883
10884 // [ToType] [Return]
10885
10886 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
10887 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
10888 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
10889 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
10890 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
10891 }
10892
10893 // return true if any matching specializations were found
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010894 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
Douglas Gregorb491ed32011-02-19 21:32:49 +000010895 const DeclAccessPair& CurAccessFunPair) {
10896 if (CXXMethodDecl *Method
10897 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
10898 // Skip non-static function templates when converting to pointer, and
10899 // static when converting to member pointer.
10900 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10901 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010902 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010903 else if (TargetTypeIsNonStaticMemberFunction)
10904 return false;
10905
10906 // C++ [over.over]p2:
10907 // If the name is a function template, template argument deduction is
10908 // done (14.8.2.2), and if the argument deduction succeeds, the
10909 // resulting template argument list is used to generate a single
10910 // function template specialization, which is added to the set of
10911 // overloaded functions considered.
Craig Topperc3ec1492014-05-26 06:22:03 +000010912 FunctionDecl *Specialization = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +000010913 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregorb491ed32011-02-19 21:32:49 +000010914 if (Sema::TemplateDeductionResult Result
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010915 = S.DeduceTemplateArguments(FunctionTemplate,
Douglas Gregorb491ed32011-02-19 21:32:49 +000010916 &OvlExplicitTemplateArgs,
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010917 TargetFunctionType, Specialization,
Richard Smithbaa47832016-12-01 02:11:49 +000010918 Info, /*IsAddressOfFunction*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010919 // Make a note of the failed deduction for diagnostics.
10920 FailedCandidates.addCandidate()
Richard Smithc2bebe92016-05-11 20:37:46 +000010921 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
Larisse Voufo98b20f12013-07-19 23:00:19 +000010922 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregorb491ed32011-02-19 21:32:49 +000010923 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010924 }
10925
Douglas Gregor19a41f12013-04-17 08:45:07 +000010926 // Template argument deduction ensures that we have an exact match or
10927 // compatible pointer-to-function arguments that would be adjusted by ICS.
Douglas Gregorb491ed32011-02-19 21:32:49 +000010928 // This function template specicalization works.
Douglas Gregor19a41f12013-04-17 08:45:07 +000010929 assert(S.isSameOrCompatibleFunctionType(
10930 Context.getCanonicalType(Specialization->getType()),
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010931 Context.getCanonicalType(TargetFunctionType)));
George Burgess IV5f21c712015-10-12 19:57:04 +000010932
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010933 if (!S.checkAddressOfFunctionIsAvailable(Specialization))
George Burgess IV5f21c712015-10-12 19:57:04 +000010934 return false;
10935
Douglas Gregorb491ed32011-02-19 21:32:49 +000010936 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
10937 return true;
10938 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010939
10940 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
Douglas Gregorb491ed32011-02-19 21:32:49 +000010941 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +000010942 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +000010943 // Skip non-static functions when converting to pointer, and static
10944 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +000010945 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10946 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010947 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010948 else if (TargetTypeIsNonStaticMemberFunction)
10949 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010950
Chandler Carruthc25c6ee2009-12-29 06:17:27 +000010951 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000010952 if (S.getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010953 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
Justin Lebarb0080032016-08-10 01:09:11 +000010954 if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010955 return false;
Erich Keane281d20b2018-01-08 21:34:17 +000010956 if (FunDecl->isMultiVersion()) {
10957 const auto *TA = FunDecl->getAttr<TargetAttr>();
10958 assert(TA && "Multiversioned functions require a target attribute");
10959 if (!TA->isDefaultVersion())
10960 return false;
10961 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010962
Richard Smith2a7d4812013-05-04 07:00:32 +000010963 // If any candidate has a placeholder return type, trigger its deduction
10964 // now.
Richard Smith9095e5b2016-11-01 01:31:23 +000010965 if (completeFunctionType(S, FunDecl, SourceExpr->getLocStart(),
10966 Complain)) {
George Burgess IV5f2ef452015-10-12 18:40:58 +000010967 HasComplained |= Complain;
Richard Smith2a7d4812013-05-04 07:00:32 +000010968 return false;
George Burgess IV5f2ef452015-10-12 18:40:58 +000010969 }
Richard Smith2a7d4812013-05-04 07:00:32 +000010970
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010971 if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
George Burgess IV5f21c712015-10-12 19:57:04 +000010972 return false;
10973
George Burgess IV6da4c202016-03-23 02:33:58 +000010974 // If we're in C, we need to support types that aren't exactly identical.
10975 if (!S.getLangOpts().CPlusPlus ||
10976 candidateHasExactlyCorrectType(FunDecl)) {
George Burgess IV5f21c712015-10-12 19:57:04 +000010977 Matches.push_back(std::make_pair(
10978 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +000010979 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010980 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +000010981 }
Mike Stump11289f42009-09-09 15:08:12 +000010982 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010983
Douglas Gregorb491ed32011-02-19 21:32:49 +000010984 return false;
10985 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010986
Douglas Gregorb491ed32011-02-19 21:32:49 +000010987 bool FindAllFunctionsThatMatchTargetTypeExactly() {
10988 bool Ret = false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010989
Douglas Gregorb491ed32011-02-19 21:32:49 +000010990 // If the overload expression doesn't have the form of a pointer to
10991 // member, don't try to convert it to a pointer-to-member type.
10992 if (IsInvalidFormOfPointerToMemberFunction())
10993 return false;
10994
10995 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010996 E = OvlExpr->decls_end();
Douglas Gregorb491ed32011-02-19 21:32:49 +000010997 I != E; ++I) {
10998 // Look through any using declarations to find the underlying function.
10999 NamedDecl *Fn = (*I)->getUnderlyingDecl();
11000
11001 // C++ [over.over]p3:
11002 // Non-member functions and static member functions match
11003 // targets of type "pointer-to-function" or "reference-to-function."
11004 // Nonstatic member functions match targets of
11005 // type "pointer-to-member-function."
11006 // Note that according to DR 247, the containing class does not matter.
11007 if (FunctionTemplateDecl *FunctionTemplate
11008 = dyn_cast<FunctionTemplateDecl>(Fn)) {
11009 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
11010 Ret = true;
11011 }
11012 // If we have explicit template arguments supplied, skip non-templates.
11013 else if (!OvlExpr->hasExplicitTemplateArgs() &&
11014 AddMatchingNonTemplateFunction(Fn, I.getPair()))
11015 Ret = true;
11016 }
11017 assert(Ret || Matches.empty());
11018 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +000011019 }
11020
Douglas Gregorb491ed32011-02-19 21:32:49 +000011021 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +000011022 // [...] and any given function template specialization F1 is
11023 // eliminated if the set contains a second function template
11024 // specialization whose function template is more specialized
11025 // than the function template of F1 according to the partial
11026 // ordering rules of 14.5.5.2.
11027
11028 // The algorithm specified above is quadratic. We instead use a
11029 // two-pass algorithm (similar to the one used to identify the
11030 // best viable function in an overload set) that identifies the
11031 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +000011032
11033 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
11034 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
11035 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011036
Larisse Voufo98b20f12013-07-19 23:00:19 +000011037 // TODO: It looks like FailedCandidates does not serve much purpose
11038 // here, since the no_viable diagnostic has index 0.
11039 UnresolvedSetIterator Result = S.getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +000011040 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +000011041 SourceExpr->getLocStart(), S.PDiag(),
Richard Smith5179eb72016-06-28 19:03:57 +000011042 S.PDiag(diag::err_addr_ovl_ambiguous)
11043 << Matches[0].second->getDeclName(),
11044 S.PDiag(diag::note_ovl_candidate)
11045 << (unsigned)oc_function_template,
Larisse Voufo98b20f12013-07-19 23:00:19 +000011046 Complain, TargetFunctionType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011047
Douglas Gregorb491ed32011-02-19 21:32:49 +000011048 if (Result != MatchesCopy.end()) {
11049 // Make it the first and only element
11050 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
11051 Matches[0].second = cast<FunctionDecl>(*Result);
11052 Matches.resize(1);
George Burgess IV5f2ef452015-10-12 18:40:58 +000011053 } else
11054 HasComplained |= Complain;
John McCall58cc69d2010-01-27 01:50:18 +000011055 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011056
Douglas Gregorb491ed32011-02-19 21:32:49 +000011057 void EliminateAllTemplateMatches() {
11058 // [...] any function template specializations in the set are
11059 // eliminated if the set also contains a non-template function, [...]
11060 for (unsigned I = 0, N = Matches.size(); I != N; ) {
Craig Topperc3ec1492014-05-26 06:22:03 +000011061 if (Matches[I].second->getPrimaryTemplate() == nullptr)
Douglas Gregorb491ed32011-02-19 21:32:49 +000011062 ++I;
11063 else {
11064 Matches[I] = Matches[--N];
Artem Belevich94a55e82015-09-22 17:22:59 +000011065 Matches.resize(N);
Douglas Gregorb491ed32011-02-19 21:32:49 +000011066 }
11067 }
11068 }
11069
Artem Belevich94a55e82015-09-22 17:22:59 +000011070 void EliminateSuboptimalCudaMatches() {
11071 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
11072 }
11073
Douglas Gregorb491ed32011-02-19 21:32:49 +000011074public:
11075 void ComplainNoMatchesFound() const {
11076 assert(Matches.empty());
11077 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
11078 << OvlExpr->getName() << TargetFunctionType
11079 << OvlExpr->getSourceRange();
Richard Smith0d905472013-08-14 00:00:44 +000011080 if (FailedCandidates.empty())
George Burgess IV5f21c712015-10-12 19:57:04 +000011081 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11082 /*TakingAddress=*/true);
Richard Smith0d905472013-08-14 00:00:44 +000011083 else {
11084 // We have some deduction failure messages. Use them to diagnose
11085 // the function templates, and diagnose the non-template candidates
11086 // normally.
11087 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11088 IEnd = OvlExpr->decls_end();
11089 I != IEnd; ++I)
11090 if (FunctionDecl *Fun =
11091 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011092 if (!functionHasPassObjectSizeParams(Fun))
Richard Smithc2bebe92016-05-11 20:37:46 +000011093 S.NoteOverloadCandidate(*I, Fun, TargetFunctionType,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011094 /*TakingAddress=*/true);
Richard Smith0d905472013-08-14 00:00:44 +000011095 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
11096 }
11097 }
11098
Douglas Gregorb491ed32011-02-19 21:32:49 +000011099 bool IsInvalidFormOfPointerToMemberFunction() const {
11100 return TargetTypeIsNonStaticMemberFunction &&
11101 !OvlExprInfo.HasFormOfMemberPointer;
11102 }
David Majnemera4f7c7a2013-08-01 06:13:59 +000011103
Douglas Gregorb491ed32011-02-19 21:32:49 +000011104 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
11105 // TODO: Should we condition this on whether any functions might
11106 // have matched, or is it more appropriate to do that in callers?
11107 // TODO: a fixit wouldn't hurt.
11108 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
11109 << TargetType << OvlExpr->getSourceRange();
11110 }
David Majnemera4f7c7a2013-08-01 06:13:59 +000011111
11112 bool IsStaticMemberFunctionFromBoundPointer() const {
11113 return StaticMemberFunctionFromBoundPointer;
11114 }
11115
11116 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
11117 S.Diag(OvlExpr->getLocStart(),
11118 diag::err_invalid_form_pointer_member_function)
11119 << OvlExpr->getSourceRange();
11120 }
11121
Douglas Gregorb491ed32011-02-19 21:32:49 +000011122 void ComplainOfInvalidConversion() const {
11123 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
11124 << OvlExpr->getName() << TargetType;
11125 }
11126
11127 void ComplainMultipleMatchesFound() const {
11128 assert(Matches.size() > 1);
11129 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
11130 << OvlExpr->getName()
11131 << OvlExpr->getSourceRange();
George Burgess IV5f21c712015-10-12 19:57:04 +000011132 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11133 /*TakingAddress=*/true);
Douglas Gregorb491ed32011-02-19 21:32:49 +000011134 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +000011135
11136 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
11137
Douglas Gregorb491ed32011-02-19 21:32:49 +000011138 int getNumMatches() const { return Matches.size(); }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011139
Douglas Gregorb491ed32011-02-19 21:32:49 +000011140 FunctionDecl* getMatchingFunctionDecl() const {
Craig Topperc3ec1492014-05-26 06:22:03 +000011141 if (Matches.size() != 1) return nullptr;
Douglas Gregorb491ed32011-02-19 21:32:49 +000011142 return Matches[0].second;
11143 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011144
Douglas Gregorb491ed32011-02-19 21:32:49 +000011145 const DeclAccessPair* getMatchingFunctionAccessPair() const {
Craig Topperc3ec1492014-05-26 06:22:03 +000011146 if (Matches.size() != 1) return nullptr;
Douglas Gregorb491ed32011-02-19 21:32:49 +000011147 return &Matches[0].first;
11148 }
11149};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000011150}
Richard Smith17c00b42014-11-12 01:24:00 +000011151
Douglas Gregorb491ed32011-02-19 21:32:49 +000011152/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
11153/// an overloaded function (C++ [over.over]), where @p From is an
11154/// expression with overloaded function type and @p ToType is the type
11155/// we're trying to resolve to. For example:
11156///
11157/// @code
11158/// int f(double);
11159/// int f(int);
11160///
11161/// int (*pfd)(double) = f; // selects f(double)
11162/// @endcode
11163///
11164/// This routine returns the resulting FunctionDecl if it could be
11165/// resolved, and NULL otherwise. When @p Complain is true, this
11166/// routine will emit diagnostics if there is an error.
11167FunctionDecl *
Abramo Bagnara5001caa2011-11-19 11:44:21 +000011168Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
11169 QualType TargetType,
11170 bool Complain,
11171 DeclAccessPair &FoundResult,
11172 bool *pHadMultipleCandidates) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000011173 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara5001caa2011-11-19 11:44:21 +000011174
11175 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
11176 Complain);
Douglas Gregorb491ed32011-02-19 21:32:49 +000011177 int NumMatches = Resolver.getNumMatches();
Craig Topperc3ec1492014-05-26 06:22:03 +000011178 FunctionDecl *Fn = nullptr;
George Burgess IV5f2ef452015-10-12 18:40:58 +000011179 bool ShouldComplain = Complain && !Resolver.hasComplained();
11180 if (NumMatches == 0 && ShouldComplain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000011181 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
11182 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
11183 else
11184 Resolver.ComplainNoMatchesFound();
11185 }
George Burgess IV5f2ef452015-10-12 18:40:58 +000011186 else if (NumMatches > 1 && ShouldComplain)
Douglas Gregorb491ed32011-02-19 21:32:49 +000011187 Resolver.ComplainMultipleMatchesFound();
11188 else if (NumMatches == 1) {
11189 Fn = Resolver.getMatchingFunctionDecl();
11190 assert(Fn);
Richard Smith9095e5b2016-11-01 01:31:23 +000011191 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
11192 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
Douglas Gregorb491ed32011-02-19 21:32:49 +000011193 FoundResult = *Resolver.getMatchingFunctionAccessPair();
David Majnemera4f7c7a2013-08-01 06:13:59 +000011194 if (Complain) {
11195 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
11196 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
11197 else
11198 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
11199 }
Sebastian Redldf4b80e2009-10-17 21:12:09 +000011200 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +000011201
11202 if (pHadMultipleCandidates)
11203 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregorb491ed32011-02-19 21:32:49 +000011204 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +000011205}
11206
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011207/// \brief Given an expression that refers to an overloaded function, try to
George Burgess IV3cde9bf2016-03-19 21:36:10 +000011208/// resolve that function to a single function that can have its address taken.
11209/// This will modify `Pair` iff it returns non-null.
11210///
11211/// This routine can only realistically succeed if all but one candidates in the
11212/// overload set for SrcExpr cannot have their addresses taken.
11213FunctionDecl *
11214Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
11215 DeclAccessPair &Pair) {
11216 OverloadExpr::FindResult R = OverloadExpr::find(E);
11217 OverloadExpr *Ovl = R.Expression;
11218 FunctionDecl *Result = nullptr;
11219 DeclAccessPair DAP;
11220 // Don't use the AddressOfResolver because we're specifically looking for
11221 // cases where we have one overload candidate that lacks
11222 // enable_if/pass_object_size/...
11223 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
11224 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
11225 if (!FD)
11226 return nullptr;
11227
11228 if (!checkAddressOfFunctionIsAvailable(FD))
11229 continue;
11230
11231 // We have more than one result; quit.
11232 if (Result)
11233 return nullptr;
11234 DAP = I.getPair();
11235 Result = FD;
11236 }
11237
11238 if (Result)
11239 Pair = DAP;
11240 return Result;
11241}
11242
George Burgess IVbeca4a32016-06-08 00:34:22 +000011243/// \brief Given an overloaded function, tries to turn it into a non-overloaded
11244/// function reference using resolveAddressOfOnlyViableOverloadCandidate. This
11245/// will perform access checks, diagnose the use of the resultant decl, and, if
George Burgess IV1dbfa852017-05-09 04:06:24 +000011246/// requested, potentially perform a function-to-pointer decay.
George Burgess IVbeca4a32016-06-08 00:34:22 +000011247///
11248/// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails.
11249/// Otherwise, returns true. This may emit diagnostics and return true.
11250bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate(
George Burgess IV1dbfa852017-05-09 04:06:24 +000011251 ExprResult &SrcExpr, bool DoFunctionPointerConverion) {
George Burgess IVbeca4a32016-06-08 00:34:22 +000011252 Expr *E = SrcExpr.get();
11253 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
11254
11255 DeclAccessPair DAP;
11256 FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP);
11257 if (!Found)
11258 return false;
11259
11260 // Emitting multiple diagnostics for a function that is both inaccessible and
11261 // unavailable is consistent with our behavior elsewhere. So, always check
11262 // for both.
11263 DiagnoseUseOfDecl(Found, E->getExprLoc());
11264 CheckAddressOfMemberAccess(E, DAP);
11265 Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
George Burgess IV1dbfa852017-05-09 04:06:24 +000011266 if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType())
George Burgess IVbeca4a32016-06-08 00:34:22 +000011267 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
11268 else
11269 SrcExpr = Fixed;
11270 return true;
11271}
11272
George Burgess IV3cde9bf2016-03-19 21:36:10 +000011273/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011274/// resolve that overloaded function expression down to a single function.
11275///
11276/// This routine can only resolve template-ids that refer to a single function
11277/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011278/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011279/// as described in C++0x [temp.arg.explicit]p3.
Alp Toker67b47ac2013-10-20 18:48:56 +000011280///
11281/// If no template-ids are found, no diagnostics are emitted and NULL is
11282/// returned.
John McCall0009fcc2011-04-26 20:42:42 +000011283FunctionDecl *
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011284Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
John McCall0009fcc2011-04-26 20:42:42 +000011285 bool Complain,
11286 DeclAccessPair *FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011287 // C++ [over.over]p1:
11288 // [...] [Note: any redundant set of parentheses surrounding the
11289 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011290 // C++ [over.over]p1:
11291 // [...] The overloaded function name can be preceded by the &
11292 // operator.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011293
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011294 // If we didn't actually find any template-ids, we're done.
John McCall0009fcc2011-04-26 20:42:42 +000011295 if (!ovl->hasExplicitTemplateArgs())
Craig Topperc3ec1492014-05-26 06:22:03 +000011296 return nullptr;
John McCall1acbbb52010-02-02 06:20:04 +000011297
11298 TemplateArgumentListInfo ExplicitTemplateArgs;
James Y Knight04ec5bf2015-12-24 02:59:37 +000011299 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
Larisse Voufo98b20f12013-07-19 23:00:19 +000011300 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011301
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011302 // Look through all of the overloaded functions, searching for one
11303 // whose type matches exactly.
Craig Topperc3ec1492014-05-26 06:22:03 +000011304 FunctionDecl *Matched = nullptr;
John McCall0009fcc2011-04-26 20:42:42 +000011305 for (UnresolvedSetIterator I = ovl->decls_begin(),
11306 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011307 // C++0x [temp.arg.explicit]p3:
11308 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011309 // where deduction is not done, if a template argument list is
11310 // specified and it, along with any default template arguments,
11311 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011312 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +000011313 FunctionTemplateDecl *FunctionTemplate
11314 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011315
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011316 // C++ [over.over]p2:
11317 // If the name is a function template, template argument deduction is
11318 // done (14.8.2.2), and if the argument deduction succeeds, the
11319 // resulting template argument list is used to generate a single
11320 // function template specialization, which is added to the set of
11321 // overloaded functions considered.
Craig Topperc3ec1492014-05-26 06:22:03 +000011322 FunctionDecl *Specialization = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +000011323 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011324 if (TemplateDeductionResult Result
11325 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
Douglas Gregor19a41f12013-04-17 08:45:07 +000011326 Specialization, Info,
Richard Smithbaa47832016-12-01 02:11:49 +000011327 /*IsAddressOfFunction*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000011328 // Make a note of the failed deduction for diagnostics.
11329 // TODO: Actually use the failed-deduction info?
11330 FailedCandidates.addCandidate()
Richard Smithc2bebe92016-05-11 20:37:46 +000011331 .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
Larisse Voufo98b20f12013-07-19 23:00:19 +000011332 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011333 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011334 }
11335
John McCall0009fcc2011-04-26 20:42:42 +000011336 assert(Specialization && "no specialization and no error?");
11337
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011338 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +000011339 if (Matched) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000011340 if (Complain) {
John McCall0009fcc2011-04-26 20:42:42 +000011341 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
11342 << ovl->getName();
11343 NoteAllOverloadCandidates(ovl);
Douglas Gregorb491ed32011-02-19 21:32:49 +000011344 }
Craig Topperc3ec1492014-05-26 06:22:03 +000011345 return nullptr;
John McCall0009fcc2011-04-26 20:42:42 +000011346 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011347
John McCall0009fcc2011-04-26 20:42:42 +000011348 Matched = Specialization;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011349 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011350 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011351
Richard Smith9095e5b2016-11-01 01:31:23 +000011352 if (Matched &&
11353 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
Craig Topperc3ec1492014-05-26 06:22:03 +000011354 return nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +000011355
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011356 return Matched;
11357}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011358
John McCall50a2c2c2011-10-11 23:14:30 +000011359// Resolve and fix an overloaded expression that can be resolved
11360// because it identifies a single function template specialization.
11361//
Douglas Gregor1beec452011-03-12 01:48:56 +000011362// Last three arguments should only be supplied if Complain = true
John McCall50a2c2c2011-10-11 23:14:30 +000011363//
11364// Return true if it was logically possible to so resolve the
11365// expression, regardless of whether or not it succeeded. Always
11366// returns true if 'complain' is set.
11367bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
11368 ExprResult &SrcExpr, bool doFunctionPointerConverion,
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011369 bool complain, SourceRange OpRangeForComplaining,
11370 QualType DestTypeForComplaining,
John McCall0009fcc2011-04-26 20:42:42 +000011371 unsigned DiagIDForComplaining) {
John McCall50a2c2c2011-10-11 23:14:30 +000011372 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregor1beec452011-03-12 01:48:56 +000011373
John McCall50a2c2c2011-10-11 23:14:30 +000011374 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregor1beec452011-03-12 01:48:56 +000011375
John McCall0009fcc2011-04-26 20:42:42 +000011376 DeclAccessPair found;
11377 ExprResult SingleFunctionExpression;
11378 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
11379 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011380 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall50a2c2c2011-10-11 23:14:30 +000011381 SrcExpr = ExprError();
11382 return true;
11383 }
John McCall0009fcc2011-04-26 20:42:42 +000011384
11385 // It is only correct to resolve to an instance method if we're
11386 // resolving a form that's permitted to be a pointer to member.
11387 // Otherwise we'll end up making a bound member expression, which
11388 // is illegal in all the contexts we resolve like this.
11389 if (!ovl.HasFormOfMemberPointer &&
11390 isa<CXXMethodDecl>(fn) &&
11391 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall50a2c2c2011-10-11 23:14:30 +000011392 if (!complain) return false;
11393
11394 Diag(ovl.Expression->getExprLoc(),
11395 diag::err_bound_member_function)
11396 << 0 << ovl.Expression->getSourceRange();
11397
11398 // TODO: I believe we only end up here if there's a mix of
11399 // static and non-static candidates (otherwise the expression
11400 // would have 'bound member' type, not 'overload' type).
11401 // Ideally we would note which candidate was chosen and why
11402 // the static candidates were rejected.
11403 SrcExpr = ExprError();
11404 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000011405 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +000011406
Sylvestre Ledrua5202662012-07-31 06:56:50 +000011407 // Fix the expression to refer to 'fn'.
John McCall0009fcc2011-04-26 20:42:42 +000011408 SingleFunctionExpression =
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011409 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
John McCall0009fcc2011-04-26 20:42:42 +000011410
11411 // If desired, do function-to-pointer decay.
John McCall50a2c2c2011-10-11 23:14:30 +000011412 if (doFunctionPointerConverion) {
John McCall0009fcc2011-04-26 20:42:42 +000011413 SingleFunctionExpression =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011414 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
John McCall50a2c2c2011-10-11 23:14:30 +000011415 if (SingleFunctionExpression.isInvalid()) {
11416 SrcExpr = ExprError();
11417 return true;
11418 }
11419 }
John McCall0009fcc2011-04-26 20:42:42 +000011420 }
11421
11422 if (!SingleFunctionExpression.isUsable()) {
11423 if (complain) {
11424 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
11425 << ovl.Expression->getName()
11426 << DestTypeForComplaining
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011427 << OpRangeForComplaining
John McCall0009fcc2011-04-26 20:42:42 +000011428 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall50a2c2c2011-10-11 23:14:30 +000011429 NoteAllOverloadCandidates(SrcExpr.get());
11430
11431 SrcExpr = ExprError();
11432 return true;
11433 }
11434
11435 return false;
John McCall0009fcc2011-04-26 20:42:42 +000011436 }
11437
John McCall50a2c2c2011-10-11 23:14:30 +000011438 SrcExpr = SingleFunctionExpression;
11439 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000011440}
11441
Douglas Gregorcabea402009-09-22 15:41:20 +000011442/// \brief Add a single candidate to the overload set.
11443static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +000011444 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +000011445 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011446 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000011447 OverloadCandidateSet &CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +000011448 bool PartialOverloading,
11449 bool KnownValid) {
John McCalla0296f72010-03-19 07:35:19 +000011450 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +000011451 if (isa<UsingShadowDecl>(Callee))
11452 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
11453
Douglas Gregorcabea402009-09-22 15:41:20 +000011454 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith95ce4f62011-06-26 22:19:54 +000011455 if (ExplicitTemplateArgs) {
11456 assert(!KnownValid && "Explicit template arguments?");
11457 return;
11458 }
Bruno Cardoso Lopes37029632017-04-26 20:13:45 +000011459 // Prevent ill-formed function decls to be added as overload candidates.
11460 if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
11461 return;
11462
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011463 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
11464 /*SuppressUsedConversions=*/false,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011465 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000011466 return;
John McCalld14a8642009-11-21 08:51:07 +000011467 }
11468
11469 if (FunctionTemplateDecl *FuncTemplate
11470 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +000011471 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011472 ExplicitTemplateArgs, Args, CandidateSet,
11473 /*SuppressUsedConversions=*/false,
11474 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +000011475 return;
11476 }
11477
Richard Smith95ce4f62011-06-26 22:19:54 +000011478 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregorcabea402009-09-22 15:41:20 +000011479}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011480
Douglas Gregorcabea402009-09-22 15:41:20 +000011481/// \brief Add the overload candidates named by callee and/or found by argument
11482/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +000011483void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011484 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000011485 OverloadCandidateSet &CandidateSet,
11486 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +000011487
11488#ifndef NDEBUG
11489 // Verify that ArgumentDependentLookup is consistent with the rules
11490 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +000011491 //
Douglas Gregorcabea402009-09-22 15:41:20 +000011492 // Let X be the lookup set produced by unqualified lookup (3.4.1)
11493 // and let Y be the lookup set produced by argument dependent
11494 // lookup (defined as follows). If X contains
11495 //
11496 // -- a declaration of a class member, or
11497 //
11498 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +000011499 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +000011500 //
11501 // -- a declaration that is neither a function or a function
11502 // template
11503 //
11504 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +000011505
John McCall57500772009-12-16 12:17:52 +000011506 if (ULE->requiresADL()) {
11507 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11508 E = ULE->decls_end(); I != E; ++I) {
11509 assert(!(*I)->getDeclContext()->isRecord());
11510 assert(isa<UsingShadowDecl>(*I) ||
11511 !(*I)->getDeclContext()->isFunctionOrMethod());
11512 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +000011513 }
11514 }
11515#endif
11516
John McCall57500772009-12-16 12:17:52 +000011517 // It would be nice to avoid this copy.
11518 TemplateArgumentListInfo TABuffer;
Craig Topperc3ec1492014-05-26 06:22:03 +000011519 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
John McCall57500772009-12-16 12:17:52 +000011520 if (ULE->hasExplicitTemplateArgs()) {
11521 ULE->copyTemplateArgumentsInto(TABuffer);
11522 ExplicitTemplateArgs = &TABuffer;
11523 }
11524
11525 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11526 E = ULE->decls_end(); I != E; ++I)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011527 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
11528 CandidateSet, PartialOverloading,
11529 /*KnownValid*/ true);
John McCalld14a8642009-11-21 08:51:07 +000011530
John McCall57500772009-12-16 12:17:52 +000011531 if (ULE->requiresADL())
Richard Smith100b24a2014-04-17 01:52:14 +000011532 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011533 Args, ExplicitTemplateArgs,
Richard Smithb6626742012-10-18 17:56:02 +000011534 CandidateSet, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000011535}
John McCalld681c392009-12-16 08:11:27 +000011536
Richard Smith0603bbb2013-06-12 22:56:54 +000011537/// Determine whether a declaration with the specified name could be moved into
11538/// a different namespace.
11539static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
11540 switch (Name.getCXXOverloadedOperator()) {
11541 case OO_New: case OO_Array_New:
11542 case OO_Delete: case OO_Array_Delete:
11543 return false;
11544
11545 default:
11546 return true;
11547 }
11548}
11549
Richard Smith998a5912011-06-05 22:42:48 +000011550/// Attempt to recover from an ill-formed use of a non-dependent name in a
11551/// template, where the non-dependent name was declared after the template
11552/// was defined. This is common in code written for a compilers which do not
11553/// correctly implement two-stage name lookup.
11554///
11555/// Returns true if a viable candidate was found and a diagnostic was issued.
11556static bool
11557DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
11558 const CXXScopeSpec &SS, LookupResult &R,
Richard Smith100b24a2014-04-17 01:52:14 +000011559 OverloadCandidateSet::CandidateSetKind CSK,
Richard Smith998a5912011-06-05 22:42:48 +000011560 TemplateArgumentListInfo *ExplicitTemplateArgs,
Hans Wennborg64937c62015-06-11 21:21:57 +000011561 ArrayRef<Expr *> Args,
11562 bool *DoDiagnoseEmptyLookup = nullptr) {
Richard Smith51ec0cf2017-02-21 01:17:38 +000011563 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
Richard Smith998a5912011-06-05 22:42:48 +000011564 return false;
11565
11566 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewyckyfcd5e7a2012-03-14 20:41:00 +000011567 if (DC->isTransparentContext())
11568 continue;
11569
Richard Smith998a5912011-06-05 22:42:48 +000011570 SemaRef.LookupQualifiedName(R, DC);
11571
11572 if (!R.empty()) {
11573 R.suppressDiagnostics();
11574
11575 if (isa<CXXRecordDecl>(DC)) {
11576 // Don't diagnose names we find in classes; we get much better
11577 // diagnostics for these from DiagnoseEmptyLookup.
11578 R.clear();
Hans Wennborg64937c62015-06-11 21:21:57 +000011579 if (DoDiagnoseEmptyLookup)
11580 *DoDiagnoseEmptyLookup = true;
Richard Smith998a5912011-06-05 22:42:48 +000011581 return false;
11582 }
11583
Richard Smith100b24a2014-04-17 01:52:14 +000011584 OverloadCandidateSet Candidates(FnLoc, CSK);
Richard Smith998a5912011-06-05 22:42:48 +000011585 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
11586 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011587 ExplicitTemplateArgs, Args,
Richard Smith95ce4f62011-06-26 22:19:54 +000011588 Candidates, false, /*KnownValid*/ false);
Richard Smith998a5912011-06-05 22:42:48 +000011589
11590 OverloadCandidateSet::iterator Best;
Richard Smith95ce4f62011-06-26 22:19:54 +000011591 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smith998a5912011-06-05 22:42:48 +000011592 // No viable functions. Don't bother the user with notes for functions
11593 // which don't work and shouldn't be found anyway.
Richard Smith95ce4f62011-06-26 22:19:54 +000011594 R.clear();
Richard Smith998a5912011-06-05 22:42:48 +000011595 return false;
Richard Smith95ce4f62011-06-26 22:19:54 +000011596 }
Richard Smith998a5912011-06-05 22:42:48 +000011597
11598 // Find the namespaces where ADL would have looked, and suggest
11599 // declaring the function there instead.
11600 Sema::AssociatedNamespaceSet AssociatedNamespaces;
11601 Sema::AssociatedClassSet AssociatedClasses;
John McCall7d8b0412012-08-24 20:38:34 +000011602 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
Richard Smith998a5912011-06-05 22:42:48 +000011603 AssociatedNamespaces,
11604 AssociatedClasses);
Chandler Carruthd50f1692011-06-05 23:36:55 +000011605 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smith0603bbb2013-06-12 22:56:54 +000011606 if (canBeDeclaredInNamespace(R.getLookupName())) {
11607 DeclContext *Std = SemaRef.getStdNamespace();
11608 for (Sema::AssociatedNamespaceSet::iterator
11609 it = AssociatedNamespaces.begin(),
11610 end = AssociatedNamespaces.end(); it != end; ++it) {
11611 // Never suggest declaring a function within namespace 'std'.
11612 if (Std && Std->Encloses(*it))
11613 continue;
Richard Smith21bae432012-12-22 02:46:14 +000011614
Richard Smith0603bbb2013-06-12 22:56:54 +000011615 // Never suggest declaring a function within a namespace with a
11616 // reserved name, like __gnu_cxx.
11617 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
11618 if (NS &&
11619 NS->getQualifiedNameAsString().find("__") != std::string::npos)
11620 continue;
11621
11622 SuggestedNamespaces.insert(*it);
11623 }
Richard Smith998a5912011-06-05 22:42:48 +000011624 }
11625
11626 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
11627 << R.getLookupName();
Chandler Carruthd50f1692011-06-05 23:36:55 +000011628 if (SuggestedNamespaces.empty()) {
Richard Smith998a5912011-06-05 22:42:48 +000011629 SemaRef.Diag(Best->Function->getLocation(),
11630 diag::note_not_found_by_two_phase_lookup)
11631 << R.getLookupName() << 0;
Chandler Carruthd50f1692011-06-05 23:36:55 +000011632 } else if (SuggestedNamespaces.size() == 1) {
Richard Smith998a5912011-06-05 22:42:48 +000011633 SemaRef.Diag(Best->Function->getLocation(),
11634 diag::note_not_found_by_two_phase_lookup)
Chandler Carruthd50f1692011-06-05 23:36:55 +000011635 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smith998a5912011-06-05 22:42:48 +000011636 } else {
11637 // FIXME: It would be useful to list the associated namespaces here,
11638 // but the diagnostics infrastructure doesn't provide a way to produce
11639 // a localized representation of a list of items.
11640 SemaRef.Diag(Best->Function->getLocation(),
11641 diag::note_not_found_by_two_phase_lookup)
11642 << R.getLookupName() << 2;
11643 }
11644
11645 // Try to recover by calling this function.
11646 return true;
11647 }
11648
11649 R.clear();
11650 }
11651
11652 return false;
11653}
11654
11655/// Attempt to recover from ill-formed use of a non-dependent operator in a
11656/// template, where the non-dependent operator was declared after the template
11657/// was defined.
11658///
11659/// Returns true if a viable candidate was found and a diagnostic was issued.
11660static bool
11661DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
11662 SourceLocation OpLoc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011663 ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +000011664 DeclarationName OpName =
11665 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
11666 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
11667 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Richard Smith100b24a2014-04-17 01:52:14 +000011668 OverloadCandidateSet::CSK_Operator,
Craig Topperc3ec1492014-05-26 06:22:03 +000011669 /*ExplicitTemplateArgs=*/nullptr, Args);
Richard Smith998a5912011-06-05 22:42:48 +000011670}
11671
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000011672namespace {
Richard Smith88d67f32012-09-25 04:46:05 +000011673class BuildRecoveryCallExprRAII {
11674 Sema &SemaRef;
11675public:
11676 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
11677 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
11678 SemaRef.IsBuildingRecoveryCallExpr = true;
11679 }
11680
11681 ~BuildRecoveryCallExprRAII() {
11682 SemaRef.IsBuildingRecoveryCallExpr = false;
11683 }
11684};
11685
Alexander Kornienkoab9db512015-06-22 23:07:51 +000011686}
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000011687
Kaelyn Takata89c881b2014-10-27 18:07:29 +000011688static std::unique_ptr<CorrectionCandidateCallback>
11689MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
11690 bool HasTemplateArgs, bool AllowTypoCorrection) {
11691 if (!AllowTypoCorrection)
11692 return llvm::make_unique<NoTypoCorrectionCCC>();
11693 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
11694 HasTemplateArgs, ME);
11695}
11696
John McCalld681c392009-12-16 08:11:27 +000011697/// Attempts to recover from a call where no functions were found.
11698///
11699/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +000011700static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +000011701BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +000011702 UnresolvedLookupExpr *ULE,
11703 SourceLocation LParenLoc,
Craig Toppere3d2ecbe2014-06-28 23:22:33 +000011704 MutableArrayRef<Expr *> Args,
Richard Smith998a5912011-06-05 22:42:48 +000011705 SourceLocation RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000011706 bool EmptyLookup, bool AllowTypoCorrection) {
Richard Smith88d67f32012-09-25 04:46:05 +000011707 // Do not try to recover if it is already building a recovery call.
11708 // This stops infinite loops for template instantiations like
11709 //
11710 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
11711 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
11712 //
11713 if (SemaRef.IsBuildingRecoveryCallExpr)
11714 return ExprError();
11715 BuildRecoveryCallExprRAII RCE(SemaRef);
John McCalld681c392009-12-16 08:11:27 +000011716
11717 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +000011718 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +000011719 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCalld681c392009-12-16 08:11:27 +000011720
John McCall57500772009-12-16 12:17:52 +000011721 TemplateArgumentListInfo TABuffer;
Craig Topperc3ec1492014-05-26 06:22:03 +000011722 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
John McCall57500772009-12-16 12:17:52 +000011723 if (ULE->hasExplicitTemplateArgs()) {
11724 ULE->copyTemplateArgumentsInto(TABuffer);
11725 ExplicitTemplateArgs = &TABuffer;
11726 }
11727
John McCalld681c392009-12-16 08:11:27 +000011728 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
11729 Sema::LookupOrdinaryName);
Hans Wennborg64937c62015-06-11 21:21:57 +000011730 bool DoDiagnoseEmptyLookup = EmptyLookup;
Richard Smith998a5912011-06-05 22:42:48 +000011731 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Richard Smith100b24a2014-04-17 01:52:14 +000011732 OverloadCandidateSet::CSK_Normal,
Hans Wennborg64937c62015-06-11 21:21:57 +000011733 ExplicitTemplateArgs, Args,
11734 &DoDiagnoseEmptyLookup) &&
11735 (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup(
11736 S, SS, R,
11737 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
11738 ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
11739 ExplicitTemplateArgs, Args)))
John McCallfaf5fb42010-08-26 23:41:50 +000011740 return ExprError();
John McCalld681c392009-12-16 08:11:27 +000011741
John McCall57500772009-12-16 12:17:52 +000011742 assert(!R.empty() && "lookup results empty despite recovery");
11743
Richard Smith151c4562016-12-20 21:35:28 +000011744 // If recovery created an ambiguity, just bail out.
11745 if (R.isAmbiguous()) {
11746 R.suppressDiagnostics();
11747 return ExprError();
11748 }
11749
John McCall57500772009-12-16 12:17:52 +000011750 // Build an implicit member call if appropriate. Just drop the
11751 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +000011752 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +000011753 if ((*R.begin())->isCXXClassMember())
Aaron Ballman6924dcd2015-09-01 14:49:24 +000011754 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
11755 ExplicitTemplateArgs, S);
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000011756 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnara7945c982012-01-27 09:46:47 +000011757 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000011758 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +000011759 else
11760 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
11761
11762 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +000011763 return ExprError();
John McCall57500772009-12-16 12:17:52 +000011764
11765 // This shouldn't cause an infinite loop because we're giving it
Richard Smith998a5912011-06-05 22:42:48 +000011766 // an expression with viable lookup results, which should never
John McCall57500772009-12-16 12:17:52 +000011767 // end up here.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011768 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011769 MultiExprArg(Args.data(), Args.size()),
11770 RParenLoc);
John McCalld681c392009-12-16 08:11:27 +000011771}
Douglas Gregor4038cf42010-06-08 17:35:15 +000011772
Sam Panzer0f384432012-08-21 00:52:01 +000011773/// \brief Constructs and populates an OverloadedCandidateSet from
11774/// the given function.
11775/// \returns true when an the ExprResult output parameter has been set.
11776bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
11777 UnresolvedLookupExpr *ULE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011778 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011779 SourceLocation RParenLoc,
11780 OverloadCandidateSet *CandidateSet,
11781 ExprResult *Result) {
John McCall57500772009-12-16 12:17:52 +000011782#ifndef NDEBUG
11783 if (ULE->requiresADL()) {
11784 // To do ADL, we must have found an unqualified name.
11785 assert(!ULE->getQualifier() && "qualified name with ADL");
11786
11787 // We don't perform ADL for implicit declarations of builtins.
11788 // Verify that this was correctly set up.
11789 FunctionDecl *F;
11790 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
11791 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
11792 F->getBuiltinID() && F->isImplicit())
David Blaikie83d382b2011-09-23 05:06:16 +000011793 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011794
John McCall57500772009-12-16 12:17:52 +000011795 // We don't perform ADL in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011796 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smithb6626742012-10-18 17:56:02 +000011797 }
John McCall57500772009-12-16 12:17:52 +000011798#endif
11799
John McCall4124c492011-10-17 18:40:02 +000011800 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011801 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
Sam Panzer0f384432012-08-21 00:52:01 +000011802 *Result = ExprError();
11803 return true;
11804 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +000011805
John McCall57500772009-12-16 12:17:52 +000011806 // Add the functions denoted by the callee to the set of candidate
11807 // functions, including those from argument-dependent lookup.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011808 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
John McCalld681c392009-12-16 08:11:27 +000011809
Hans Wennborgb2747382015-06-12 21:23:23 +000011810 if (getLangOpts().MSVCCompat &&
11811 CurContext->isDependentContext() && !isSFINAEContext() &&
Hans Wennborg64937c62015-06-11 21:21:57 +000011812 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
11813
11814 OverloadCandidateSet::iterator Best;
11815 if (CandidateSet->empty() ||
11816 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) ==
11817 OR_No_Viable_Function) {
11818 // In Microsoft mode, if we are inside a template class member function then
11819 // create a type dependent CallExpr. The goal is to postpone name lookup
11820 // to instantiation time to be able to search into type dependent base
11821 // classes.
11822 CallExpr *CE = new (Context) CallExpr(
11823 Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc);
Sebastian Redlb49c46c2011-09-24 17:48:00 +000011824 CE->setTypeDependent(true);
Richard Smithed9b8f02015-09-23 21:30:47 +000011825 CE->setValueDependent(true);
11826 CE->setInstantiationDependent(true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011827 *Result = CE;
Sam Panzer0f384432012-08-21 00:52:01 +000011828 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +000011829 }
Francois Pichetbcf64712011-09-07 00:14:57 +000011830 }
John McCalld681c392009-12-16 08:11:27 +000011831
Hans Wennborg64937c62015-06-11 21:21:57 +000011832 if (CandidateSet->empty())
11833 return false;
11834
John McCall4124c492011-10-17 18:40:02 +000011835 UnbridgedCasts.restore();
Sam Panzer0f384432012-08-21 00:52:01 +000011836 return false;
11837}
John McCall4124c492011-10-17 18:40:02 +000011838
Sam Panzer0f384432012-08-21 00:52:01 +000011839/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
11840/// the completed call expression. If overload resolution fails, emits
11841/// diagnostics and returns ExprError()
11842static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11843 UnresolvedLookupExpr *ULE,
11844 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011845 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011846 SourceLocation RParenLoc,
11847 Expr *ExecConfig,
11848 OverloadCandidateSet *CandidateSet,
11849 OverloadCandidateSet::iterator *Best,
11850 OverloadingResult OverloadResult,
11851 bool AllowTypoCorrection) {
11852 if (CandidateSet->empty())
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011853 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011854 RParenLoc, /*EmptyLookup=*/true,
11855 AllowTypoCorrection);
11856
11857 switch (OverloadResult) {
John McCall57500772009-12-16 12:17:52 +000011858 case OR_Success: {
Sam Panzer0f384432012-08-21 00:52:01 +000011859 FunctionDecl *FDecl = (*Best)->Function;
Sam Panzer0f384432012-08-21 00:52:01 +000011860 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000011861 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
11862 return ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000011863 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011864 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11865 ExecConfig);
John McCall57500772009-12-16 12:17:52 +000011866 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011867
Richard Smith998a5912011-06-05 22:42:48 +000011868 case OR_No_Viable_Function: {
11869 // Try to recover by looking for viable functions which the user might
11870 // have meant to call.
Sam Panzer0f384432012-08-21 00:52:01 +000011871 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011872 Args, RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000011873 /*EmptyLookup=*/false,
11874 AllowTypoCorrection);
Richard Smith998a5912011-06-05 22:42:48 +000011875 if (!Recovery.isInvalid())
11876 return Recovery;
11877
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011878 // If the user passes in a function that we can't take the address of, we
11879 // generally end up emitting really bad error messages. Here, we attempt to
11880 // emit better ones.
11881 for (const Expr *Arg : Args) {
11882 if (!Arg->getType()->isFunctionType())
11883 continue;
11884 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
11885 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
11886 if (FD &&
11887 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
11888 Arg->getExprLoc()))
11889 return ExprError();
11890 }
11891 }
11892
11893 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_no_viable_function_in_call)
11894 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011895 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011896 break;
Richard Smith998a5912011-06-05 22:42:48 +000011897 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011898
11899 case OR_Ambiguous:
Sam Panzer0f384432012-08-21 00:52:01 +000011900 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +000011901 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011902 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011903 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000011904
Sam Panzer0f384432012-08-21 00:52:01 +000011905 case OR_Deleted: {
11906 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
11907 << (*Best)->Function->isDeleted()
11908 << ULE->getName()
11909 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
11910 << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011911 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Argyrios Kyrtzidis3eaa22a2011-11-04 15:58:13 +000011912
Sam Panzer0f384432012-08-21 00:52:01 +000011913 // We emitted an error for the unvailable/deleted function call but keep
11914 // the call in the AST.
11915 FunctionDecl *FDecl = (*Best)->Function;
11916 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011917 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11918 ExecConfig);
Sam Panzer0f384432012-08-21 00:52:01 +000011919 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011920 }
11921
Douglas Gregorb412e172010-07-25 18:17:45 +000011922 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +000011923 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011924}
11925
George Burgess IV7204ed92016-01-07 02:26:57 +000011926static void markUnaddressableCandidatesUnviable(Sema &S,
11927 OverloadCandidateSet &CS) {
11928 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
11929 if (I->Viable &&
11930 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
11931 I->Viable = false;
11932 I->FailureKind = ovl_fail_addr_not_available;
11933 }
11934 }
11935}
11936
Sam Panzer0f384432012-08-21 00:52:01 +000011937/// BuildOverloadedCallExpr - Given the call expression that calls Fn
11938/// (which eventually refers to the declaration Func) and the call
11939/// arguments Args/NumArgs, attempt to resolve the function call down
11940/// to a specific function. If overload resolution succeeds, returns
11941/// the call expression produced by overload resolution.
11942/// Otherwise, emits diagnostics and returns ExprError.
11943ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
11944 UnresolvedLookupExpr *ULE,
11945 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011946 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011947 SourceLocation RParenLoc,
11948 Expr *ExecConfig,
George Burgess IV7204ed92016-01-07 02:26:57 +000011949 bool AllowTypoCorrection,
11950 bool CalleesAddressIsTaken) {
Richard Smith100b24a2014-04-17 01:52:14 +000011951 OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
11952 OverloadCandidateSet::CSK_Normal);
Sam Panzer0f384432012-08-21 00:52:01 +000011953 ExprResult result;
11954
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011955 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
11956 &result))
Sam Panzer0f384432012-08-21 00:52:01 +000011957 return result;
11958
George Burgess IV7204ed92016-01-07 02:26:57 +000011959 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
11960 // functions that aren't addressible are considered unviable.
11961 if (CalleesAddressIsTaken)
11962 markUnaddressableCandidatesUnviable(*this, CandidateSet);
11963
Sam Panzer0f384432012-08-21 00:52:01 +000011964 OverloadCandidateSet::iterator Best;
11965 OverloadingResult OverloadResult =
11966 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
11967
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011968 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011969 RParenLoc, ExecConfig, &CandidateSet,
11970 &Best, OverloadResult,
11971 AllowTypoCorrection);
11972}
11973
John McCall4c4c1df2010-01-26 03:27:55 +000011974static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +000011975 return Functions.size() > 1 ||
11976 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
11977}
11978
Douglas Gregor084d8552009-03-13 23:49:33 +000011979/// \brief Create a unary operation that may resolve to an overloaded
11980/// operator.
11981///
11982/// \param OpLoc The location of the operator itself (e.g., '*').
11983///
Craig Toppera92ffb02015-12-10 08:51:49 +000011984/// \param Opc The UnaryOperatorKind that describes this operator.
Douglas Gregor084d8552009-03-13 23:49:33 +000011985///
James Dennett18348b62012-06-22 08:52:37 +000011986/// \param Fns The set of non-member functions that will be
Douglas Gregor084d8552009-03-13 23:49:33 +000011987/// considered by overload resolution. The caller needs to build this
11988/// set based on the context using, e.g.,
11989/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11990/// set should not contain any member functions; those will be added
11991/// by CreateOverloadedUnaryOp().
11992///
James Dennett91738ff2012-06-22 10:32:46 +000011993/// \param Input The input argument.
John McCalldadc5752010-08-24 06:29:42 +000011994ExprResult
Craig Toppera92ffb02015-12-10 08:51:49 +000011995Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
John McCall4c4c1df2010-01-26 03:27:55 +000011996 const UnresolvedSetImpl &Fns,
Richard Smith91fc7d82017-10-05 19:35:51 +000011997 Expr *Input, bool PerformADL) {
Douglas Gregor084d8552009-03-13 23:49:33 +000011998 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
11999 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
12000 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000012001 // TODO: provide better source location info.
12002 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +000012003
John McCall4124c492011-10-17 18:40:02 +000012004 if (checkPlaceholderForOverload(*this, Input))
12005 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012006
Craig Topperc3ec1492014-05-26 06:22:03 +000012007 Expr *Args[2] = { Input, nullptr };
Douglas Gregor084d8552009-03-13 23:49:33 +000012008 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +000012009
Douglas Gregor084d8552009-03-13 23:49:33 +000012010 // For post-increment and post-decrement, add the implicit '0' as
12011 // the second argument, so that we know this is a post-increment or
12012 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +000012013 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +000012014 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +000012015 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
12016 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +000012017 NumArgs = 2;
12018 }
12019
Richard Smithe54c3072013-05-05 15:51:06 +000012020 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
12021
Douglas Gregor084d8552009-03-13 23:49:33 +000012022 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +000012023 if (Fns.empty())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012024 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
12025 VK_RValue, OK_Ordinary, OpLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012026
Craig Topperc3ec1492014-05-26 06:22:03 +000012027 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +000012028 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000012029 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000012030 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000012031 /*ADL*/ true, IsOverloaded(Fns),
12032 Fns.begin(), Fns.end());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012033 return new (Context)
12034 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
Adam Nemet484aa452017-03-27 19:17:25 +000012035 VK_RValue, OpLoc, FPOptions());
Douglas Gregor084d8552009-03-13 23:49:33 +000012036 }
12037
12038 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000012039 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
Douglas Gregor084d8552009-03-13 23:49:33 +000012040
12041 // Add the candidates from the given function set.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000012042 AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000012043
12044 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000012045 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000012046
John McCall4c4c1df2010-01-26 03:27:55 +000012047 // Add candidates from ADL.
Richard Smith91fc7d82017-10-05 19:35:51 +000012048 if (PerformADL) {
12049 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
12050 /*ExplicitTemplateArgs*/nullptr,
12051 CandidateSet);
12052 }
John McCall4c4c1df2010-01-26 03:27:55 +000012053
Douglas Gregor084d8552009-03-13 23:49:33 +000012054 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000012055 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000012056
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012057 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12058
Douglas Gregor084d8552009-03-13 23:49:33 +000012059 // Perform overload resolution.
12060 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012061 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +000012062 case OR_Success: {
12063 // We found a built-in operator or an overloaded operator.
12064 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +000012065
Douglas Gregor084d8552009-03-13 23:49:33 +000012066 if (FnDecl) {
Akira Hatanaka22461672017-07-13 06:08:27 +000012067 Expr *Base = nullptr;
Douglas Gregor084d8552009-03-13 23:49:33 +000012068 // We matched an overloaded operator. Build a call to that
12069 // operator.
Mike Stump11289f42009-09-09 15:08:12 +000012070
Douglas Gregor084d8552009-03-13 23:49:33 +000012071 // Convert the arguments.
12072 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Craig Topperc3ec1492014-05-26 06:22:03 +000012073 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000012074
John Wiegley01296292011-04-08 18:41:53 +000012075 ExprResult InputRes =
Craig Topperc3ec1492014-05-26 06:22:03 +000012076 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012077 Best->FoundDecl, Method);
12078 if (InputRes.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000012079 return ExprError();
Akira Hatanaka22461672017-07-13 06:08:27 +000012080 Base = Input = InputRes.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000012081 } else {
12082 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000012083 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +000012084 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000012085 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +000012086 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012087 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +000012088 Input);
Douglas Gregore6600372009-12-23 17:40:29 +000012089 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000012090 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012091 Input = InputInit.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000012092 }
12093
Douglas Gregor084d8552009-03-13 23:49:33 +000012094 // Build the actual expression node.
Nick Lewycky134af912013-02-07 05:08:22 +000012095 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
Akira Hatanaka22461672017-07-13 06:08:27 +000012096 Base, HadMultipleCandidates,
12097 OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000012098 if (FnExpr.isInvalid())
12099 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +000012100
Richard Smithc1564702013-11-15 02:58:23 +000012101 // Determine the result type.
Alp Toker314cc812014-01-25 16:55:45 +000012102 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000012103 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12104 ResultTy = ResultTy.getNonLValueExprType(Context);
12105
Eli Friedman030eee42009-11-18 03:58:17 +000012106 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +000012107 CallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012108 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
Adam Nemet484aa452017-03-27 19:17:25 +000012109 ResultTy, VK, OpLoc, FPOptions());
John McCall4fa0d5f2010-05-06 18:15:07 +000012110
Alp Toker314cc812014-01-25 16:55:45 +000012111 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
Anders Carlssonf64a3da2009-10-13 21:19:37 +000012112 return ExprError();
12113
George Burgess IVce6284b2017-01-28 02:19:40 +000012114 if (CheckFunctionCall(FnDecl, TheCall,
12115 FnDecl->getType()->castAs<FunctionProtoType>()))
12116 return ExprError();
12117
John McCallb268a282010-08-23 23:25:46 +000012118 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +000012119 } else {
12120 // We matched a built-in operator. Convert the arguments, then
12121 // break out so that we will build the appropriate built-in
12122 // operator node.
George Burgess IV5f6ab9a2017-06-08 20:55:21 +000012123 ExprResult InputRes = PerformImplicitConversion(
12124 Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing);
John Wiegley01296292011-04-08 18:41:53 +000012125 if (InputRes.isInvalid())
12126 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012127 Input = InputRes.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000012128 break;
Douglas Gregor084d8552009-03-13 23:49:33 +000012129 }
John Wiegley01296292011-04-08 18:41:53 +000012130 }
12131
12132 case OR_No_Viable_Function:
Richard Smith998a5912011-06-05 22:42:48 +000012133 // This is an erroneous use of an operator which can be overloaded by
12134 // a non-member function. Check for non-member operators which were
12135 // defined too late to be candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000012136 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
Richard Smith998a5912011-06-05 22:42:48 +000012137 // FIXME: Recover by calling the found function.
12138 return ExprError();
12139
John Wiegley01296292011-04-08 18:41:53 +000012140 // No viable function; fall through to handling this as a
12141 // built-in operator, which will produce an error message for us.
12142 break;
12143
12144 case OR_Ambiguous:
12145 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
12146 << UnaryOperator::getOpcodeStr(Opc)
12147 << Input->getType()
12148 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000012149 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
John Wiegley01296292011-04-08 18:41:53 +000012150 UnaryOperator::getOpcodeStr(Opc), OpLoc);
12151 return ExprError();
12152
12153 case OR_Deleted:
12154 Diag(OpLoc, diag::err_ovl_deleted_oper)
12155 << Best->Function->isDeleted()
12156 << UnaryOperator::getOpcodeStr(Opc)
12157 << getDeletedOrUnavailableSuffix(Best->Function)
12158 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000012159 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000012160 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000012161 return ExprError();
12162 }
Douglas Gregor084d8552009-03-13 23:49:33 +000012163
12164 // Either we found no viable overloaded operator or we matched a
12165 // built-in operator. In either case, fall through to trying to
12166 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +000012167 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +000012168}
12169
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012170/// \brief Create a binary operation that may resolve to an overloaded
12171/// operator.
12172///
12173/// \param OpLoc The location of the operator itself (e.g., '+').
12174///
Craig Toppera92ffb02015-12-10 08:51:49 +000012175/// \param Opc The BinaryOperatorKind that describes this operator.
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012176///
James Dennett18348b62012-06-22 08:52:37 +000012177/// \param Fns The set of non-member functions that will be
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012178/// considered by overload resolution. The caller needs to build this
12179/// set based on the context using, e.g.,
12180/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12181/// set should not contain any member functions; those will be added
12182/// by CreateOverloadedBinOp().
12183///
12184/// \param LHS Left-hand argument.
12185/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +000012186ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012187Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Craig Toppera92ffb02015-12-10 08:51:49 +000012188 BinaryOperatorKind Opc,
John McCall4c4c1df2010-01-26 03:27:55 +000012189 const UnresolvedSetImpl &Fns,
Richard Smith91fc7d82017-10-05 19:35:51 +000012190 Expr *LHS, Expr *RHS, bool PerformADL) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012191 Expr *Args[2] = { LHS, RHS };
Craig Topperc3ec1492014-05-26 06:22:03 +000012192 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012193
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012194 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
12195 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12196
12197 // If either side is type-dependent, create an appropriate dependent
12198 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +000012199 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +000012200 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012201 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +000012202 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +000012203 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012204 return new (Context) BinaryOperator(
12205 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
Adam Nemet484aa452017-03-27 19:17:25 +000012206 OpLoc, FPFeatures);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012207
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012208 return new (Context) CompoundAssignOperator(
12209 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
12210 Context.DependentTy, Context.DependentTy, OpLoc,
Adam Nemet484aa452017-03-27 19:17:25 +000012211 FPFeatures);
Douglas Gregor5287f092009-11-05 00:51:44 +000012212 }
John McCall4c4c1df2010-01-26 03:27:55 +000012213
12214 // FIXME: save results of ADL from here?
Craig Topperc3ec1492014-05-26 06:22:03 +000012215 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000012216 // TODO: provide better source location info in DNLoc component.
12217 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +000012218 UnresolvedLookupExpr *Fn
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000012219 = UnresolvedLookupExpr::Create(Context, NamingClass,
12220 NestedNameSpecifierLoc(), OpNameInfo,
Richard Smith91fc7d82017-10-05 19:35:51 +000012221 /*ADL*/PerformADL, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000012222 Fns.begin(), Fns.end());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012223 return new (Context)
12224 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
Adam Nemet484aa452017-03-27 19:17:25 +000012225 VK_RValue, OpLoc, FPFeatures);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012226 }
12227
John McCall4124c492011-10-17 18:40:02 +000012228 // Always do placeholder-like conversions on the RHS.
12229 if (checkPlaceholderForOverload(*this, Args[1]))
12230 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012231
John McCall526ab472011-10-25 17:37:35 +000012232 // Do placeholder-like conversion on the LHS; note that we should
12233 // not get here with a PseudoObject LHS.
12234 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall4124c492011-10-17 18:40:02 +000012235 if (checkPlaceholderForOverload(*this, Args[0]))
12236 return ExprError();
12237
Sebastian Redl6a96bf72009-11-18 23:10:33 +000012238 // If this is the assignment operator, we only perform overload resolution
12239 // if the left-hand side is a class or enumeration type. This is actually
12240 // a hack. The standard requires that we do overload resolution between the
12241 // various built-in candidates, but as DR507 points out, this can lead to
12242 // problems. So we do it this way, which pretty much follows what GCC does.
12243 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +000012244 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +000012245 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012246
John McCalle26a8722010-12-04 08:14:53 +000012247 // If this is the .* operator, which is not overloadable, just
12248 // create a built-in binary operator.
12249 if (Opc == BO_PtrMemD)
12250 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12251
Douglas Gregor084d8552009-03-13 23:49:33 +000012252 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000012253 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012254
12255 // Add the candidates from the given function set.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000012256 AddFunctionCandidates(Fns, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012257
12258 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000012259 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012260
Richard Smith0daabd72014-09-23 20:31:39 +000012261 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
12262 // performed for an assignment operator (nor for operator[] nor operator->,
12263 // which don't get here).
Richard Smith91fc7d82017-10-05 19:35:51 +000012264 if (Opc != BO_Assign && PerformADL)
Richard Smith0daabd72014-09-23 20:31:39 +000012265 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
12266 /*ExplicitTemplateArgs*/ nullptr,
12267 CandidateSet);
John McCall4c4c1df2010-01-26 03:27:55 +000012268
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012269 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000012270 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012271
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012272 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12273
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012274 // Perform overload resolution.
12275 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012276 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +000012277 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012278 // We found a built-in operator or an overloaded operator.
12279 FunctionDecl *FnDecl = Best->Function;
12280
12281 if (FnDecl) {
Akira Hatanaka22461672017-07-13 06:08:27 +000012282 Expr *Base = nullptr;
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012283 // We matched an overloaded operator. Build a call to that
12284 // operator.
12285
12286 // Convert the arguments.
12287 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +000012288 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +000012289 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000012290
Chandler Carruth8e543b32010-12-12 08:17:55 +000012291 ExprResult Arg1 =
12292 PerformCopyInitialization(
12293 InitializedEntity::InitializeParameter(Context,
12294 FnDecl->getParamDecl(0)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012295 SourceLocation(), Args[1]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000012296 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012297 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000012298
John Wiegley01296292011-04-08 18:41:53 +000012299 ExprResult Arg0 =
Craig Topperc3ec1492014-05-26 06:22:03 +000012300 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012301 Best->FoundDecl, Method);
12302 if (Arg0.isInvalid())
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000012303 return ExprError();
Akira Hatanaka22461672017-07-13 06:08:27 +000012304 Base = Args[0] = Arg0.getAs<Expr>();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012305 Args[1] = RHS = Arg1.getAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012306 } else {
12307 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +000012308 ExprResult Arg0 = PerformCopyInitialization(
12309 InitializedEntity::InitializeParameter(Context,
12310 FnDecl->getParamDecl(0)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012311 SourceLocation(), Args[0]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000012312 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012313 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000012314
Chandler Carruth8e543b32010-12-12 08:17:55 +000012315 ExprResult Arg1 =
12316 PerformCopyInitialization(
12317 InitializedEntity::InitializeParameter(Context,
12318 FnDecl->getParamDecl(1)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012319 SourceLocation(), Args[1]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000012320 if (Arg1.isInvalid())
12321 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012322 Args[0] = LHS = Arg0.getAs<Expr>();
12323 Args[1] = RHS = Arg1.getAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012324 }
12325
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012326 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012327 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Akira Hatanaka22461672017-07-13 06:08:27 +000012328 Best->FoundDecl, Base,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012329 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000012330 if (FnExpr.isInvalid())
12331 return ExprError();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012332
Richard Smithc1564702013-11-15 02:58:23 +000012333 // Determine the result type.
Alp Toker314cc812014-01-25 16:55:45 +000012334 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000012335 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12336 ResultTy = ResultTy.getNonLValueExprType(Context);
12337
John McCallb268a282010-08-23 23:25:46 +000012338 CXXOperatorCallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012339 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
Lang Hames5de91cc2012-10-02 04:45:10 +000012340 Args, ResultTy, VK, OpLoc,
Adam Nemet484aa452017-03-27 19:17:25 +000012341 FPFeatures);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012342
Alp Toker314cc812014-01-25 16:55:45 +000012343 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000012344 FnDecl))
12345 return ExprError();
12346
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000012347 ArrayRef<const Expr *> ArgsArray(Args, 2);
George Burgess IVce6284b2017-01-28 02:19:40 +000012348 const Expr *ImplicitThis = nullptr;
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000012349 // Cut off the implicit 'this'.
George Burgess IVce6284b2017-01-28 02:19:40 +000012350 if (isa<CXXMethodDecl>(FnDecl)) {
12351 ImplicitThis = ArgsArray[0];
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000012352 ArgsArray = ArgsArray.slice(1);
George Burgess IVce6284b2017-01-28 02:19:40 +000012353 }
Richard Trieu36d0b2b2015-01-13 02:32:02 +000012354
12355 // Check for a self move.
12356 if (Op == OO_Equal)
12357 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
12358
George Burgess IVce6284b2017-01-28 02:19:40 +000012359 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
12360 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
12361 VariadicDoesNotApply);
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000012362
John McCallb268a282010-08-23 23:25:46 +000012363 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012364 } else {
12365 // We matched a built-in operator. Convert the arguments, then
12366 // break out so that we will build the appropriate built-in
12367 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000012368 ExprResult ArgsRes0 =
George Burgess IV5f6ab9a2017-06-08 20:55:21 +000012369 PerformImplicitConversion(Args[0], Best->BuiltinParamTypes[0],
12370 Best->Conversions[0], AA_Passing);
John Wiegley01296292011-04-08 18:41:53 +000012371 if (ArgsRes0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012372 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012373 Args[0] = ArgsRes0.get();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012374
John Wiegley01296292011-04-08 18:41:53 +000012375 ExprResult ArgsRes1 =
George Burgess IV5f6ab9a2017-06-08 20:55:21 +000012376 PerformImplicitConversion(Args[1], Best->BuiltinParamTypes[1],
12377 Best->Conversions[1], AA_Passing);
John Wiegley01296292011-04-08 18:41:53 +000012378 if (ArgsRes1.isInvalid())
12379 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012380 Args[1] = ArgsRes1.get();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012381 break;
12382 }
12383 }
12384
Douglas Gregor66950a32009-09-30 21:46:01 +000012385 case OR_No_Viable_Function: {
12386 // C++ [over.match.oper]p9:
12387 // If the operator is the operator , [...] and there are no
12388 // viable functions, then the operator is assumed to be the
12389 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +000012390 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +000012391 break;
12392
Chandler Carruth8e543b32010-12-12 08:17:55 +000012393 // For class as left operand for assignment or compound assigment
12394 // operator do not fall through to handling in built-in, but report that
12395 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +000012396 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012397 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +000012398 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +000012399 Diag(OpLoc, diag::err_ovl_no_viable_oper)
12400 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +000012401 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Eli Friedmana31efa02013-08-28 20:35:35 +000012402 if (Args[0]->getType()->isIncompleteType()) {
12403 Diag(OpLoc, diag::note_assign_lhs_incomplete)
12404 << Args[0]->getType()
12405 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12406 }
Douglas Gregor66950a32009-09-30 21:46:01 +000012407 } else {
Richard Smith998a5912011-06-05 22:42:48 +000012408 // This is an erroneous use of an operator which can be overloaded by
12409 // a non-member function. Check for non-member operators which were
12410 // defined too late to be candidates.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012411 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smith998a5912011-06-05 22:42:48 +000012412 // FIXME: Recover by calling the found function.
12413 return ExprError();
12414
Douglas Gregor66950a32009-09-30 21:46:01 +000012415 // No viable function; try to create a built-in operation, which will
12416 // produce an error. Then, show the non-viable candidates.
12417 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +000012418 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012419 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +000012420 "C++ binary operator overloading is missing candidates!");
12421 if (Result.isInvalid())
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012422 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012423 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012424 return Result;
Douglas Gregor66950a32009-09-30 21:46:01 +000012425 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012426
12427 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000012428 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012429 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +000012430 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +000012431 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012432 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012433 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012434 return ExprError();
12435
12436 case OR_Deleted:
Douglas Gregor74f7d502012-02-15 19:33:52 +000012437 if (isImplicitlyDeleted(Best->Function)) {
12438 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12439 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
Richard Smithde1a4872012-12-28 12:23:24 +000012440 << Context.getRecordType(Method->getParent())
12441 << getSpecialMember(Method);
Richard Smith6f1e2c62012-04-02 20:59:25 +000012442
Richard Smithde1a4872012-12-28 12:23:24 +000012443 // The user probably meant to call this special member. Just
12444 // explain why it's deleted.
12445 NoteDeletedFunction(Method);
12446 return ExprError();
Douglas Gregor74f7d502012-02-15 19:33:52 +000012447 } else {
12448 Diag(OpLoc, diag::err_ovl_deleted_oper)
12449 << Best->Function->isDeleted()
12450 << BinaryOperator::getOpcodeStr(Opc)
12451 << getDeletedOrUnavailableSuffix(Best->Function)
12452 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12453 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012454 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000012455 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012456 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +000012457 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012458
Douglas Gregor66950a32009-09-30 21:46:01 +000012459 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +000012460 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012461}
12462
John McCalldadc5752010-08-24 06:29:42 +000012463ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +000012464Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
12465 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +000012466 Expr *Base, Expr *Idx) {
12467 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +000012468 DeclarationName OpName =
12469 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
12470
12471 // If either side is type-dependent, create an appropriate dependent
12472 // expression.
12473 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12474
Craig Topperc3ec1492014-05-26 06:22:03 +000012475 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000012476 // CHECKME: no 'operator' keyword?
12477 DeclarationNameInfo OpNameInfo(OpName, LLoc);
12478 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +000012479 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000012480 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000012481 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000012482 /*ADL*/ true, /*Overloaded*/ false,
12483 UnresolvedSetIterator(),
12484 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +000012485 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +000012486
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012487 return new (Context)
12488 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
Adam Nemet484aa452017-03-27 19:17:25 +000012489 Context.DependentTy, VK_RValue, RLoc, FPOptions());
Sebastian Redladba46e2009-10-29 20:17:01 +000012490 }
12491
John McCall4124c492011-10-17 18:40:02 +000012492 // Handle placeholders on both operands.
12493 if (checkPlaceholderForOverload(*this, Args[0]))
12494 return ExprError();
12495 if (checkPlaceholderForOverload(*this, Args[1]))
12496 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012497
Sebastian Redladba46e2009-10-29 20:17:01 +000012498 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000012499 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
Sebastian Redladba46e2009-10-29 20:17:01 +000012500
12501 // Subscript can only be overloaded as a member function.
12502
12503 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000012504 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000012505
12506 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000012507 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000012508
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012509 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12510
Sebastian Redladba46e2009-10-29 20:17:01 +000012511 // Perform overload resolution.
12512 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012513 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +000012514 case OR_Success: {
12515 // We found a built-in operator or an overloaded operator.
12516 FunctionDecl *FnDecl = Best->Function;
12517
12518 if (FnDecl) {
12519 // We matched an overloaded operator. Build a call to that
12520 // operator.
12521
John McCalla0296f72010-03-19 07:35:19 +000012522 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall58cc69d2010-01-27 01:50:18 +000012523
Sebastian Redladba46e2009-10-29 20:17:01 +000012524 // Convert the arguments.
12525 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley01296292011-04-08 18:41:53 +000012526 ExprResult Arg0 =
Craig Topperc3ec1492014-05-26 06:22:03 +000012527 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012528 Best->FoundDecl, Method);
12529 if (Arg0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000012530 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012531 Args[0] = Arg0.get();
Sebastian Redladba46e2009-10-29 20:17:01 +000012532
Anders Carlssona68e51e2010-01-29 18:37:50 +000012533 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000012534 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +000012535 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000012536 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +000012537 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012538 SourceLocation(),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012539 Args[1]);
Anders Carlssona68e51e2010-01-29 18:37:50 +000012540 if (InputInit.isInvalid())
12541 return ExprError();
12542
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012543 Args[1] = InputInit.getAs<Expr>();
Anders Carlssona68e51e2010-01-29 18:37:50 +000012544
Sebastian Redladba46e2009-10-29 20:17:01 +000012545 // Build the actual expression node.
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012546 DeclarationNameInfo OpLocInfo(OpName, LLoc);
12547 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012548 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000012549 Best->FoundDecl,
Akira Hatanaka22461672017-07-13 06:08:27 +000012550 Base,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012551 HadMultipleCandidates,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012552 OpLocInfo.getLoc(),
12553 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000012554 if (FnExpr.isInvalid())
12555 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000012556
Richard Smithc1564702013-11-15 02:58:23 +000012557 // Determine the result type
Alp Toker314cc812014-01-25 16:55:45 +000012558 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000012559 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12560 ResultTy = ResultTy.getNonLValueExprType(Context);
12561
John McCallb268a282010-08-23 23:25:46 +000012562 CXXOperatorCallExpr *TheCall =
12563 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012564 FnExpr.get(), Args,
Lang Hames5de91cc2012-10-02 04:45:10 +000012565 ResultTy, VK, RLoc,
Adam Nemet484aa452017-03-27 19:17:25 +000012566 FPOptions());
Sebastian Redladba46e2009-10-29 20:17:01 +000012567
Alp Toker314cc812014-01-25 16:55:45 +000012568 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
Sebastian Redladba46e2009-10-29 20:17:01 +000012569 return ExprError();
12570
George Burgess IVce6284b2017-01-28 02:19:40 +000012571 if (CheckFunctionCall(Method, TheCall,
12572 Method->getType()->castAs<FunctionProtoType>()))
12573 return ExprError();
12574
John McCallb268a282010-08-23 23:25:46 +000012575 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +000012576 } else {
12577 // We matched a built-in operator. Convert the arguments, then
12578 // break out so that we will build the appropriate built-in
12579 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000012580 ExprResult ArgsRes0 =
George Burgess IV5f6ab9a2017-06-08 20:55:21 +000012581 PerformImplicitConversion(Args[0], Best->BuiltinParamTypes[0],
12582 Best->Conversions[0], AA_Passing);
John Wiegley01296292011-04-08 18:41:53 +000012583 if (ArgsRes0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000012584 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012585 Args[0] = ArgsRes0.get();
John Wiegley01296292011-04-08 18:41:53 +000012586
12587 ExprResult ArgsRes1 =
George Burgess IV5f6ab9a2017-06-08 20:55:21 +000012588 PerformImplicitConversion(Args[1], Best->BuiltinParamTypes[1],
12589 Best->Conversions[1], AA_Passing);
John Wiegley01296292011-04-08 18:41:53 +000012590 if (ArgsRes1.isInvalid())
12591 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012592 Args[1] = ArgsRes1.get();
Sebastian Redladba46e2009-10-29 20:17:01 +000012593
12594 break;
12595 }
12596 }
12597
12598 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +000012599 if (CandidateSet.empty())
12600 Diag(LLoc, diag::err_ovl_no_oper)
12601 << Args[0]->getType() << /*subscript*/ 0
12602 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12603 else
12604 Diag(LLoc, diag::err_ovl_no_viable_subscript)
12605 << Args[0]->getType()
12606 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012607 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012608 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +000012609 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000012610 }
12611
12612 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000012613 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012614 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +000012615 << Args[0]->getType() << Args[1]->getType()
12616 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012617 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012618 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000012619 return ExprError();
12620
12621 case OR_Deleted:
12622 Diag(LLoc, diag::err_ovl_deleted_oper)
12623 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012624 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +000012625 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012626 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012627 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000012628 return ExprError();
12629 }
12630
12631 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +000012632 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000012633}
12634
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012635/// BuildCallToMemberFunction - Build a call to a member
12636/// function. MemExpr is the expression that refers to the member
12637/// function (and includes the object parameter), Args/NumArgs are the
12638/// arguments to the function call (not including the object
12639/// parameter). The caller needs to validate that the member
John McCall0009fcc2011-04-26 20:42:42 +000012640/// expression refers to a non-static member function or an overloaded
12641/// member function.
John McCalldadc5752010-08-24 06:29:42 +000012642ExprResult
Mike Stump11289f42009-09-09 15:08:12 +000012643Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012644 SourceLocation LParenLoc,
12645 MultiExprArg Args,
12646 SourceLocation RParenLoc) {
John McCall0009fcc2011-04-26 20:42:42 +000012647 assert(MemExprE->getType() == Context.BoundMemberTy ||
12648 MemExprE->getType() == Context.OverloadTy);
12649
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012650 // Dig out the member expression. This holds both the object
12651 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +000012652 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012653
John McCall0009fcc2011-04-26 20:42:42 +000012654 // Determine whether this is a call to a pointer-to-member function.
12655 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
12656 assert(op->getType() == Context.BoundMemberTy);
12657 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
12658
12659 QualType fnType =
12660 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
12661
12662 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
12663 QualType resultType = proto->getCallResultType(Context);
Alp Toker314cc812014-01-25 16:55:45 +000012664 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
John McCall0009fcc2011-04-26 20:42:42 +000012665
12666 // Check that the object type isn't more qualified than the
12667 // member function we're calling.
12668 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
12669
12670 QualType objectType = op->getLHS()->getType();
12671 if (op->getOpcode() == BO_PtrMemI)
12672 objectType = objectType->castAs<PointerType>()->getPointeeType();
12673 Qualifiers objectQuals = objectType.getQualifiers();
12674
12675 Qualifiers difference = objectQuals - funcQuals;
12676 difference.removeObjCGCAttr();
12677 difference.removeAddressSpace();
12678 if (difference) {
12679 std::string qualsString = difference.getAsString();
12680 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
12681 << fnType.getUnqualifiedType()
12682 << qualsString
12683 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
12684 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +000012685
John McCall0009fcc2011-04-26 20:42:42 +000012686 CXXMemberCallExpr *call
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012687 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall0009fcc2011-04-26 20:42:42 +000012688 resultType, valueKind, RParenLoc);
12689
Alp Toker314cc812014-01-25 16:55:45 +000012690 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
Craig Topperc3ec1492014-05-26 06:22:03 +000012691 call, nullptr))
John McCall0009fcc2011-04-26 20:42:42 +000012692 return ExprError();
12693
Craig Topperc3ec1492014-05-26 06:22:03 +000012694 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
John McCall0009fcc2011-04-26 20:42:42 +000012695 return ExprError();
12696
Richard Trieu9be9c682013-06-22 02:30:38 +000012697 if (CheckOtherCall(call, proto))
12698 return ExprError();
12699
John McCall0009fcc2011-04-26 20:42:42 +000012700 return MaybeBindToTemporary(call);
12701 }
12702
David Majnemerced8bdf2015-02-25 17:36:15 +000012703 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
12704 return new (Context)
12705 CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc);
12706
John McCall4124c492011-10-17 18:40:02 +000012707 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012708 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000012709 return ExprError();
12710
John McCall10eae182009-11-30 22:42:35 +000012711 MemberExpr *MemExpr;
Craig Topperc3ec1492014-05-26 06:22:03 +000012712 CXXMethodDecl *Method = nullptr;
12713 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
12714 NestedNameSpecifier *Qualifier = nullptr;
John McCall10eae182009-11-30 22:42:35 +000012715 if (isa<MemberExpr>(NakedMemExpr)) {
12716 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +000012717 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +000012718 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +000012719 Qualifier = MemExpr->getQualifier();
John McCall4124c492011-10-17 18:40:02 +000012720 UnbridgedCasts.restore();
John McCall10eae182009-11-30 22:42:35 +000012721 } else {
12722 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +000012723 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012724
John McCall6e9f8f62009-12-03 04:06:58 +000012725 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +000012726 Expr::Classification ObjectClassification
12727 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
12728 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +000012729
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012730 // Add overload candidates
Richard Smith100b24a2014-04-17 01:52:14 +000012731 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
12732 OverloadCandidateSet::CSK_Normal);
Mike Stump11289f42009-09-09 15:08:12 +000012733
John McCall2d74de92009-12-01 22:10:20 +000012734 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000012735 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCall2d74de92009-12-01 22:10:20 +000012736 if (UnresExpr->hasExplicitTemplateArgs()) {
12737 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12738 TemplateArgs = &TemplateArgsBuffer;
12739 }
12740
John McCall10eae182009-11-30 22:42:35 +000012741 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
12742 E = UnresExpr->decls_end(); I != E; ++I) {
12743
John McCall6e9f8f62009-12-03 04:06:58 +000012744 NamedDecl *Func = *I;
12745 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
12746 if (isa<UsingShadowDecl>(Func))
12747 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
12748
Douglas Gregor02824322011-01-26 19:30:28 +000012749
Francois Pichet64225792011-01-18 05:04:39 +000012750 // Microsoft supports direct constructor calls.
David Blaikiebbafb8a2012-03-11 07:00:24 +000012751 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012752 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012753 Args, CandidateSet);
Francois Pichet64225792011-01-18 05:04:39 +000012754 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +000012755 // If explicit template arguments were provided, we can't call a
12756 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +000012757 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +000012758 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012759
John McCalla0296f72010-03-19 07:35:19 +000012760 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
George Burgess IVce6284b2017-01-28 02:19:40 +000012761 ObjectClassification, Args, CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +000012762 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000012763 } else {
George Burgess IV177399e2017-01-09 04:12:14 +000012764 AddMethodTemplateCandidate(
12765 cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC,
George Burgess IVce6284b2017-01-28 02:19:40 +000012766 TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet,
George Burgess IV177399e2017-01-09 04:12:14 +000012767 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000012768 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000012769 }
Mike Stump11289f42009-09-09 15:08:12 +000012770
John McCall10eae182009-11-30 22:42:35 +000012771 DeclarationName DeclName = UnresExpr->getMemberName();
12772
John McCall4124c492011-10-17 18:40:02 +000012773 UnbridgedCasts.restore();
12774
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012775 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012776 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +000012777 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012778 case OR_Success:
12779 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +000012780 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +000012781 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000012782 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
12783 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000012784 // If FoundDecl is different from Method (such as if one is a template
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000012785 // and the other a specialization), make sure DiagnoseUseOfDecl is
Faisal Valid6676412013-06-15 11:54:37 +000012786 // called on both.
12787 // FIXME: This would be more comprehensively addressed by modifying
12788 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
12789 // being used.
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000012790 if (Method != FoundDecl.getDecl() &&
Faisal Valid6676412013-06-15 11:54:37 +000012791 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
12792 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012793 break;
12794
12795 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +000012796 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012797 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000012798 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012799 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012800 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000012801 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012802
12803 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +000012804 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000012805 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012806 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012807 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000012808 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000012809
12810 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +000012811 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +000012812 << Best->Function->isDeleted()
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000012813 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012814 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012815 << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012816 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000012817 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000012818 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012819 }
12820
John McCall16df1e52010-03-30 21:47:33 +000012821 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +000012822
John McCall2d74de92009-12-01 22:10:20 +000012823 // If overload resolution picked a static member, build a
12824 // non-member call based on that function.
12825 if (Method->isStatic()) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012826 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
12827 RParenLoc);
John McCall2d74de92009-12-01 22:10:20 +000012828 }
12829
John McCall10eae182009-11-30 22:42:35 +000012830 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012831 }
12832
Alp Toker314cc812014-01-25 16:55:45 +000012833 QualType ResultType = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000012834 ExprValueKind VK = Expr::getValueKindForType(ResultType);
12835 ResultType = ResultType.getNonLValueExprType(Context);
12836
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012837 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012838 CXXMemberCallExpr *TheCall =
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012839 new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall7decc9e2010-11-18 06:31:45 +000012840 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012841
Anders Carlssonc4859ba2009-10-10 00:06:20 +000012842 // Check for a valid return type.
Alp Toker314cc812014-01-25 16:55:45 +000012843 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +000012844 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +000012845 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012846
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012847 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +000012848 // We only need to do this if there was actually an overload; otherwise
12849 // it was done at lookup.
John Wiegley01296292011-04-08 18:41:53 +000012850 if (!Method->isStatic()) {
12851 ExprResult ObjectArg =
12852 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
12853 FoundDecl, Method);
12854 if (ObjectArg.isInvalid())
12855 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012856 MemExpr->setBase(ObjectArg.get());
John Wiegley01296292011-04-08 18:41:53 +000012857 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012858
12859 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +000012860 const FunctionProtoType *Proto =
12861 Method->getType()->getAs<FunctionProtoType>();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012862 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012863 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +000012864 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012865
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012866 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000012867
Richard Smith55ce3522012-06-25 20:30:08 +000012868 if (CheckFunctionCall(Method, TheCall, Proto))
John McCall2d74de92009-12-01 22:10:20 +000012869 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +000012870
George Burgess IVaea6ade2015-09-25 17:53:16 +000012871 // In the case the method to call was not selected by the overloading
12872 // resolution process, we still need to handle the enable_if attribute. Do
George Burgess IV0d546532016-11-10 21:47:12 +000012873 // that here, so it will not hide previous -- and more relevant -- errors.
George Burgess IVadd6ab52016-11-16 21:31:25 +000012874 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
George Burgess IVaea6ade2015-09-25 17:53:16 +000012875 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
George Burgess IVadd6ab52016-11-16 21:31:25 +000012876 Diag(MemE->getMemberLoc(),
George Burgess IVaea6ade2015-09-25 17:53:16 +000012877 diag::err_ovl_no_viable_member_function_in_call)
12878 << Method << Method->getSourceRange();
12879 Diag(Method->getLocation(),
George Burgess IV177399e2017-01-09 04:12:14 +000012880 diag::note_ovl_candidate_disabled_by_function_cond_attr)
George Burgess IVaea6ade2015-09-25 17:53:16 +000012881 << Attr->getCond()->getSourceRange() << Attr->getMessage();
12882 return ExprError();
12883 }
12884 }
12885
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000012886 if ((isa<CXXConstructorDecl>(CurContext) ||
12887 isa<CXXDestructorDecl>(CurContext)) &&
Anders Carlsson47061ee2011-05-06 14:25:31 +000012888 TheCall->getMethodDecl()->isPure()) {
12889 const CXXMethodDecl *MD = TheCall->getMethodDecl();
12890
Davide Italianoccb37382015-07-14 23:36:10 +000012891 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
12892 MemExpr->performsVirtualDispatch(getLangOpts())) {
12893 Diag(MemExpr->getLocStart(),
Anders Carlsson47061ee2011-05-06 14:25:31 +000012894 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
12895 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
12896 << MD->getParent()->getDeclName();
12897
12898 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Davide Italianoccb37382015-07-14 23:36:10 +000012899 if (getLangOpts().AppleKext)
12900 Diag(MemExpr->getLocStart(),
12901 diag::note_pure_qualified_call_kext)
12902 << MD->getParent()->getDeclName()
12903 << MD->getDeclName();
Chandler Carruth59259262011-06-27 08:31:58 +000012904 }
Anders Carlsson47061ee2011-05-06 14:25:31 +000012905 }
Nico Weber5a9259c2016-01-15 21:45:31 +000012906
12907 if (CXXDestructorDecl *DD =
12908 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
12909 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
Justin Lebard35f7062016-07-12 23:23:01 +000012910 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
Nico Weber5a9259c2016-01-15 21:45:31 +000012911 CheckVirtualDtorCall(DD, MemExpr->getLocStart(), /*IsDelete=*/false,
12912 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
12913 MemExpr->getMemberLoc());
12914 }
12915
John McCallb268a282010-08-23 23:25:46 +000012916 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012917}
12918
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012919/// BuildCallToObjectOfClassType - Build a call to an object of class
12920/// type (C++ [over.call.object]), which can end up invoking an
12921/// overloaded function call operator (@c operator()) or performing a
12922/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +000012923ExprResult
John Wiegley01296292011-04-08 18:41:53 +000012924Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregorb0846b02008-12-06 00:22:45 +000012925 SourceLocation LParenLoc,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012926 MultiExprArg Args,
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012927 SourceLocation RParenLoc) {
John McCall4124c492011-10-17 18:40:02 +000012928 if (checkPlaceholderForOverload(*this, Obj))
12929 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012930 ExprResult Object = Obj;
John McCall4124c492011-10-17 18:40:02 +000012931
12932 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012933 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000012934 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012935
Nico Weberb58e51c2014-11-19 05:21:39 +000012936 assert(Object.get()->getType()->isRecordType() &&
12937 "Requires object type argument");
John Wiegley01296292011-04-08 18:41:53 +000012938 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +000012939
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012940 // C++ [over.call.object]p1:
12941 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +000012942 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012943 // candidate functions includes at least the function call
12944 // operators of T. The function call operators of T are obtained by
12945 // ordinary lookup of the name operator() in the context of
12946 // (E).operator().
Richard Smith100b24a2014-04-17 01:52:14 +000012947 OverloadCandidateSet CandidateSet(LParenLoc,
12948 OverloadCandidateSet::CSK_Operator);
Douglas Gregor91f84212008-12-11 16:49:14 +000012949 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +000012950
John Wiegley01296292011-04-08 18:41:53 +000012951 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012952 diag::err_incomplete_object_call, Object.get()))
Douglas Gregorc473cbb2009-11-15 07:48:03 +000012953 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012954
John McCall27b18f82009-11-17 02:14:36 +000012955 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
12956 LookupQualifiedName(R, Record->getDecl());
12957 R.suppressDiagnostics();
12958
Douglas Gregorc473cbb2009-11-15 07:48:03 +000012959 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +000012960 Oper != OperEnd; ++Oper) {
John Wiegley01296292011-04-08 18:41:53 +000012961 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
George Burgess IVce6284b2017-01-28 02:19:40 +000012962 Object.get()->Classify(Context), Args, CandidateSet,
12963 /*SuppressUserConversions=*/false);
Douglas Gregor358e7742009-11-07 17:23:56 +000012964 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012965
Douglas Gregorab7897a2008-11-19 22:57:39 +000012966 // C++ [over.call.object]p2:
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000012967 // In addition, for each (non-explicit in C++0x) conversion function
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012968 // declared in T of the form
Douglas Gregorab7897a2008-11-19 22:57:39 +000012969 //
12970 // operator conversion-type-id () cv-qualifier;
12971 //
12972 // where cv-qualifier is the same cv-qualification as, or a
12973 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +000012974 // denotes the type "pointer to function of (P1,...,Pn) returning
12975 // R", or the type "reference to pointer to function of
12976 // (P1,...,Pn) returning R", or the type "reference to function
12977 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +000012978 // is also considered as a candidate function. Similarly,
12979 // surrogate call functions are added to the set of candidate
12980 // functions for each conversion function declared in an
12981 // accessible base class provided the function is not hidden
12982 // within T by another intervening declaration.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +000012983 const auto &Conversions =
12984 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
12985 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +000012986 NamedDecl *D = *I;
12987 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
12988 if (isa<UsingShadowDecl>(D))
12989 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012990
Douglas Gregor74ba25c2009-10-21 06:18:39 +000012991 // Skip over templated conversion functions; they aren't
12992 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +000012993 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +000012994 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +000012995
John McCall6e9f8f62009-12-03 04:06:58 +000012996 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012997 if (!Conv->isExplicit()) {
12998 // Strip the reference type (if any) and then the pointer type (if
12999 // any) to get down to what might be a function type.
13000 QualType ConvType = Conv->getConversionType().getNonReferenceType();
13001 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
13002 ConvType = ConvPtrType->getPointeeType();
John McCalld14a8642009-11-21 08:51:07 +000013003
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000013004 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
13005 {
13006 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000013007 Object.get(), Args, CandidateSet);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000013008 }
13009 }
Douglas Gregorab7897a2008-11-19 22:57:39 +000013010 }
Mike Stump11289f42009-09-09 15:08:12 +000013011
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013012 bool HadMultipleCandidates = (CandidateSet.size() > 1);
13013
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013014 // Perform overload resolution.
13015 OverloadCandidateSet::iterator Best;
John Wiegley01296292011-04-08 18:41:53 +000013016 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
Richard Smith67ef14f2017-09-26 18:37:55 +000013017 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013018 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +000013019 // Overload resolution succeeded; we'll build the appropriate call
13020 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013021 break;
13022
13023 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +000013024 if (CandidateSet.empty())
Daniel Dunbar62ee6412012-03-09 18:35:03 +000013025 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley01296292011-04-08 18:41:53 +000013026 << Object.get()->getType() << /*call*/ 1
13027 << Object.get()->getSourceRange();
John McCall02374852010-01-07 02:04:15 +000013028 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +000013029 Diag(Object.get()->getLocStart(),
John McCall02374852010-01-07 02:04:15 +000013030 diag::err_ovl_no_viable_object_call)
John Wiegley01296292011-04-08 18:41:53 +000013031 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000013032 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013033 break;
13034
13035 case OR_Ambiguous:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000013036 Diag(Object.get()->getLocStart(),
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013037 diag::err_ovl_ambiguous_object_call)
John Wiegley01296292011-04-08 18:41:53 +000013038 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000013039 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013040 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000013041
13042 case OR_Deleted:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000013043 Diag(Object.get()->getLocStart(),
Douglas Gregor171c45a2009-02-18 21:56:37 +000013044 diag::err_ovl_deleted_object_call)
13045 << Best->Function->isDeleted()
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000013046 << Object.get()->getType()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000013047 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley01296292011-04-08 18:41:53 +000013048 << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000013049 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000013050 break;
Mike Stump11289f42009-09-09 15:08:12 +000013051 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013052
Douglas Gregorb412e172010-07-25 18:17:45 +000013053 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013054 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013055
John McCall4124c492011-10-17 18:40:02 +000013056 UnbridgedCasts.restore();
13057
Craig Topperc3ec1492014-05-26 06:22:03 +000013058 if (Best->Function == nullptr) {
Douglas Gregorab7897a2008-11-19 22:57:39 +000013059 // Since there is no function declaration, this is one of the
13060 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +000013061 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +000013062 = cast<CXXConversionDecl>(
13063 Best->Conversions[0].UserDefined.ConversionFunction);
13064
Craig Topperc3ec1492014-05-26 06:22:03 +000013065 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
13066 Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000013067 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
13068 return ExprError();
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000013069 assert(Conv == Best->FoundDecl.getDecl() &&
Faisal Valid6676412013-06-15 11:54:37 +000013070 "Found Decl & conversion-to-functionptr should be same, right?!");
Douglas Gregorab7897a2008-11-19 22:57:39 +000013071 // We selected one of the surrogate functions that converts the
13072 // object parameter to a function pointer. Perform the conversion
13073 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013074
Fariborz Jahanian774cf792009-09-28 18:35:46 +000013075 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +000013076 // and then call it.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013077 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
13078 Conv, HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +000013079 if (Call.isInvalid())
13080 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +000013081 // Record usage of conversion in an implicit cast.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000013082 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
13083 CK_UserDefinedConversion, Call.get(),
13084 nullptr, VK_RValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013085
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000013086 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +000013087 }
13088
Craig Topperc3ec1492014-05-26 06:22:03 +000013089 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
John McCall49ec2e62010-01-28 01:54:34 +000013090
Douglas Gregorab7897a2008-11-19 22:57:39 +000013091 // We found an overloaded operator(). Build a CXXOperatorCallExpr
13092 // that calls this method, using Object for the implicit object
13093 // parameter and passing along the remaining arguments.
13094 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Nico Weber1fefe412012-11-09 06:06:14 +000013095
13096 // An error diagnostic has already been printed when parsing the declaration.
Nico Weber9512d3f2012-11-09 08:38:04 +000013097 if (Method->isInvalidDecl())
Nico Weber1fefe412012-11-09 06:06:14 +000013098 return ExprError();
13099
Chandler Carruth8e543b32010-12-12 08:17:55 +000013100 const FunctionProtoType *Proto =
13101 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013102
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000013103 unsigned NumParams = Proto->getNumParams();
Mike Stump11289f42009-09-09 15:08:12 +000013104
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000013105 DeclarationNameInfo OpLocInfo(
13106 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
13107 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Nick Lewycky134af912013-02-07 05:08:22 +000013108 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Akira Hatanaka22461672017-07-13 06:08:27 +000013109 Obj, HadMultipleCandidates,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000013110 OpLocInfo.getLoc(),
13111 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000013112 if (NewFn.isInvalid())
13113 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013114
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000013115 // Build the full argument list for the method call (the implicit object
13116 // parameter is placed at the beginning of the list).
George Burgess IV215f6e72016-12-13 19:22:56 +000013117 SmallVector<Expr *, 8> MethodArgs(Args.size() + 1);
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000013118 MethodArgs[0] = Object.get();
George Burgess IV215f6e72016-12-13 19:22:56 +000013119 std::copy(Args.begin(), Args.end(), MethodArgs.begin() + 1);
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000013120
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013121 // Once we've built TheCall, all of the expressions are properly
13122 // owned.
Alp Toker314cc812014-01-25 16:55:45 +000013123 QualType ResultTy = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000013124 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13125 ResultTy = ResultTy.getNonLValueExprType(Context);
13126
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000013127 CXXOperatorCallExpr *TheCall = new (Context)
George Burgess IV215f6e72016-12-13 19:22:56 +000013128 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(), MethodArgs, ResultTy,
Adam Nemet484aa452017-03-27 19:17:25 +000013129 VK, RParenLoc, FPOptions());
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013130
Alp Toker314cc812014-01-25 16:55:45 +000013131 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
Anders Carlsson3d5829c2009-10-13 21:49:31 +000013132 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013133
Douglas Gregor02a0acd2009-01-13 05:10:00 +000013134 // We may have default arguments. If so, we need to allocate more
13135 // slots in the call for them.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000013136 if (Args.size() < NumParams)
13137 TheCall->setNumArgs(Context, NumParams + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +000013138
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000013139 bool IsError = false;
13140
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013141 // Initialize the implicit object parameter.
John Wiegley01296292011-04-08 18:41:53 +000013142 ExprResult ObjRes =
Craig Topperc3ec1492014-05-26 06:22:03 +000013143 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000013144 Best->FoundDecl, Method);
13145 if (ObjRes.isInvalid())
13146 IsError = true;
13147 else
Benjamin Kramer62b95d82012-08-23 21:35:17 +000013148 Object = ObjRes;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013149 TheCall->setArg(0, Object.get());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000013150
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013151 // Check the argument types.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000013152 for (unsigned i = 0; i != NumParams; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013153 Expr *Arg;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000013154 if (i < Args.size()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013155 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +000013156
Douglas Gregor02a0acd2009-01-13 05:10:00 +000013157 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +000013158
John McCalldadc5752010-08-24 06:29:42 +000013159 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +000013160 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000013161 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +000013162 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +000013163 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013164
Anders Carlsson7c5fe482010-01-29 18:43:53 +000013165 IsError |= InputInit.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013166 Arg = InputInit.getAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000013167 } else {
John McCalldadc5752010-08-24 06:29:42 +000013168 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +000013169 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
13170 if (DefArg.isInvalid()) {
13171 IsError = true;
13172 break;
13173 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013174
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013175 Arg = DefArg.getAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000013176 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013177
13178 TheCall->setArg(i + 1, Arg);
13179 }
13180
13181 // If this is a variadic call, handle args passed through "...".
13182 if (Proto->isVariadic()) {
13183 // Promote the arguments (C99 6.5.2.2p7).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000013184 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
Craig Topperc3ec1492014-05-26 06:22:03 +000013185 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
13186 nullptr);
John Wiegley01296292011-04-08 18:41:53 +000013187 IsError |= Arg.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013188 TheCall->setArg(i + 1, Arg.get());
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013189 }
13190 }
13191
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000013192 if (IsError) return true;
13193
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000013194 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000013195
Richard Smith55ce3522012-06-25 20:30:08 +000013196 if (CheckFunctionCall(Method, TheCall, Proto))
Anders Carlssonbc4c1072009-08-16 01:56:34 +000013197 return true;
13198
John McCalle172be52010-08-24 06:09:16 +000013199 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013200}
13201
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013202/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +000013203/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013204/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +000013205ExprResult
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000013206Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
13207 bool *NoArrowOperatorFound) {
Chandler Carruth8e543b32010-12-12 08:17:55 +000013208 assert(Base->getType()->isRecordType() &&
13209 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +000013210
John McCall4124c492011-10-17 18:40:02 +000013211 if (checkPlaceholderForOverload(*this, Base))
13212 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000013213
John McCallbc077cf2010-02-08 23:07:23 +000013214 SourceLocation Loc = Base->getExprLoc();
13215
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013216 // C++ [over.ref]p1:
13217 //
13218 // [...] An expression x->m is interpreted as (x.operator->())->m
13219 // for a class object x of type T if T::operator->() exists and if
13220 // the operator is selected as the best match function by the
13221 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +000013222 DeclarationName OpName =
13223 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
Richard Smith100b24a2014-04-17 01:52:14 +000013224 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
Ted Kremenekc23c7e62009-07-29 21:53:49 +000013225 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +000013226
John McCallbc077cf2010-02-08 23:07:23 +000013227 if (RequireCompleteType(Loc, Base->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000013228 diag::err_typecheck_incomplete_tag, Base))
Eli Friedman132e70b2009-11-18 01:28:03 +000013229 return ExprError();
13230
John McCall27b18f82009-11-17 02:14:36 +000013231 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
13232 LookupQualifiedName(R, BaseRecord->getDecl());
13233 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +000013234
13235 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +000013236 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +000013237 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
George Burgess IVce6284b2017-01-28 02:19:40 +000013238 None, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +000013239 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013240
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013241 bool HadMultipleCandidates = (CandidateSet.size() > 1);
13242
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013243 // Perform overload resolution.
13244 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000013245 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013246 case OR_Success:
13247 // Overload resolution succeeded; we'll build the call below.
13248 break;
13249
13250 case OR_No_Viable_Function:
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000013251 if (CandidateSet.empty()) {
13252 QualType BaseType = Base->getType();
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000013253 if (NoArrowOperatorFound) {
13254 // Report this specific error to the caller instead of emitting a
13255 // diagnostic, as requested.
13256 *NoArrowOperatorFound = true;
13257 return ExprError();
13258 }
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000013259 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
13260 << BaseType << Base->getSourceRange();
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000013261 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000013262 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000013263 << FixItHint::CreateReplacement(OpLoc, ".");
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000013264 }
13265 } else
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013266 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +000013267 << "operator->" << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000013268 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000013269 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013270
13271 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000013272 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
13273 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000013274 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000013275 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000013276
13277 case OR_Deleted:
13278 Diag(OpLoc, diag::err_ovl_deleted_oper)
13279 << Best->Function->isDeleted()
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000013280 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000013281 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000013282 << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000013283 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000013284 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013285 }
13286
Craig Topperc3ec1492014-05-26 06:22:03 +000013287 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
John McCalla0296f72010-03-19 07:35:19 +000013288
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013289 // Convert the object parameter.
13290 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000013291 ExprResult BaseResult =
Craig Topperc3ec1492014-05-26 06:22:03 +000013292 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000013293 Best->FoundDecl, Method);
13294 if (BaseResult.isInvalid())
Douglas Gregord8061562009-08-06 03:17:00 +000013295 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013296 Base = BaseResult.get();
Douglas Gregor9ecea262008-11-21 03:04:22 +000013297
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013298 // Build the operator call.
Nick Lewycky134af912013-02-07 05:08:22 +000013299 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Akira Hatanaka22461672017-07-13 06:08:27 +000013300 Base, HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000013301 if (FnExpr.isInvalid())
13302 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013303
Alp Toker314cc812014-01-25 16:55:45 +000013304 QualType ResultTy = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000013305 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13306 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +000013307 CXXOperatorCallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013308 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
Adam Nemet484aa452017-03-27 19:17:25 +000013309 Base, ResultTy, VK, OpLoc, FPOptions());
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000013310
Alp Toker314cc812014-01-25 16:55:45 +000013311 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
George Burgess IVce6284b2017-01-28 02:19:40 +000013312 return ExprError();
13313
13314 if (CheckFunctionCall(Method, TheCall,
13315 Method->getType()->castAs<FunctionProtoType>()))
13316 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +000013317
13318 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013319}
13320
Richard Smithbcc22fc2012-03-09 08:00:36 +000013321/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
13322/// a literal operator described by the provided lookup results.
13323ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
13324 DeclarationNameInfo &SuffixInfo,
13325 ArrayRef<Expr*> Args,
13326 SourceLocation LitEndLoc,
13327 TemplateArgumentListInfo *TemplateArgs) {
13328 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smithc67fdd42012-03-07 08:35:16 +000013329
Richard Smith100b24a2014-04-17 01:52:14 +000013330 OverloadCandidateSet CandidateSet(UDSuffixLoc,
13331 OverloadCandidateSet::CSK_Normal);
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000013332 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
13333 /*SuppressUserConversions=*/true);
Richard Smithc67fdd42012-03-07 08:35:16 +000013334
Richard Smithbcc22fc2012-03-09 08:00:36 +000013335 bool HadMultipleCandidates = (CandidateSet.size() > 1);
13336
Richard Smithbcc22fc2012-03-09 08:00:36 +000013337 // Perform overload resolution. This will usually be trivial, but might need
13338 // to perform substitutions for a literal operator template.
13339 OverloadCandidateSet::iterator Best;
13340 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
13341 case OR_Success:
13342 case OR_Deleted:
13343 break;
13344
13345 case OR_No_Viable_Function:
13346 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
13347 << R.getLookupName();
13348 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13349 return ExprError();
13350
13351 case OR_Ambiguous:
13352 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
13353 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
13354 return ExprError();
Richard Smithc67fdd42012-03-07 08:35:16 +000013355 }
13356
Richard Smithbcc22fc2012-03-09 08:00:36 +000013357 FunctionDecl *FD = Best->Function;
Nick Lewycky134af912013-02-07 05:08:22 +000013358 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
Akira Hatanaka22461672017-07-13 06:08:27 +000013359 nullptr, HadMultipleCandidates,
Richard Smithbcc22fc2012-03-09 08:00:36 +000013360 SuffixInfo.getLoc(),
13361 SuffixInfo.getInfo());
13362 if (Fn.isInvalid())
13363 return true;
Richard Smithc67fdd42012-03-07 08:35:16 +000013364
13365 // Check the argument types. This should almost always be a no-op, except
13366 // that array-to-pointer decay is applied to string literals.
Richard Smithc67fdd42012-03-07 08:35:16 +000013367 Expr *ConvArgs[2];
Richard Smithe54c3072013-05-05 15:51:06 +000013368 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Richard Smithc67fdd42012-03-07 08:35:16 +000013369 ExprResult InputInit = PerformCopyInitialization(
13370 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
13371 SourceLocation(), Args[ArgIdx]);
13372 if (InputInit.isInvalid())
13373 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013374 ConvArgs[ArgIdx] = InputInit.get();
Richard Smithc67fdd42012-03-07 08:35:16 +000013375 }
13376
Alp Toker314cc812014-01-25 16:55:45 +000013377 QualType ResultTy = FD->getReturnType();
Richard Smithc67fdd42012-03-07 08:35:16 +000013378 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13379 ResultTy = ResultTy.getNonLValueExprType(Context);
13380
Richard Smithc67fdd42012-03-07 08:35:16 +000013381 UserDefinedLiteral *UDL =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013382 new (Context) UserDefinedLiteral(Context, Fn.get(),
Benjamin Kramerc215e762012-08-24 11:54:20 +000013383 llvm::makeArrayRef(ConvArgs, Args.size()),
Richard Smithc67fdd42012-03-07 08:35:16 +000013384 ResultTy, VK, LitEndLoc, UDSuffixLoc);
13385
Alp Toker314cc812014-01-25 16:55:45 +000013386 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
Richard Smithc67fdd42012-03-07 08:35:16 +000013387 return ExprError();
13388
Craig Topperc3ec1492014-05-26 06:22:03 +000013389 if (CheckFunctionCall(FD, UDL, nullptr))
Richard Smithc67fdd42012-03-07 08:35:16 +000013390 return ExprError();
13391
13392 return MaybeBindToTemporary(UDL);
13393}
13394
Sam Panzer0f384432012-08-21 00:52:01 +000013395/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
13396/// given LookupResult is non-empty, it is assumed to describe a member which
13397/// will be invoked. Otherwise, the function will be found via argument
13398/// dependent lookup.
13399/// CallExpr is set to a valid expression and FRS_Success returned on success,
13400/// otherwise CallExpr is set to ExprError() and some non-success value
13401/// is returned.
13402Sema::ForRangeStatus
Richard Smith9f690bd2015-10-27 06:02:45 +000013403Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
13404 SourceLocation RangeLoc,
Sam Panzer0f384432012-08-21 00:52:01 +000013405 const DeclarationNameInfo &NameInfo,
13406 LookupResult &MemberLookup,
13407 OverloadCandidateSet *CandidateSet,
13408 Expr *Range, ExprResult *CallExpr) {
Richard Smith9f690bd2015-10-27 06:02:45 +000013409 Scope *S = nullptr;
13410
Richard Smith67ef14f2017-09-26 18:37:55 +000013411 CandidateSet->clear(OverloadCandidateSet::CSK_Normal);
Sam Panzer0f384432012-08-21 00:52:01 +000013412 if (!MemberLookup.empty()) {
13413 ExprResult MemberRef =
13414 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
13415 /*IsPtr=*/false, CXXScopeSpec(),
13416 /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +000013417 /*FirstQualifierInScope=*/nullptr,
Sam Panzer0f384432012-08-21 00:52:01 +000013418 MemberLookup,
Aaron Ballman6924dcd2015-09-01 14:49:24 +000013419 /*TemplateArgs=*/nullptr, S);
Sam Panzer0f384432012-08-21 00:52:01 +000013420 if (MemberRef.isInvalid()) {
13421 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000013422 return FRS_DiagnosticIssued;
13423 }
Craig Topperc3ec1492014-05-26 06:22:03 +000013424 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
Sam Panzer0f384432012-08-21 00:52:01 +000013425 if (CallExpr->isInvalid()) {
13426 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000013427 return FRS_DiagnosticIssued;
13428 }
13429 } else {
13430 UnresolvedSet<0> FoundNames;
Sam Panzer0f384432012-08-21 00:52:01 +000013431 UnresolvedLookupExpr *Fn =
Craig Topperc3ec1492014-05-26 06:22:03 +000013432 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
Sam Panzer0f384432012-08-21 00:52:01 +000013433 NestedNameSpecifierLoc(), NameInfo,
13434 /*NeedsADL=*/true, /*Overloaded=*/false,
Richard Smithb6626742012-10-18 17:56:02 +000013435 FoundNames.begin(), FoundNames.end());
Sam Panzer0f384432012-08-21 00:52:01 +000013436
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000013437 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
Sam Panzer0f384432012-08-21 00:52:01 +000013438 CandidateSet, CallExpr);
13439 if (CandidateSet->empty() || CandidateSetError) {
13440 *CallExpr = ExprError();
13441 return FRS_NoViableFunction;
13442 }
13443 OverloadCandidateSet::iterator Best;
13444 OverloadingResult OverloadResult =
13445 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
13446
13447 if (OverloadResult == OR_No_Viable_Function) {
13448 *CallExpr = ExprError();
13449 return FRS_NoViableFunction;
13450 }
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000013451 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
Craig Topperc3ec1492014-05-26 06:22:03 +000013452 Loc, nullptr, CandidateSet, &Best,
Sam Panzer0f384432012-08-21 00:52:01 +000013453 OverloadResult,
13454 /*AllowTypoCorrection=*/false);
13455 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
13456 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000013457 return FRS_DiagnosticIssued;
13458 }
13459 }
13460 return FRS_Success;
13461}
13462
13463
Douglas Gregorcd695e52008-11-10 20:40:00 +000013464/// FixOverloadedFunctionReference - E is an expression that refers to
13465/// a C++ overloaded function (possibly with some parentheses and
13466/// perhaps a '&' around it). We have resolved the overloaded function
13467/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +000013468/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +000013469Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +000013470 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +000013471 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000013472 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
13473 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000013474 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000013475 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013476
Douglas Gregor51c538b2009-11-20 19:42:02 +000013477 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013478 }
13479
Douglas Gregor51c538b2009-11-20 19:42:02 +000013480 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000013481 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
13482 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013483 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +000013484 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +000013485 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +000013486 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +000013487 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000013488 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013489
13490 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +000013491 ICE->getCastKind(),
Craig Topperc3ec1492014-05-26 06:22:03 +000013492 SubExpr, nullptr,
John McCall2536c6d2010-08-25 10:28:54 +000013493 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013494 }
13495
Aaron Ballmanff7bd8b2016-09-02 13:45:40 +000013496 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
13497 if (!GSE->isResultDependent()) {
13498 Expr *SubExpr =
13499 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
13500 if (SubExpr == GSE->getResultExpr())
13501 return GSE;
13502
13503 // Replace the resulting type information before rebuilding the generic
13504 // selection expression.
Aaron Ballman8b871d92016-09-02 18:31:31 +000013505 ArrayRef<Expr *> A = GSE->getAssocExprs();
13506 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
Aaron Ballmanff7bd8b2016-09-02 13:45:40 +000013507 unsigned ResultIdx = GSE->getResultIndex();
13508 AssocExprs[ResultIdx] = SubExpr;
13509
13510 return new (Context) GenericSelectionExpr(
13511 Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
13512 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
13513 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
13514 ResultIdx);
13515 }
13516 // Rather than fall through to the unreachable, return the original generic
13517 // selection expression.
13518 return GSE;
13519 }
13520
Douglas Gregor51c538b2009-11-20 19:42:02 +000013521 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +000013522 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +000013523 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +000013524 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13525 if (Method->isStatic()) {
13526 // Do nothing: static member functions aren't any different
13527 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +000013528 } else {
Alp Toker028ed912013-12-06 17:56:43 +000013529 // Fix the subexpression, which really has to be an
John McCalle66edc12009-11-24 19:00:30 +000013530 // UnresolvedLookupExpr holding an overloaded member function
13531 // or template.
John McCall16df1e52010-03-30 21:47:33 +000013532 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13533 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +000013534 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000013535 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +000013536
John McCalld14a8642009-11-21 08:51:07 +000013537 assert(isa<DeclRefExpr>(SubExpr)
13538 && "fixed to something other than a decl ref");
13539 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
13540 && "fixed to a member ref with no nested name qualifier");
13541
13542 // We have taken the address of a pointer to member
13543 // function. Perform the computation here so that we get the
13544 // appropriate pointer to member type.
13545 QualType ClassType
13546 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
13547 QualType MemPtrType
13548 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
David Majnemer02d57cc2016-06-30 03:02:03 +000013549 // Under the MS ABI, lock down the inheritance model now.
13550 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13551 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
John McCalld14a8642009-11-21 08:51:07 +000013552
John McCall7decc9e2010-11-18 06:31:45 +000013553 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
13554 VK_RValue, OK_Ordinary,
13555 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +000013556 }
13557 }
John McCall16df1e52010-03-30 21:47:33 +000013558 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13559 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000013560 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000013561 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013562
John McCalle3027922010-08-25 11:45:40 +000013563 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +000013564 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +000013565 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +000013566 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013567 }
John McCalld14a8642009-11-21 08:51:07 +000013568
Richard Smith84a0b6d2016-10-18 23:39:12 +000013569 // C++ [except.spec]p17:
13570 // An exception-specification is considered to be needed when:
13571 // - in an expression the function is the unique lookup result or the
13572 // selected member of a set of overloaded functions
13573 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13574 ResolveExceptionSpec(E->getExprLoc(), FPT);
13575
John McCalld14a8642009-11-21 08:51:07 +000013576 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +000013577 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000013578 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCalle66edc12009-11-24 19:00:30 +000013579 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +000013580 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
13581 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +000013582 }
13583
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013584 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13585 ULE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000013586 ULE->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013587 Fn,
John McCall113bee02012-03-10 09:33:50 +000013588 /*enclosing*/ false, // FIXME?
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013589 ULE->getNameLoc(),
13590 Fn->getType(),
13591 VK_LValue,
13592 Found.getDecl(),
13593 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000013594 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013595 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
13596 return DRE;
John McCalld14a8642009-11-21 08:51:07 +000013597 }
13598
John McCall10eae182009-11-30 22:42:35 +000013599 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +000013600 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000013601 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCall2d74de92009-12-01 22:10:20 +000013602 if (MemExpr->hasExplicitTemplateArgs()) {
13603 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
13604 TemplateArgs = &TemplateArgsBuffer;
13605 }
John McCall6b51f282009-11-23 01:53:49 +000013606
John McCall2d74de92009-12-01 22:10:20 +000013607 Expr *Base;
13608
John McCall7decc9e2010-11-18 06:31:45 +000013609 // If we're filling in a static method where we used to have an
13610 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +000013611 if (MemExpr->isImplicitAccess()) {
13612 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013613 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13614 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000013615 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013616 Fn,
John McCall113bee02012-03-10 09:33:50 +000013617 /*enclosing*/ false,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013618 MemExpr->getMemberLoc(),
13619 Fn->getType(),
13620 VK_LValue,
13621 Found.getDecl(),
13622 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000013623 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013624 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
13625 return DRE;
Douglas Gregorb15af892010-01-07 23:12:05 +000013626 } else {
13627 SourceLocation Loc = MemExpr->getMemberLoc();
13628 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +000013629 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman73a04092012-01-07 04:59:52 +000013630 CheckCXXThisCapture(Loc);
Douglas Gregorb15af892010-01-07 23:12:05 +000013631 Base = new (Context) CXXThisExpr(Loc,
13632 MemExpr->getBaseType(),
13633 /*isImplicit=*/true);
13634 }
John McCall2d74de92009-12-01 22:10:20 +000013635 } else
John McCallc3007a22010-10-26 07:05:15 +000013636 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +000013637
John McCall4adb38c2011-04-27 00:36:17 +000013638 ExprValueKind valueKind;
13639 QualType type;
13640 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13641 valueKind = VK_LValue;
13642 type = Fn->getType();
13643 } else {
13644 valueKind = VK_RValue;
Yunzhong Gaoeba323a2015-05-01 02:04:32 +000013645 type = Context.BoundMemberTy;
13646 }
13647
13648 MemberExpr *ME = MemberExpr::Create(
13649 Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
13650 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
13651 MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
13652 OK_Ordinary);
13653 ME->setHadMultipleCandidates(true);
13654 MarkMemberReferenced(ME);
13655 return ME;
Douglas Gregor51c538b2009-11-20 19:42:02 +000013656 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013657
John McCallc3007a22010-10-26 07:05:15 +000013658 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregorcd695e52008-11-10 20:40:00 +000013659}
13660
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013661ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +000013662 DeclAccessPair Found,
13663 FunctionDecl *Fn) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000013664 return FixOverloadedFunctionReference(E.get(), Found, Fn);
Douglas Gregor3e1e5272009-12-09 23:02:17 +000013665}