blob: a8d69ea7fbadfce7859e4f9b252bede3c92a84b9 [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() ||
Erich Keane2fcbe922018-06-12 13:59:32 +0000226 getFromType()->isMemberPointerType() ||
John McCall6d1116a2010-06-11 10:04:22 +0000227 getFromType()->isObjCObjectPointerType() ||
228 getFromType()->isBlockPointerType() ||
Anders Carlsson7da7cc52010-11-05 00:12:09 +0000229 getFromType()->isNullPtrType() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000230 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
231 return true;
232
233 return false;
234}
235
Douglas Gregor5c407d92008-10-23 00:40:37 +0000236/// isPointerConversionToVoidPointer - Determines whether this
237/// conversion is a conversion of a pointer to a void pointer. This is
238/// used as part of the ranking of standard conversion sequences (C++
239/// 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000240bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000241StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000242isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall0d1da222010-01-12 00:44:57 +0000243 QualType FromType = getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000244 QualType ToType = getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +0000245
246 // Note that FromType has not necessarily been transformed by the
247 // array-to-pointer implicit conversion, so check for its presence
248 // and redo the conversion to get a pointer.
249 if (First == ICK_Array_To_Pointer)
250 FromType = Context.getArrayDecayedType(FromType);
251
Douglas Gregor5d3d3fa2011-04-15 20:45:44 +0000252 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000253 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000254 return ToPtrType->getPointeeType()->isVoidType();
255
256 return false;
257}
258
Richard Smith66e05fe2012-01-18 05:21:49 +0000259/// Skip any implicit casts which could be either part of a narrowing conversion
260/// or after one in an implicit conversion.
261static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
262 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
263 switch (ICE->getCastKind()) {
264 case CK_NoOp:
265 case CK_IntegralCast:
266 case CK_IntegralToBoolean:
267 case CK_IntegralToFloating:
George Burgess IVdf1ed002016-01-13 01:52:39 +0000268 case CK_BooleanToSignedIntegral:
Richard Smith66e05fe2012-01-18 05:21:49 +0000269 case CK_FloatingToIntegral:
270 case CK_FloatingToBoolean:
271 case CK_FloatingCast:
272 Converted = ICE->getSubExpr();
273 continue;
274
275 default:
276 return Converted;
277 }
278 }
279
280 return Converted;
281}
282
283/// Check if this standard conversion sequence represents a narrowing
284/// conversion, according to C++11 [dcl.init.list]p7.
285///
286/// \param Ctx The AST context.
287/// \param Converted The result of applying this standard conversion sequence.
288/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
289/// value of the expression prior to the narrowing conversion.
Richard Smith5614ca72012-03-23 23:55:39 +0000290/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
291/// type of the expression prior to the narrowing conversion.
Eric Fiselier0683c0e2018-05-07 21:07:10 +0000292/// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
293/// from floating point types to integral types should be ignored.
294NarrowingKind StandardConversionSequence::getNarrowingKind(
295 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
296 QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000297 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
Richard Smith66e05fe2012-01-18 05:21:49 +0000298
299 // C++11 [dcl.init.list]p7:
300 // A narrowing conversion is an implicit conversion ...
301 QualType FromType = getToType(0);
302 QualType ToType = getToType(1);
Richard Smithed638862016-03-28 06:08:37 +0000303
304 // A conversion to an enumeration type is narrowing if the conversion to
305 // the underlying type is narrowing. This only arises for expressions of
306 // the form 'Enum{init}'.
307 if (auto *ET = ToType->getAs<EnumType>())
308 ToType = ET->getDecl()->getIntegerType();
309
Richard Smith66e05fe2012-01-18 05:21:49 +0000310 switch (Second) {
Richard Smith64ecacf2015-02-19 00:39:05 +0000311 // 'bool' is an integral type; dispatch to the right place to handle it.
312 case ICK_Boolean_Conversion:
313 if (FromType->isRealFloatingType())
314 goto FloatingIntegralConversion;
315 if (FromType->isIntegralOrUnscopedEnumerationType())
316 goto IntegralConversion;
317 // Boolean conversions can be from pointers and pointers to members
318 // [conv.bool], and those aren't considered narrowing conversions.
319 return NK_Not_Narrowing;
320
Richard Smith66e05fe2012-01-18 05:21:49 +0000321 // -- from a floating-point type to an integer type, or
322 //
323 // -- from an integer type or unscoped enumeration type to a floating-point
324 // type, except where the source is a constant expression and the actual
325 // value after conversion will fit into the target type and will produce
326 // the original value when converted back to the original type, or
327 case ICK_Floating_Integral:
Richard Smith64ecacf2015-02-19 00:39:05 +0000328 FloatingIntegralConversion:
Richard Smith66e05fe2012-01-18 05:21:49 +0000329 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
330 return NK_Type_Narrowing;
Mikhail Maltsev7b1a9502018-02-21 10:08:18 +0000331 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
332 ToType->isRealFloatingType()) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +0000333 if (IgnoreFloatToIntegralConversion)
334 return NK_Not_Narrowing;
Richard Smith66e05fe2012-01-18 05:21:49 +0000335 llvm::APSInt IntConstantValue;
336 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
Simon Pilgrimf9409872017-06-01 18:13:02 +0000337 assert(Initializer && "Unknown conversion expression");
Richard Smith52e624f2016-12-21 21:42:57 +0000338
339 // If it's value-dependent, we can't tell whether it's narrowing.
340 if (Initializer->isValueDependent())
341 return NK_Dependent_Narrowing;
342
Simon Pilgrimf9409872017-06-01 18:13:02 +0000343 if (Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
Richard Smith66e05fe2012-01-18 05:21:49 +0000344 // Convert the integer to the floating type.
345 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
346 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
347 llvm::APFloat::rmNearestTiesToEven);
348 // And back.
349 llvm::APSInt ConvertedValue = IntConstantValue;
350 bool ignored;
351 Result.convertToInteger(ConvertedValue,
352 llvm::APFloat::rmTowardZero, &ignored);
353 // If the resulting value is different, this was a narrowing conversion.
354 if (IntConstantValue != ConvertedValue) {
355 ConstantValue = APValue(IntConstantValue);
Richard Smith5614ca72012-03-23 23:55:39 +0000356 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000357 return NK_Constant_Narrowing;
358 }
359 } else {
360 // Variables are always narrowings.
361 return NK_Variable_Narrowing;
362 }
363 }
364 return NK_Not_Narrowing;
365
366 // -- from long double to double or float, or from double to float, except
367 // where the source is a constant expression and the actual value after
368 // conversion is within the range of values that can be represented (even
369 // if it cannot be represented exactly), or
370 case ICK_Floating_Conversion:
371 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
372 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
373 // FromType is larger than ToType.
374 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
Richard Smith52e624f2016-12-21 21:42:57 +0000375
376 // If it's value-dependent, we can't tell whether it's narrowing.
377 if (Initializer->isValueDependent())
378 return NK_Dependent_Narrowing;
379
Richard Smith66e05fe2012-01-18 05:21:49 +0000380 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
381 // Constant!
382 assert(ConstantValue.isFloat());
383 llvm::APFloat FloatVal = ConstantValue.getFloat();
384 // Convert the source value into the target type.
385 bool ignored;
386 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
387 Ctx.getFloatTypeSemantics(ToType),
388 llvm::APFloat::rmNearestTiesToEven, &ignored);
389 // If there was no overflow, the source value is within the range of
390 // values that can be represented.
Richard Smith5614ca72012-03-23 23:55:39 +0000391 if (ConvertStatus & llvm::APFloat::opOverflow) {
392 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000393 return NK_Constant_Narrowing;
Richard Smith5614ca72012-03-23 23:55:39 +0000394 }
Richard Smith66e05fe2012-01-18 05:21:49 +0000395 } else {
396 return NK_Variable_Narrowing;
397 }
398 }
399 return NK_Not_Narrowing;
400
401 // -- from an integer type or unscoped enumeration type to an integer type
402 // that cannot represent all the values of the original type, except where
403 // the source is a constant expression and the actual value after
404 // conversion will fit into the target type and will produce the original
405 // value when converted back to the original type.
Richard Smith64ecacf2015-02-19 00:39:05 +0000406 case ICK_Integral_Conversion:
407 IntegralConversion: {
Richard Smith66e05fe2012-01-18 05:21:49 +0000408 assert(FromType->isIntegralOrUnscopedEnumerationType());
409 assert(ToType->isIntegralOrUnscopedEnumerationType());
410 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
411 const unsigned FromWidth = Ctx.getIntWidth(FromType);
412 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
413 const unsigned ToWidth = Ctx.getIntWidth(ToType);
414
415 if (FromWidth > ToWidth ||
Richard Smith25a80d42012-06-13 01:07:41 +0000416 (FromWidth == ToWidth && FromSigned != ToSigned) ||
417 (FromSigned && !ToSigned)) {
Richard Smith66e05fe2012-01-18 05:21:49 +0000418 // Not all values of FromType can be represented in ToType.
419 llvm::APSInt InitializerValue;
420 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
Richard Smith52e624f2016-12-21 21:42:57 +0000421
422 // If it's value-dependent, we can't tell whether it's narrowing.
423 if (Initializer->isValueDependent())
424 return NK_Dependent_Narrowing;
425
Richard Smith25a80d42012-06-13 01:07:41 +0000426 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
427 // Such conversions on variables are always narrowing.
428 return NK_Variable_Narrowing;
Richard Smith72cd8ea2012-06-19 21:28:35 +0000429 }
430 bool Narrowing = false;
431 if (FromWidth < ToWidth) {
Richard Smith25a80d42012-06-13 01:07:41 +0000432 // Negative -> unsigned is narrowing. Otherwise, more bits is never
433 // narrowing.
434 if (InitializerValue.isSigned() && InitializerValue.isNegative())
Richard Smith72cd8ea2012-06-19 21:28:35 +0000435 Narrowing = true;
Richard Smith25a80d42012-06-13 01:07:41 +0000436 } else {
Richard Smith66e05fe2012-01-18 05:21:49 +0000437 // Add a bit to the InitializerValue so we don't have to worry about
438 // signed vs. unsigned comparisons.
439 InitializerValue = InitializerValue.extend(
440 InitializerValue.getBitWidth() + 1);
441 // Convert the initializer to and from the target width and signed-ness.
442 llvm::APSInt ConvertedValue = InitializerValue;
443 ConvertedValue = ConvertedValue.trunc(ToWidth);
444 ConvertedValue.setIsSigned(ToSigned);
445 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
446 ConvertedValue.setIsSigned(InitializerValue.isSigned());
447 // If the result is different, this was a narrowing conversion.
Richard Smith72cd8ea2012-06-19 21:28:35 +0000448 if (ConvertedValue != InitializerValue)
449 Narrowing = true;
450 }
451 if (Narrowing) {
452 ConstantType = Initializer->getType();
453 ConstantValue = APValue(InitializerValue);
454 return NK_Constant_Narrowing;
Richard Smith66e05fe2012-01-18 05:21:49 +0000455 }
456 }
457 return NK_Not_Narrowing;
458 }
459
460 default:
461 // Other kinds of conversions are not narrowings.
462 return NK_Not_Narrowing;
463 }
464}
465
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000466/// dump - Print this standard conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000467/// error. Useful for debugging overloading issues.
Yaron Kerencdae9412016-01-29 19:38:18 +0000468LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000469 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000470 bool PrintedSomething = false;
471 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000472 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000473 PrintedSomething = true;
474 }
475
476 if (Second != ICK_Identity) {
477 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000478 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000479 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000480 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000481
482 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000483 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000484 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000485 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000486 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000487 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000488 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000489 PrintedSomething = true;
490 }
491
492 if (Third != ICK_Identity) {
493 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000494 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000495 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000496 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000497 PrintedSomething = true;
498 }
499
500 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000501 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000502 }
503}
504
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000505/// dump - Print this user-defined conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000506/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000507void UserDefinedConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000508 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000509 if (Before.First || Before.Second || Before.Third) {
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000510 Before.dump();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000511 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000512 }
Sebastian Redl72ef7bc2011-11-01 15:53:09 +0000513 if (ConversionFunction)
514 OS << '\'' << *ConversionFunction << '\'';
515 else
516 OS << "aggregate initialization";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000517 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000518 OS << " -> ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000519 After.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000520 }
521}
522
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000523/// dump - Print this implicit conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000524/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000525void ImplicitConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000526 raw_ostream &OS = llvm::errs();
Richard Smitha93f1022013-09-06 22:30:28 +0000527 if (isStdInitializerListElement())
528 OS << "Worst std::initializer_list element conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000529 switch (ConversionKind) {
530 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000531 OS << "Standard conversion: ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000532 Standard.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000533 break;
534 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000535 OS << "User-defined conversion: ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000536 UserDefined.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000537 break;
538 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000539 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000540 break;
John McCall0d1da222010-01-12 00:44:57 +0000541 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000542 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000543 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000544 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000545 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000546 break;
547 }
548
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000549 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000550}
551
John McCall0d1da222010-01-12 00:44:57 +0000552void AmbiguousConversionSequence::construct() {
553 new (&conversions()) ConversionSet();
554}
555
556void AmbiguousConversionSequence::destruct() {
557 conversions().~ConversionSet();
558}
559
560void
561AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
562 FromTypePtr = O.FromTypePtr;
563 ToTypePtr = O.ToTypePtr;
564 new (&conversions()) ConversionSet(O.conversions());
565}
566
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000567namespace {
Larisse Voufo98b20f12013-07-19 23:00:19 +0000568 // Structure used by DeductionFailureInfo to store
Richard Smith44ecdbd2013-01-31 05:19:49 +0000569 // template argument information.
570 struct DFIArguments {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000571 TemplateArgument FirstArg;
572 TemplateArgument SecondArg;
573 };
Larisse Voufo98b20f12013-07-19 23:00:19 +0000574 // Structure used by DeductionFailureInfo to store
Richard Smith44ecdbd2013-01-31 05:19:49 +0000575 // template parameter and template argument information.
576 struct DFIParamWithArguments : DFIArguments {
577 TemplateParameter Param;
578 };
Richard Smith9b534542015-12-31 02:02:54 +0000579 // Structure used by DeductionFailureInfo to store template argument
580 // information and the index of the problematic call argument.
581 struct DFIDeducedMismatchArgs : DFIArguments {
582 TemplateArgumentList *TemplateArgs;
583 unsigned CallArgIndex;
584 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000585}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000586
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000587/// Convert from Sema's representation of template deduction information
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000588/// to the form used in overload-candidate information.
Richard Smith17c00b42014-11-12 01:24:00 +0000589DeductionFailureInfo
590clang::MakeDeductionFailureInfo(ASTContext &Context,
591 Sema::TemplateDeductionResult TDK,
592 TemplateDeductionInfo &Info) {
Larisse Voufo98b20f12013-07-19 23:00:19 +0000593 DeductionFailureInfo Result;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000594 Result.Result = static_cast<unsigned>(TDK);
Richard Smith9ca64612012-05-07 09:03:25 +0000595 Result.HasDiagnostic = false;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000596 switch (TDK) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000597 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000598 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000599 case Sema::TDK_TooManyArguments:
600 case Sema::TDK_TooFewArguments:
Richard Smith9b534542015-12-31 02:02:54 +0000601 case Sema::TDK_MiscellaneousDeductionFailure:
Artem Belevich13e9b4d2016-12-07 19:27:16 +0000602 case Sema::TDK_CUDATargetMismatch:
Richard Smith9b534542015-12-31 02:02:54 +0000603 Result.Data = nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000604 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000605
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000606 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000607 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000608 Result.Data = Info.Param.getOpaqueValue();
609 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000610
Richard Smithc92d2062017-01-05 23:02:44 +0000611 case Sema::TDK_DeducedMismatch:
612 case Sema::TDK_DeducedMismatchNested: {
Richard Smith9b534542015-12-31 02:02:54 +0000613 // FIXME: Should allocate from normal heap so that we can free this later.
614 auto *Saved = new (Context) DFIDeducedMismatchArgs;
615 Saved->FirstArg = Info.FirstArg;
616 Saved->SecondArg = Info.SecondArg;
617 Saved->TemplateArgs = Info.take();
618 Saved->CallArgIndex = Info.CallArgIndex;
619 Result.Data = Saved;
620 break;
621 }
622
Richard Smith44ecdbd2013-01-31 05:19:49 +0000623 case Sema::TDK_NonDeducedMismatch: {
624 // FIXME: Should allocate from normal heap so that we can free this later.
625 DFIArguments *Saved = new (Context) DFIArguments;
626 Saved->FirstArg = Info.FirstArg;
627 Saved->SecondArg = Info.SecondArg;
628 Result.Data = Saved;
629 break;
630 }
631
Richard Smith4a8f3512018-07-19 19:00:37 +0000632 case Sema::TDK_IncompletePack:
633 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000634 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000635 case Sema::TDK_Underqualified: {
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000636 // FIXME: Should allocate from normal heap so that we can free this later.
637 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000638 Saved->Param = Info.Param;
639 Saved->FirstArg = Info.FirstArg;
640 Saved->SecondArg = Info.SecondArg;
641 Result.Data = Saved;
642 break;
643 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000644
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000645 case Sema::TDK_SubstitutionFailure:
Douglas Gregord09efd42010-05-08 20:07:26 +0000646 Result.Data = Info.take();
Richard Smith9ca64612012-05-07 09:03:25 +0000647 if (Info.hasSFINAEDiagnostic()) {
648 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
649 SourceLocation(), PartialDiagnostic::NullDiagnostic());
650 Info.takeSFINAEDiagnostic(*Diag);
651 Result.HasDiagnostic = true;
652 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000653 break;
Richard Smith6eedfe72017-01-09 08:01:21 +0000654
655 case Sema::TDK_Success:
656 case Sema::TDK_NonDependentConversionFailure:
657 llvm_unreachable("not a deduction failure");
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000658 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000659
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000660 return Result;
661}
John McCall0d1da222010-01-12 00:44:57 +0000662
Larisse Voufo98b20f12013-07-19 23:00:19 +0000663void DeductionFailureInfo::Destroy() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000664 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
665 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000666 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000667 case Sema::TDK_InstantiationDepth:
668 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000669 case Sema::TDK_TooManyArguments:
670 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000671 case Sema::TDK_InvalidExplicitArguments:
Artem Belevich13e9b4d2016-12-07 19:27:16 +0000672 case Sema::TDK_CUDATargetMismatch:
Richard Smith6eedfe72017-01-09 08:01:21 +0000673 case Sema::TDK_NonDependentConversionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000674 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000675
Richard Smith4a8f3512018-07-19 19:00:37 +0000676 case Sema::TDK_IncompletePack:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000677 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000678 case Sema::TDK_Underqualified:
Richard Smith9b534542015-12-31 02:02:54 +0000679 case Sema::TDK_DeducedMismatch:
Richard Smithc92d2062017-01-05 23:02:44 +0000680 case Sema::TDK_DeducedMismatchNested:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000681 case Sema::TDK_NonDeducedMismatch:
Douglas Gregorb02d6b32010-05-08 20:20:05 +0000682 // FIXME: Destroy the data?
Craig Topperc3ec1492014-05-26 06:22:03 +0000683 Data = nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000684 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000685
686 case Sema::TDK_SubstitutionFailure:
Richard Smith9ca64612012-05-07 09:03:25 +0000687 // FIXME: Destroy the template argument list?
Craig Topperc3ec1492014-05-26 06:22:03 +0000688 Data = nullptr;
Richard Smith9ca64612012-05-07 09:03:25 +0000689 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
690 Diag->~PartialDiagnosticAt();
691 HasDiagnostic = false;
692 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000693 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000694
Douglas Gregor461761d2010-05-08 18:20:53 +0000695 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000696 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000697 break;
698 }
699}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000700
Larisse Voufo98b20f12013-07-19 23:00:19 +0000701PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
Richard Smith9ca64612012-05-07 09:03:25 +0000702 if (HasDiagnostic)
703 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
Craig Topperc3ec1492014-05-26 06:22:03 +0000704 return nullptr;
Richard Smith9ca64612012-05-07 09:03:25 +0000705}
706
Larisse Voufo98b20f12013-07-19 23:00:19 +0000707TemplateParameter DeductionFailureInfo::getTemplateParameter() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000708 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
709 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000710 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000711 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000712 case Sema::TDK_TooManyArguments:
713 case Sema::TDK_TooFewArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000714 case Sema::TDK_SubstitutionFailure:
Richard Smith9b534542015-12-31 02:02:54 +0000715 case Sema::TDK_DeducedMismatch:
Richard Smithc92d2062017-01-05 23:02:44 +0000716 case Sema::TDK_DeducedMismatchNested:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000717 case Sema::TDK_NonDeducedMismatch:
Artem Belevich13e9b4d2016-12-07 19:27:16 +0000718 case Sema::TDK_CUDATargetMismatch:
Richard Smith6eedfe72017-01-09 08:01:21 +0000719 case Sema::TDK_NonDependentConversionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000720 return TemplateParameter();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000721
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000722 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000723 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000724 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000725
Richard Smith4a8f3512018-07-19 19:00:37 +0000726 case Sema::TDK_IncompletePack:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000727 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000728 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000729 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000730
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000731 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000732 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000733 break;
734 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000735
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000736 return TemplateParameter();
737}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000738
Larisse Voufo98b20f12013-07-19 23:00:19 +0000739TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
Douglas Gregord09efd42010-05-08 20:07:26 +0000740 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
Richard Smith44ecdbd2013-01-31 05:19:49 +0000741 case Sema::TDK_Success:
742 case Sema::TDK_Invalid:
743 case Sema::TDK_InstantiationDepth:
744 case Sema::TDK_TooManyArguments:
745 case Sema::TDK_TooFewArguments:
746 case Sema::TDK_Incomplete:
Richard Smith4a8f3512018-07-19 19:00:37 +0000747 case Sema::TDK_IncompletePack:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000748 case Sema::TDK_InvalidExplicitArguments:
749 case Sema::TDK_Inconsistent:
750 case Sema::TDK_Underqualified:
751 case Sema::TDK_NonDeducedMismatch:
Artem Belevich13e9b4d2016-12-07 19:27:16 +0000752 case Sema::TDK_CUDATargetMismatch:
Richard Smith6eedfe72017-01-09 08:01:21 +0000753 case Sema::TDK_NonDependentConversionFailure:
Craig Topperc3ec1492014-05-26 06:22:03 +0000754 return nullptr;
Douglas Gregord09efd42010-05-08 20:07:26 +0000755
Richard Smith9b534542015-12-31 02:02:54 +0000756 case Sema::TDK_DeducedMismatch:
Richard Smithc92d2062017-01-05 23:02:44 +0000757 case Sema::TDK_DeducedMismatchNested:
Richard Smith9b534542015-12-31 02:02:54 +0000758 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
759
Richard Smith44ecdbd2013-01-31 05:19:49 +0000760 case Sema::TDK_SubstitutionFailure:
761 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000762
Richard Smith44ecdbd2013-01-31 05:19:49 +0000763 // Unhandled
764 case Sema::TDK_MiscellaneousDeductionFailure:
765 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000766 }
767
Craig Topperc3ec1492014-05-26 06:22:03 +0000768 return nullptr;
Douglas Gregord09efd42010-05-08 20:07:26 +0000769}
770
Larisse Voufo98b20f12013-07-19 23:00:19 +0000771const TemplateArgument *DeductionFailureInfo::getFirstArg() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000772 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
773 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000774 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000775 case Sema::TDK_InstantiationDepth:
776 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000777 case Sema::TDK_TooManyArguments:
778 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000779 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000780 case Sema::TDK_SubstitutionFailure:
Artem Belevich13e9b4d2016-12-07 19:27:16 +0000781 case Sema::TDK_CUDATargetMismatch:
Richard Smith6eedfe72017-01-09 08:01:21 +0000782 case Sema::TDK_NonDependentConversionFailure:
Craig Topperc3ec1492014-05-26 06:22:03 +0000783 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000784
Richard Smith4a8f3512018-07-19 19:00:37 +0000785 case Sema::TDK_IncompletePack:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000786 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000787 case Sema::TDK_Underqualified:
Richard Smith9b534542015-12-31 02:02:54 +0000788 case Sema::TDK_DeducedMismatch:
Richard Smithc92d2062017-01-05 23:02:44 +0000789 case Sema::TDK_DeducedMismatchNested:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000790 case Sema::TDK_NonDeducedMismatch:
791 return &static_cast<DFIArguments*>(Data)->FirstArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000792
Douglas Gregor461761d2010-05-08 18:20:53 +0000793 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000794 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000795 break;
796 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000797
Craig Topperc3ec1492014-05-26 06:22:03 +0000798 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000799}
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000800
Larisse Voufo98b20f12013-07-19 23:00:19 +0000801const TemplateArgument *DeductionFailureInfo::getSecondArg() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000802 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
803 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000804 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000805 case Sema::TDK_InstantiationDepth:
806 case Sema::TDK_Incomplete:
Richard Smith4a8f3512018-07-19 19:00:37 +0000807 case Sema::TDK_IncompletePack:
Douglas Gregor461761d2010-05-08 18:20:53 +0000808 case Sema::TDK_TooManyArguments:
809 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000810 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000811 case Sema::TDK_SubstitutionFailure:
Artem Belevich13e9b4d2016-12-07 19:27:16 +0000812 case Sema::TDK_CUDATargetMismatch:
Richard Smith6eedfe72017-01-09 08:01:21 +0000813 case Sema::TDK_NonDependentConversionFailure:
Craig Topperc3ec1492014-05-26 06:22:03 +0000814 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000815
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000816 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000817 case Sema::TDK_Underqualified:
Richard Smith9b534542015-12-31 02:02:54 +0000818 case Sema::TDK_DeducedMismatch:
Richard Smithc92d2062017-01-05 23:02:44 +0000819 case Sema::TDK_DeducedMismatchNested:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000820 case Sema::TDK_NonDeducedMismatch:
821 return &static_cast<DFIArguments*>(Data)->SecondArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000822
Douglas Gregor461761d2010-05-08 18:20:53 +0000823 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000824 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000825 break;
826 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000827
Craig Topperc3ec1492014-05-26 06:22:03 +0000828 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000829}
830
Richard Smith9b534542015-12-31 02:02:54 +0000831llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
Richard Smithc92d2062017-01-05 23:02:44 +0000832 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
833 case Sema::TDK_DeducedMismatch:
834 case Sema::TDK_DeducedMismatchNested:
Richard Smith9b534542015-12-31 02:02:54 +0000835 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
836
Richard Smithc92d2062017-01-05 23:02:44 +0000837 default:
838 return llvm::None;
839 }
Richard Smith9b534542015-12-31 02:02:54 +0000840}
841
Benjamin Kramer97e59492012-10-09 15:52:25 +0000842void OverloadCandidateSet::destroyCandidates() {
Richard Smith0bf93aa2012-07-18 23:52:59 +0000843 for (iterator i = begin(), e = end(); i != e; ++i) {
Richard Smith6eedfe72017-01-09 08:01:21 +0000844 for (auto &C : i->Conversions)
845 C.~ImplicitConversionSequence();
Richard Smith0bf93aa2012-07-18 23:52:59 +0000846 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
847 i->DeductionFailure.Destroy();
848 }
Benjamin Kramer97e59492012-10-09 15:52:25 +0000849}
850
Richard Smith67ef14f2017-09-26 18:37:55 +0000851void OverloadCandidateSet::clear(CandidateSetKind CSK) {
Benjamin Kramer97e59492012-10-09 15:52:25 +0000852 destroyCandidates();
George Burgess IV177399e2017-01-09 04:12:14 +0000853 SlabAllocator.Reset();
854 NumInlineBytesUsed = 0;
Benjamin Kramerfb761ff2012-01-14 16:31:55 +0000855 Candidates.clear();
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000856 Functions.clear();
Richard Smith67ef14f2017-09-26 18:37:55 +0000857 Kind = CSK;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000858}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000859
John McCall4124c492011-10-17 18:40:02 +0000860namespace {
861 class UnbridgedCastsSet {
862 struct Entry {
863 Expr **Addr;
864 Expr *Saved;
865 };
866 SmallVector<Entry, 2> Entries;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +0000867
John McCall4124c492011-10-17 18:40:02 +0000868 public:
869 void save(Sema &S, Expr *&E) {
870 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
871 Entry entry = { &E, E };
872 Entries.push_back(entry);
873 E = S.stripARCUnbridgedCast(E);
874 }
875
876 void restore() {
877 for (SmallVectorImpl<Entry>::iterator
Simon Pilgrimfb9662a2017-06-01 18:17:18 +0000878 i = Entries.begin(), e = Entries.end(); i != e; ++i)
John McCall4124c492011-10-17 18:40:02 +0000879 *i->Addr = i->Saved;
880 }
881 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000882}
John McCall4124c492011-10-17 18:40:02 +0000883
884/// checkPlaceholderForOverload - Do any interesting placeholder-like
885/// preprocessing on the given expression.
886///
887/// \param unbridgedCasts a collection to which to add unbridged casts;
888/// without this, they will be immediately diagnosed as errors
889///
890/// Return true on unrecoverable error.
Craig Topperc3ec1492014-05-26 06:22:03 +0000891static bool
892checkPlaceholderForOverload(Sema &S, Expr *&E,
893 UnbridgedCastsSet *unbridgedCasts = nullptr) {
John McCall4124c492011-10-17 18:40:02 +0000894 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
895 // We can't handle overloaded expressions here because overload
896 // resolution might reasonably tweak them.
897 if (placeholder->getKind() == BuiltinType::Overload) return false;
898
899 // If the context potentially accepts unbridged ARC casts, strip
900 // the unbridged cast and add it to the collection for later restoration.
901 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
902 unbridgedCasts) {
903 unbridgedCasts->save(S, E);
904 return false;
905 }
906
907 // Go ahead and check everything else.
908 ExprResult result = S.CheckPlaceholderExpr(E);
909 if (result.isInvalid())
910 return true;
911
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000912 E = result.get();
John McCall4124c492011-10-17 18:40:02 +0000913 return false;
914 }
915
916 // Nothing to do.
917 return false;
918}
919
920/// checkArgPlaceholdersForOverload - Check a set of call operands for
921/// placeholders.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000922static bool checkArgPlaceholdersForOverload(Sema &S,
923 MultiExprArg Args,
John McCall4124c492011-10-17 18:40:02 +0000924 UnbridgedCastsSet &unbridged) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000925 for (unsigned i = 0, e = Args.size(); i != e; ++i)
926 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
John McCall4124c492011-10-17 18:40:02 +0000927 return true;
928
929 return false;
930}
931
George Burgess IV2d82b092017-04-06 00:23:31 +0000932/// Determine whether the given New declaration is an overload of the
933/// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if
934/// New and Old cannot be overloaded, e.g., if New has the same signature as
935/// some function in Old (C++ 1.3.10) or if the Old declarations aren't
936/// functions (or function templates) at all. When it does return Ovl_Match or
937/// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be
938/// overloaded with. This decl may be a UsingShadowDecl on top of the underlying
939/// declaration.
940///
941/// Example: Given the following input:
942///
943/// void f(int, float); // #1
944/// void f(int, int); // #2
945/// int f(int, int); // #3
946///
947/// When we process #1, there is no previous declaration of "f", so IsOverload
948/// will not be used.
949///
950/// When we process #2, Old contains only the FunctionDecl for #1. By comparing
951/// the parameter types, we see that #1 and #2 are overloaded (since they have
952/// different signatures), so this routine returns Ovl_Overload; MatchedDecl is
953/// unchanged.
954///
955/// When we process #3, Old is an overload set containing #1 and #2. We compare
956/// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then
957/// #3 to #2. Since the signatures of #3 and #2 are identical (return types of
958/// functions are not part of the signature), IsOverload returns Ovl_Match and
959/// MatchedDecl will be set to point to the FunctionDecl for #2.
960///
961/// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class
962/// by a using declaration. The rules for whether to hide shadow declarations
963/// ignore some properties which otherwise figure into a function template's
964/// signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000965Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000966Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
967 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000968 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000969 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000970 NamedDecl *OldD = *I;
971
972 bool OldIsUsingDecl = false;
973 if (isa<UsingShadowDecl>(OldD)) {
974 OldIsUsingDecl = true;
975
976 // We can always introduce two using declarations into the same
977 // context, even if they have identical signatures.
978 if (NewIsUsingDecl) continue;
979
980 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
981 }
982
Richard Smithf091e122015-09-15 01:28:55 +0000983 // A using-declaration does not conflict with another declaration
984 // if one of them is hidden.
985 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
986 continue;
987
John McCalle9cccd82010-06-16 08:42:20 +0000988 // If either declaration was introduced by a using declaration,
989 // we'll need to use slightly different rules for matching.
990 // Essentially, these rules are the normal rules, except that
991 // function templates hide function templates with different
992 // return types or template parameter lists.
993 bool UseMemberUsingDeclRules =
John McCallc70fca62013-04-03 21:19:47 +0000994 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
995 !New->getFriendObjectKind();
John McCalle9cccd82010-06-16 08:42:20 +0000996
Alp Tokera2794f92014-01-22 07:29:52 +0000997 if (FunctionDecl *OldF = OldD->getAsFunction()) {
John McCalle9cccd82010-06-16 08:42:20 +0000998 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
999 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1000 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
1001 continue;
1002 }
1003
Alp Tokera2794f92014-01-22 07:29:52 +00001004 if (!isa<FunctionTemplateDecl>(OldD) &&
1005 !shouldLinkPossiblyHiddenDecl(*I, New))
Rafael Espindola5bddd6a2013-04-15 12:49:13 +00001006 continue;
1007
John McCalldaa3d6b2009-12-09 03:35:25 +00001008 Match = *I;
1009 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +00001010 }
Erich Keane41af9712018-04-16 21:30:08 +00001011
1012 // Builtins that have custom typechecking or have a reference should
1013 // not be overloadable or redeclarable.
1014 if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1015 Match = *I;
1016 return Ovl_NonFunction;
1017 }
Richard Smith151c4562016-12-20 21:35:28 +00001018 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +00001019 // We can overload with these, which can show up when doing
1020 // redeclaration checks for UsingDecls.
1021 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalla8987a2942010-11-10 03:01:53 +00001022 } else if (isa<TagDecl>(OldD)) {
1023 // We can always overload with tags by hiding them.
Richard Smithd8a9e372016-12-18 21:39:37 +00001024 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +00001025 // Optimistically assume that an unresolved using decl will
1026 // overload; if it doesn't, we'll have to diagnose during
1027 // template instantiation.
Richard Smithd8a9e372016-12-18 21:39:37 +00001028 //
1029 // Exception: if the scope is dependent and this is not a class
1030 // member, the using declaration can only introduce an enumerator.
1031 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1032 Match = *I;
1033 return Ovl_NonFunction;
1034 }
John McCall84d87672009-12-10 09:41:52 +00001035 } else {
John McCall1f82f242009-11-18 22:49:29 +00001036 // (C++ 13p1):
1037 // Only function declarations can be overloaded; object and type
1038 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +00001039 Match = *I;
1040 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +00001041 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001042 }
John McCall1f82f242009-11-18 22:49:29 +00001043
John McCalldaa3d6b2009-12-09 03:35:25 +00001044 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +00001045}
1046
Richard Smithac974a32013-06-30 09:48:50 +00001047bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
Justin Lebarba122ab2016-03-30 23:30:21 +00001048 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
Richard Smithac974a32013-06-30 09:48:50 +00001049 // C++ [basic.start.main]p2: This function shall not be overloaded.
1050 if (New->isMain())
Rafael Espindola576127d2012-12-28 14:21:58 +00001051 return false;
Rafael Espindola7cf35ef2013-01-12 01:47:40 +00001052
David Majnemerc729b0b2013-09-16 22:44:20 +00001053 // MSVCRT user defined entry points cannot be overloaded.
1054 if (New->isMSVCRTEntryPoint())
1055 return false;
1056
John McCall1f82f242009-11-18 22:49:29 +00001057 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1058 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1059
1060 // C++ [temp.fct]p2:
1061 // A function template can be overloaded with other function templates
1062 // and with normal (non-template) functions.
Craig Topperc3ec1492014-05-26 06:22:03 +00001063 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
John McCall1f82f242009-11-18 22:49:29 +00001064 return true;
1065
1066 // Is the function New an overload of the function Old?
Richard Smithac974a32013-06-30 09:48:50 +00001067 QualType OldQType = Context.getCanonicalType(Old->getType());
1068 QualType NewQType = Context.getCanonicalType(New->getType());
John McCall1f82f242009-11-18 22:49:29 +00001069
1070 // Compare the signatures (C++ 1.3.10) of the two functions to
1071 // determine whether they are overloads. If we find any mismatch
1072 // in the signature, they are overloads.
1073
1074 // If either of these functions is a K&R-style function (no
1075 // prototype), then we consider them to have matching signatures.
1076 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1077 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1078 return false;
1079
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001080 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1081 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
John McCall1f82f242009-11-18 22:49:29 +00001082
1083 // The signature of a function includes the types of its
1084 // parameters (C++ 1.3.10), which includes the presence or absence
1085 // of the ellipsis; see C++ DR 357).
1086 if (OldQType != NewQType &&
Alp Toker9cacbab2014-01-20 20:26:09 +00001087 (OldType->getNumParams() != NewType->getNumParams() ||
John McCall1f82f242009-11-18 22:49:29 +00001088 OldType->isVariadic() != NewType->isVariadic() ||
Alp Toker9cacbab2014-01-20 20:26:09 +00001089 !FunctionParamTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +00001090 return true;
1091
1092 // C++ [temp.over.link]p4:
1093 // The signature of a function template consists of its function
1094 // signature, its return type and its template parameter list. The names
1095 // of the template parameters are significant only for establishing the
1096 // relationship between the template parameters and the rest of the
1097 // signature.
1098 //
1099 // We check the return type and template parameter lists for function
1100 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +00001101 //
1102 // However, we don't consider either of these when deciding whether
1103 // a member introduced by a shadow declaration is hidden.
Justin Lebar39fd5292016-03-30 20:41:05 +00001104 if (!UseMemberUsingDeclRules && NewTemplate &&
Richard Smithac974a32013-06-30 09:48:50 +00001105 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1106 OldTemplate->getTemplateParameters(),
1107 false, TPL_TemplateMatch) ||
Richard Smith4576a772018-09-10 06:35:32 +00001108 !Context.hasSameType(Old->getDeclaredReturnType(),
1109 New->getDeclaredReturnType())))
John McCall1f82f242009-11-18 22:49:29 +00001110 return true;
1111
1112 // If the function is a class member, its signature includes the
Douglas Gregorb2f8aa92011-01-26 17:47:49 +00001113 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall1f82f242009-11-18 22:49:29 +00001114 //
1115 // As part of this, also check whether one of the member functions
1116 // is static, in which case they are not overloads (C++
1117 // 13.1p2). While not part of the definition of the signature,
1118 // this check is important to determine whether these functions
1119 // can be overloaded.
Richard Smith574f4f62013-01-14 05:37:29 +00001120 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1121 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
John McCall1f82f242009-11-18 22:49:29 +00001122 if (OldMethod && NewMethod &&
Richard Smith574f4f62013-01-14 05:37:29 +00001123 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1124 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
Justin Lebar39fd5292016-03-30 20:41:05 +00001125 if (!UseMemberUsingDeclRules &&
Richard Smith574f4f62013-01-14 05:37:29 +00001126 (OldMethod->getRefQualifier() == RQ_None ||
1127 NewMethod->getRefQualifier() == RQ_None)) {
1128 // C++0x [over.load]p2:
1129 // - Member function declarations with the same name and the same
1130 // parameter-type-list as well as member function template
1131 // declarations with the same name, the same parameter-type-list, and
1132 // the same template parameter lists cannot be overloaded if any of
1133 // them, but not all, have a ref-qualifier (8.3.5).
Richard Smithac974a32013-06-30 09:48:50 +00001134 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
Richard Smith574f4f62013-01-14 05:37:29 +00001135 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
Richard Smithac974a32013-06-30 09:48:50 +00001136 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
Richard Smith574f4f62013-01-14 05:37:29 +00001137 }
1138 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001139 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001140
Richard Smith574f4f62013-01-14 05:37:29 +00001141 // We may not have applied the implicit const for a constexpr member
1142 // function yet (because we haven't yet resolved whether this is a static
1143 // or non-static member function). Add it now, on the assumption that this
1144 // is a redeclaration of OldMethod.
David Majnemer42350df2013-11-03 23:51:28 +00001145 unsigned OldQuals = OldMethod->getTypeQualifiers();
Richard Smith574f4f62013-01-14 05:37:29 +00001146 unsigned NewQuals = NewMethod->getTypeQualifiers();
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001147 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
Richard Smithe83b1d32013-06-25 18:46:26 +00001148 !isa<CXXConstructorDecl>(NewMethod))
Richard Smith574f4f62013-01-14 05:37:29 +00001149 NewQuals |= Qualifiers::Const;
David Majnemer42350df2013-11-03 23:51:28 +00001150
1151 // We do not allow overloading based off of '__restrict'.
1152 OldQuals &= ~Qualifiers::Restrict;
1153 NewQuals &= ~Qualifiers::Restrict;
1154 if (OldQuals != NewQuals)
Richard Smith574f4f62013-01-14 05:37:29 +00001155 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001156 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001157
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001158 // Though pass_object_size is placed on parameters and takes an argument, we
1159 // consider it to be a function-level modifier for the sake of function
1160 // identity. Either the function has one or more parameters with
1161 // pass_object_size or it doesn't.
1162 if (functionHasPassObjectSizeParams(New) !=
1163 functionHasPassObjectSizeParams(Old))
1164 return true;
1165
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001166 // enable_if attributes are an order-sensitive part of the signature.
1167 for (specific_attr_iterator<EnableIfAttr>
1168 NewI = New->specific_attr_begin<EnableIfAttr>(),
1169 NewE = New->specific_attr_end<EnableIfAttr>(),
1170 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1171 OldE = Old->specific_attr_end<EnableIfAttr>();
1172 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1173 if (NewI == NewE || OldI == OldE)
1174 return true;
1175 llvm::FoldingSetNodeID NewID, OldID;
1176 NewI->getCond()->Profile(NewID, Context, true);
1177 OldI->getCond()->Profile(OldID, Context, true);
Nick Lewyckyd950ae72014-01-21 01:30:30 +00001178 if (NewID != OldID)
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001179 return true;
1180 }
1181
Justin Lebarba122ab2016-03-30 23:30:21 +00001182 if (getLangOpts().CUDA && ConsiderCudaAttrs) {
Justin Lebare060feb2016-10-03 16:48:23 +00001183 // Don't allow overloading of destructors. (In theory we could, but it
1184 // would be a giant change to clang.)
1185 if (isa<CXXDestructorDecl>(New))
1186 return false;
1187
Artem Belevich94a55e82015-09-22 17:22:59 +00001188 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1189 OldTarget = IdentifyCUDATarget(Old);
Artem Belevich13e9b4d2016-12-07 19:27:16 +00001190 if (NewTarget == CFT_InvalidTarget)
Artem Belevich94a55e82015-09-22 17:22:59 +00001191 return false;
1192
1193 assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target.");
1194
Justin Lebar53b000af2016-10-03 16:48:27 +00001195 // Allow overloading of functions with same signature and different CUDA
1196 // target attributes.
Artem Belevich94a55e82015-09-22 17:22:59 +00001197 return NewTarget != OldTarget;
1198 }
1199
John McCall1f82f242009-11-18 22:49:29 +00001200 // The signatures match; this is not an overload.
1201 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001202}
1203
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001204/// Checks availability of the function depending on the current
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00001205/// function context. Inside an unavailable function, unavailability is ignored.
1206///
1207/// \returns true if \arg FD is unavailable and current context is inside
1208/// an available function, false otherwise.
1209bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
Duncan P. N. Exon Smith85363922016-03-08 10:28:52 +00001210 if (!FD->isUnavailable())
1211 return false;
1212
1213 // Walk up the context of the caller.
1214 Decl *C = cast<Decl>(CurContext);
1215 do {
1216 if (C->isUnavailable())
1217 return false;
1218 } while ((C = cast_or_null<Decl>(C->getDeclContext())));
1219 return true;
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00001220}
1221
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001222/// Tries a user-defined conversion from From to ToType.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001223///
1224/// Produces an implicit conversion sequence for when a standard conversion
1225/// is not an option. See TryImplicitConversion for more information.
1226static ImplicitConversionSequence
1227TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1228 bool SuppressUserConversions,
1229 bool AllowExplicit,
1230 bool InOverloadResolution,
1231 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001232 bool AllowObjCWritebackConversion,
1233 bool AllowObjCConversionOnExplicit) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001234 ImplicitConversionSequence ICS;
1235
1236 if (SuppressUserConversions) {
1237 // We're not in the case above, so there is no conversion that
1238 // we can perform.
1239 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1240 return ICS;
1241 }
1242
1243 // Attempt user-defined conversion.
Richard Smith100b24a2014-04-17 01:52:14 +00001244 OverloadCandidateSet Conversions(From->getExprLoc(),
1245 OverloadCandidateSet::CSK_Normal);
Richard Smith48372b62015-01-27 03:30:40 +00001246 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1247 Conversions, AllowExplicit,
1248 AllowObjCConversionOnExplicit)) {
1249 case OR_Success:
1250 case OR_Deleted:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001251 ICS.setUserDefined();
1252 // C++ [over.ics.user]p4:
1253 // A conversion of an expression of class type to the same class
1254 // type is given Exact Match rank, and a conversion of an
1255 // expression of class type to a base class of that type is
1256 // given Conversion rank, in spite of the fact that a copy
1257 // constructor (i.e., a user-defined conversion function) is
1258 // called for those cases.
1259 if (CXXConstructorDecl *Constructor
1260 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1261 QualType FromCanon
1262 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1263 QualType ToCanon
1264 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1265 if (Constructor->isCopyConstructor() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00001266 (FromCanon == ToCanon ||
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001267 S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001268 // Turn this into a "standard" conversion sequence, so that it
1269 // gets ranked with standard conversion sequences.
Richard Smithc2bebe92016-05-11 20:37:46 +00001270 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001271 ICS.setStandard();
1272 ICS.Standard.setAsIdentityConversion();
1273 ICS.Standard.setFromType(From->getType());
1274 ICS.Standard.setAllToTypes(ToType);
1275 ICS.Standard.CopyConstructor = Constructor;
Richard Smithc2bebe92016-05-11 20:37:46 +00001276 ICS.Standard.FoundCopyConstructor = Found;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001277 if (ToCanon != FromCanon)
1278 ICS.Standard.Second = ICK_Derived_To_Base;
1279 }
1280 }
Richard Smith48372b62015-01-27 03:30:40 +00001281 break;
1282
1283 case OR_Ambiguous:
Richard Smith1bbaba82015-01-27 23:23:39 +00001284 ICS.setAmbiguous();
1285 ICS.Ambiguous.setFromType(From->getType());
1286 ICS.Ambiguous.setToType(ToType);
1287 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1288 Cand != Conversions.end(); ++Cand)
1289 if (Cand->Viable)
Richard Smithc2bebe92016-05-11 20:37:46 +00001290 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
Richard Smith1bbaba82015-01-27 23:23:39 +00001291 break;
Richard Smith48372b62015-01-27 03:30:40 +00001292
1293 // Fall through.
1294 case OR_No_Viable_Function:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001295 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Richard Smith48372b62015-01-27 03:30:40 +00001296 break;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001297 }
1298
1299 return ICS;
1300}
1301
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001302/// TryImplicitConversion - Attempt to perform an implicit conversion
1303/// from the given expression (Expr) to the given type (ToType). This
1304/// function returns an implicit conversion sequence that can be used
1305/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001306///
1307/// void f(float f);
1308/// void g(int i) { f(i); }
1309///
1310/// this routine would produce an implicit conversion sequence to
1311/// describe the initialization of f from i, which will be a standard
1312/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1313/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1314//
1315/// Note that this routine only determines how the conversion can be
1316/// performed; it does not actually perform the conversion. As such,
1317/// it will not produce any diagnostics if no conversion is available,
1318/// but will instead return an implicit conversion sequence of kind
1319/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +00001320///
1321/// If @p SuppressUserConversions, then user-defined conversions are
1322/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +00001323/// If @p AllowExplicit, then explicit user-defined conversions are
1324/// permitted.
John McCall31168b02011-06-15 23:02:42 +00001325///
1326/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1327/// writeback conversion, which allows __autoreleasing id* parameters to
1328/// be initialized with __strong id* or __weak id* arguments.
John McCall5c32be02010-08-24 20:38:10 +00001329static ImplicitConversionSequence
1330TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1331 bool SuppressUserConversions,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001332 bool AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001333 bool InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001334 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001335 bool AllowObjCWritebackConversion,
1336 bool AllowObjCConversionOnExplicit) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001337 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +00001338 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001339 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall0d1da222010-01-12 00:44:57 +00001340 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +00001341 return ICS;
1342 }
1343
David Blaikiebbafb8a2012-03-11 07:00:24 +00001344 if (!S.getLangOpts().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +00001345 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +00001346 return ICS;
1347 }
1348
Douglas Gregor836a7e82010-08-11 02:15:33 +00001349 // C++ [over.ics.user]p4:
1350 // A conversion of an expression of class type to the same class
1351 // type is given Exact Match rank, and a conversion of an
1352 // expression of class type to a base class of that type is
1353 // given Conversion rank, in spite of the fact that a copy/move
1354 // constructor (i.e., a user-defined conversion function) is
1355 // called for those cases.
1356 QualType FromType = From->getType();
1357 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00001358 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001359 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001360 ICS.setStandard();
1361 ICS.Standard.setAsIdentityConversion();
1362 ICS.Standard.setFromType(FromType);
1363 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001364
Douglas Gregor5ab11652010-04-17 22:01:05 +00001365 // We don't actually check at this point whether there is a valid
1366 // copy/move constructor, since overloading just assumes that it
1367 // exists. When we actually perform initialization, we'll find the
1368 // appropriate constructor to copy the returned object, if needed.
Craig Topperc3ec1492014-05-26 06:22:03 +00001369 ICS.Standard.CopyConstructor = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001370
Douglas Gregor5ab11652010-04-17 22:01:05 +00001371 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +00001372 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +00001373 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001374
Douglas Gregor836a7e82010-08-11 02:15:33 +00001375 return ICS;
1376 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001377
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001378 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1379 AllowExplicit, InOverloadResolution, CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001380 AllowObjCWritebackConversion,
1381 AllowObjCConversionOnExplicit);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001382}
1383
John McCall31168b02011-06-15 23:02:42 +00001384ImplicitConversionSequence
1385Sema::TryImplicitConversion(Expr *From, QualType ToType,
1386 bool SuppressUserConversions,
1387 bool AllowExplicit,
1388 bool InOverloadResolution,
1389 bool CStyle,
1390 bool AllowObjCWritebackConversion) {
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00001391 return ::TryImplicitConversion(*this, From, ToType,
Richard Smith17c00b42014-11-12 01:24:00 +00001392 SuppressUserConversions, AllowExplicit,
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00001393 InOverloadResolution, CStyle,
Richard Smith17c00b42014-11-12 01:24:00 +00001394 AllowObjCWritebackConversion,
1395 /*AllowObjCConversionOnExplicit=*/false);
John McCall5c32be02010-08-24 20:38:10 +00001396}
1397
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001398/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley01296292011-04-08 18:41:53 +00001399/// expression From to the type ToType. Returns the
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001400/// converted expression. Flavor is the kind of conversion we're
1401/// performing, used in the error message. If @p AllowExplicit,
1402/// explicit user-defined conversions are permitted.
John Wiegley01296292011-04-08 18:41:53 +00001403ExprResult
1404Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redlcc152642011-10-16 18:19:06 +00001405 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001406 ImplicitConversionSequence ICS;
Sebastian Redlcc152642011-10-16 18:19:06 +00001407 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001408}
1409
John Wiegley01296292011-04-08 18:41:53 +00001410ExprResult
1411Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001412 AssignmentAction Action, bool AllowExplicit,
Sebastian Redlcc152642011-10-16 18:19:06 +00001413 ImplicitConversionSequence& ICS) {
John McCall526ab472011-10-25 17:37:35 +00001414 if (checkPlaceholderForOverload(*this, From))
1415 return ExprError();
1416
John McCall31168b02011-06-15 23:02:42 +00001417 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1418 bool AllowObjCWritebackConversion
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00001419 = getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001420 (Action == AA_Passing || Action == AA_Sending);
Fariborz Jahanian381edf52013-12-16 22:54:37 +00001421 if (getLangOpts().ObjC1)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001422 CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1423 From->getType(), From);
Richard Smith17c00b42014-11-12 01:24:00 +00001424 ICS = ::TryImplicitConversion(*this, From, ToType,
1425 /*SuppressUserConversions=*/false,
1426 AllowExplicit,
1427 /*InOverloadResolution=*/false,
1428 /*CStyle=*/false,
1429 AllowObjCWritebackConversion,
1430 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001431 return PerformImplicitConversion(From, ToType, ICS, Action);
1432}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001433
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001434/// Determine whether the conversion from FromType to ToType is a valid
Richard Smith3c4f8d22016-10-16 17:54:23 +00001435/// conversion that strips "noexcept" or "noreturn" off the nested function
1436/// type.
1437bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
Chandler Carruth53e61b02011-06-18 01:19:03 +00001438 QualType &ResultTy) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001439 if (Context.hasSameUnqualifiedType(FromType, ToType))
1440 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001441
John McCall991eb4b2010-12-21 00:44:39 +00001442 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
Richard Smith3c4f8d22016-10-16 17:54:23 +00001443 // or F(t noexcept) -> F(t)
John McCall991eb4b2010-12-21 00:44:39 +00001444 // where F adds one of the following at most once:
1445 // - a pointer
1446 // - a member pointer
1447 // - a block pointer
Richard Smitheb7ef2e2016-10-20 21:53:09 +00001448 // Changes here need matching changes in FindCompositePointerType.
John McCall991eb4b2010-12-21 00:44:39 +00001449 CanQualType CanTo = Context.getCanonicalType(ToType);
1450 CanQualType CanFrom = Context.getCanonicalType(FromType);
1451 Type::TypeClass TyClass = CanTo->getTypeClass();
1452 if (TyClass != CanFrom->getTypeClass()) return false;
1453 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1454 if (TyClass == Type::Pointer) {
1455 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1456 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1457 } else if (TyClass == Type::BlockPointer) {
1458 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1459 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1460 } else if (TyClass == Type::MemberPointer) {
Richard Smitheb7ef2e2016-10-20 21:53:09 +00001461 auto ToMPT = CanTo.getAs<MemberPointerType>();
1462 auto FromMPT = CanFrom.getAs<MemberPointerType>();
1463 // A function pointer conversion cannot change the class of the function.
1464 if (ToMPT->getClass() != FromMPT->getClass())
1465 return false;
1466 CanTo = ToMPT->getPointeeType();
1467 CanFrom = FromMPT->getPointeeType();
John McCall991eb4b2010-12-21 00:44:39 +00001468 } else {
1469 return false;
1470 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001471
John McCall991eb4b2010-12-21 00:44:39 +00001472 TyClass = CanTo->getTypeClass();
1473 if (TyClass != CanFrom->getTypeClass()) return false;
1474 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1475 return false;
1476 }
1477
Richard Smith3c4f8d22016-10-16 17:54:23 +00001478 const auto *FromFn = cast<FunctionType>(CanFrom);
1479 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
John McCall991eb4b2010-12-21 00:44:39 +00001480
Richard Smith6f427402016-10-20 00:01:36 +00001481 const auto *ToFn = cast<FunctionType>(CanTo);
Richard Smith3c4f8d22016-10-16 17:54:23 +00001482 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1483
1484 bool Changed = false;
1485
1486 // Drop 'noreturn' if not present in target type.
1487 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1488 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1489 Changed = true;
1490 }
1491
1492 // Drop 'noexcept' if not present in target type.
1493 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
Richard Smith6f427402016-10-20 00:01:36 +00001494 const auto *ToFPT = cast<FunctionProtoType>(ToFn);
Richard Smitheaf11ad2018-05-03 03:58:32 +00001495 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
Richard Smith3c4f8d22016-10-16 17:54:23 +00001496 FromFn = cast<FunctionType>(
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00001497 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1498 EST_None)
Richard Smith3c4f8d22016-10-16 17:54:23 +00001499 .getTypePtr());
1500 Changed = true;
1501 }
Artem Belevich55ebd6c2018-04-03 18:29:31 +00001502
Akira Hatanaka98a49332017-09-22 00:41:05 +00001503 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1504 // only if the ExtParameterInfo lists of the two function prototypes can be
1505 // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1506 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
1507 bool CanUseToFPT, CanUseFromFPT;
1508 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1509 CanUseFromFPT, NewParamInfos) &&
1510 CanUseToFPT && !CanUseFromFPT) {
1511 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1512 ExtInfo.ExtParameterInfos =
1513 NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1514 QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1515 FromFPT->getParamTypes(), ExtInfo);
1516 FromFn = QT->getAs<FunctionType>();
1517 Changed = true;
1518 }
Richard Smith3c4f8d22016-10-16 17:54:23 +00001519 }
1520
1521 if (!Changed)
1522 return false;
1523
John McCall991eb4b2010-12-21 00:44:39 +00001524 assert(QualType(FromFn, 0).isCanonical());
1525 if (QualType(FromFn, 0) != CanTo) return false;
1526
1527 ResultTy = ToType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001528 return true;
1529}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001530
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001531/// Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor46188682010-05-18 22:42:18 +00001532/// vector conversion.
1533///
1534/// \param ICK Will be set to the vector conversion kind, if this is a vector
1535/// conversion.
John McCall9b595db2014-02-04 23:58:19 +00001536static bool IsVectorConversion(Sema &S, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001537 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregor46188682010-05-18 22:42:18 +00001538 // We need at least one of these types to be a vector type to have a vector
1539 // conversion.
1540 if (!ToType->isVectorType() && !FromType->isVectorType())
1541 return false;
1542
1543 // Identical types require no conversions.
John McCall9b595db2014-02-04 23:58:19 +00001544 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor46188682010-05-18 22:42:18 +00001545 return false;
1546
1547 // There are no conversions between extended vector types, only identity.
1548 if (ToType->isExtVectorType()) {
1549 // There are no conversions between extended vector types other than the
1550 // identity conversion.
1551 if (FromType->isExtVectorType())
1552 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001553
Douglas Gregor46188682010-05-18 22:42:18 +00001554 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +00001555 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +00001556 ICK = ICK_Vector_Splat;
1557 return true;
1558 }
1559 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001560
1561 // We can perform the conversion between vector types in the following cases:
1562 // 1)vector types are equivalent AltiVec and GCC vector types
1563 // 2)lax vector conversions are permitted and the vector types are of the
1564 // same size
1565 if (ToType->isVectorType() && FromType->isVectorType()) {
John McCall9b595db2014-02-04 23:58:19 +00001566 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1567 S.isLaxVectorConversion(FromType, ToType)) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001568 ICK = ICK_Vector_Conversion;
1569 return true;
1570 }
Douglas Gregor46188682010-05-18 22:42:18 +00001571 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001572
Douglas Gregor46188682010-05-18 22:42:18 +00001573 return false;
1574}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001575
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001576static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1577 bool InOverloadResolution,
1578 StandardConversionSequence &SCS,
1579 bool CStyle);
George Burgess IV45461812015-10-11 20:13:20 +00001580
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001581/// IsStandardConversion - Determines whether there is a standard
1582/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1583/// expression From to the type ToType. Standard conversion sequences
1584/// only consider non-class types; for conversions that involve class
1585/// types, use TryImplicitConversion. If a conversion exists, SCS will
1586/// contain the standard conversion sequence required to perform this
1587/// conversion and this routine will return true. Otherwise, this
1588/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +00001589static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1590 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +00001591 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +00001592 bool CStyle,
1593 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001594 QualType FromType = From->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001595
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001596 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +00001597 SCS.setAsIdentityConversion();
Douglas Gregor47d3f272008-12-19 17:40:08 +00001598 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +00001599 SCS.setFromType(FromType);
Craig Topperc3ec1492014-05-26 06:22:03 +00001600 SCS.CopyConstructor = nullptr;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001601
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001602 // There are no standard conversions for class types in C++, so
George Burgess IV45461812015-10-11 20:13:20 +00001603 // abort early. When overloading in C, however, we do permit them.
1604 if (S.getLangOpts().CPlusPlus &&
1605 (FromType->isRecordType() || ToType->isRecordType()))
1606 return false;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001607
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001608 // The first conversion can be an lvalue-to-rvalue conversion,
1609 // array-to-pointer conversion, or function-to-pointer conversion
1610 // (C++ 4p1).
1611
John McCall5c32be02010-08-24 20:38:10 +00001612 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001613 DeclAccessPair AccessPair;
1614 if (FunctionDecl *Fn
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001615 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall5c32be02010-08-24 20:38:10 +00001616 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001617 // We were able to resolve the address of the overloaded function,
1618 // so we can convert to the type of that function.
1619 FromType = Fn->getType();
Ehsan Akhgaric3ad3ba2014-07-22 20:20:14 +00001620 SCS.setFromType(FromType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00001621
1622 // we can sometimes resolve &foo<int> regardless of ToType, so check
1623 // if the type matches (identity) or we are converting to bool
1624 if (!S.Context.hasSameUnqualifiedType(
1625 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1626 QualType resultTy;
1627 // if the function type matches except for [[noreturn]], it's ok
Richard Smith3c4f8d22016-10-16 17:54:23 +00001628 if (!S.IsFunctionConversion(FromType,
Douglas Gregorb491ed32011-02-19 21:32:49 +00001629 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00001630 // otherwise, only a boolean conversion is standard
1631 if (!ToType->isBooleanType())
1632 return false;
Douglas Gregor980fb162010-04-29 18:24:40 +00001633 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001634
Chandler Carruthffce2452011-03-29 08:08:18 +00001635 // Check if the "from" expression is taking the address of an overloaded
1636 // function and recompute the FromType accordingly. Take advantage of the
1637 // fact that non-static member functions *must* have such an address-of
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00001638 // expression.
Chandler Carruthffce2452011-03-29 08:08:18 +00001639 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1640 if (Method && !Method->isStatic()) {
1641 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1642 "Non-unary operator on non-static member address");
1643 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1644 == UO_AddrOf &&
1645 "Non-address-of operator on non-static member address");
1646 const Type *ClassType
1647 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1648 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruth7750f762011-03-29 18:38:10 +00001649 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1650 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1651 UO_AddrOf &&
Chandler Carruthffce2452011-03-29 08:08:18 +00001652 "Non-address-of operator for overloaded function expression");
1653 FromType = S.Context.getPointerType(FromType);
1654 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001655
Douglas Gregor980fb162010-04-29 18:24:40 +00001656 // Check that we've computed the proper type after overload resolution.
Richard Smith9095e5b2016-11-01 01:31:23 +00001657 // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't
1658 // be calling it from within an NDEBUG block.
Chandler Carruthffce2452011-03-29 08:08:18 +00001659 assert(S.Context.hasSameType(
1660 FromType,
1661 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001662 } else {
1663 return false;
1664 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001665 }
John McCall154a2fd2011-08-30 00:57:29 +00001666 // Lvalue-to-rvalue conversion (C++11 4.1):
1667 // A glvalue (3.10) of a non-function, non-array type T can
1668 // be converted to a prvalue.
1669 bool argIsLValue = From->isGLValue();
John McCall086a4642010-11-24 05:12:34 +00001670 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001671 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001672 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001673 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001674
Douglas Gregorc79862f2012-04-12 17:51:55 +00001675 // C11 6.3.2.1p2:
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00001676 // ... if the lvalue has atomic type, the value has the non-atomic version
Douglas Gregorc79862f2012-04-12 17:51:55 +00001677 // of the type of the lvalue ...
1678 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1679 FromType = Atomic->getValueType();
1680
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001681 // If T is a non-class type, the type of the rvalue is the
1682 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001683 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1684 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001685 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001686 } else if (FromType->isArrayType()) {
1687 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001688 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001689
1690 // An lvalue or rvalue of type "array of N T" or "array of unknown
1691 // bound of T" can be converted to an rvalue of type "pointer to
1692 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001693 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001694
John McCall5c32be02010-08-24 20:38:10 +00001695 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00001696 // This conversion is deprecated in C++03 (D.4)
Douglas Gregore489a7d2010-02-28 18:30:25 +00001697 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001698
1699 // For the purpose of ranking in overload resolution
1700 // (13.3.3.1.1), this conversion is considered an
1701 // array-to-pointer conversion followed by a qualification
1702 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001703 SCS.Second = ICK_Identity;
1704 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001705 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001706 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001707 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001708 }
John McCall086a4642010-11-24 05:12:34 +00001709 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001710 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001711 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001712
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001713 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1714 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1715 if (!S.checkAddressOfFunctionIsAvailable(FD))
1716 return false;
1717
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001718 // An lvalue of function type T can be converted to an rvalue of
1719 // type "pointer to T." The result is a pointer to the
1720 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001721 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001722 } else {
1723 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001724 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001725 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001726 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001727
1728 // The second conversion can be an integral promotion, floating
1729 // point promotion, integral conversion, floating point conversion,
1730 // floating-integral conversion, pointer conversion,
1731 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001732 // For overloading in C, this can also be a "compatible-type"
1733 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001734 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001735 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001736 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001737 // The unqualified versions of the types are the same: there's no
1738 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001739 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001740 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001741 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001742 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001743 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001744 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001745 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001746 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001747 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001748 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001749 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001750 SCS.Second = ICK_Complex_Promotion;
1751 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001752 } else if (ToType->isBooleanType() &&
1753 (FromType->isArithmeticType() ||
1754 FromType->isAnyPointerType() ||
1755 FromType->isBlockPointerType() ||
1756 FromType->isMemberPointerType() ||
1757 FromType->isNullPtrType())) {
1758 // Boolean conversions (C++ 4.12).
1759 SCS.Second = ICK_Boolean_Conversion;
1760 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001761 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001762 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001763 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001764 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001765 FromType = ToType.getUnqualifiedType();
Richard Smithb8a98242013-05-10 20:29:50 +00001766 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001767 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001768 SCS.Second = ICK_Complex_Conversion;
1769 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001770 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1771 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001772 // Complex-real conversions (C99 6.3.1.7)
1773 SCS.Second = ICK_Complex_Real;
1774 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001775 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001776 // FIXME: disable conversions between long double and __float128 if
1777 // their representation is different until there is back end support
1778 // We of course allow this conversion if long double is really double.
1779 if (&S.Context.getFloatTypeSemantics(FromType) !=
1780 &S.Context.getFloatTypeSemantics(ToType)) {
1781 bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1782 ToType == S.Context.LongDoubleTy) ||
1783 (FromType == S.Context.LongDoubleTy &&
1784 ToType == S.Context.Float128Ty));
1785 if (Float128AndLongDouble &&
Benjamin Kramer98057952018-01-17 22:56:57 +00001786 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1787 &llvm::APFloat::PPCDoubleDouble()))
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001788 return false;
1789 }
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001790 // Floating point conversions (C++ 4.8).
1791 SCS.Second = ICK_Floating_Conversion;
1792 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001793 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001794 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001795 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001796 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001797 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001798 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001799 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001800 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCall31168b02011-06-15 23:02:42 +00001801 SCS.Second = ICK_Block_Pointer_Conversion;
1802 } else if (AllowObjCWritebackConversion &&
1803 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1804 SCS.Second = ICK_Writeback_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001805 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1806 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001807 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001808 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001809 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregoraec25842011-04-26 23:16:46 +00001810 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001811 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall5c32be02010-08-24 20:38:10 +00001812 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001813 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001814 SCS.Second = ICK_Pointer_Member;
John McCall9b595db2014-02-04 23:58:19 +00001815 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001816 SCS.Second = SecondICK;
1817 FromType = ToType.getUnqualifiedType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001818 } else if (!S.getLangOpts().CPlusPlus &&
John McCall5c32be02010-08-24 20:38:10 +00001819 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001820 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001821 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001822 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001823 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1824 InOverloadResolution,
1825 SCS, CStyle)) {
1826 SCS.Second = ICK_TransparentUnionConversion;
1827 FromType = ToType;
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001828 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1829 CStyle)) {
1830 // tryAtomicConversion has updated the standard conversion sequence
Douglas Gregorc79862f2012-04-12 17:51:55 +00001831 // appropriately.
1832 return true;
George Burgess IV45461812015-10-11 20:13:20 +00001833 } else if (ToType->isEventT() &&
Guy Benyei259f9f42013-02-07 16:05:33 +00001834 From->isIntegerConstantExpr(S.getASTContext()) &&
George Burgess IV45461812015-10-11 20:13:20 +00001835 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
Guy Benyei259f9f42013-02-07 16:05:33 +00001836 SCS.Second = ICK_Zero_Event_Conversion;
1837 FromType = ToType;
Egor Churaev89831422016-12-23 14:55:49 +00001838 } else if (ToType->isQueueT() &&
1839 From->isIntegerConstantExpr(S.getASTContext()) &&
1840 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1841 SCS.Second = ICK_Zero_Queue_Conversion;
1842 FromType = ToType;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001843 } else {
1844 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001845 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001846 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001847 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001848
Richard Smitheb7ef2e2016-10-20 21:53:09 +00001849 // The third conversion can be a function pointer conversion or a
1850 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
John McCall31168b02011-06-15 23:02:42 +00001851 bool ObjCLifetimeConversion;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00001852 if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1853 // Function pointer conversions (removing 'noexcept') including removal of
1854 // 'noreturn' (Clang extension).
1855 SCS.Third = ICK_Function_Conversion;
1856 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1857 ObjCLifetimeConversion)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001858 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001859 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001860 FromType = ToType;
1861 } else {
1862 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001863 SCS.Third = ICK_Identity;
Richard Smith9c37e662016-10-20 17:57:33 +00001864 }
Richard Smitheb7ef2e2016-10-20 21:53:09 +00001865
1866 // C++ [over.best.ics]p6:
1867 // [...] Any difference in top-level cv-qualification is
1868 // subsumed by the initialization itself and does not constitute
1869 // a conversion. [...]
1870 QualType CanonFrom = S.Context.getCanonicalType(FromType);
1871 QualType CanonTo = S.Context.getCanonicalType(ToType);
1872 if (CanonFrom.getLocalUnqualifiedType()
1873 == CanonTo.getLocalUnqualifiedType() &&
1874 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1875 FromType = ToType;
1876 CanonFrom = CanonTo;
1877 }
1878
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001879 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001880
George Burgess IV45461812015-10-11 20:13:20 +00001881 if (CanonFrom == CanonTo)
1882 return true;
1883
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001884 // If we have not converted the argument type to the parameter type,
George Burgess IV45461812015-10-11 20:13:20 +00001885 // this is a bad conversion sequence, unless we're resolving an overload in C.
1886 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001887 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001888
George Burgess IV45461812015-10-11 20:13:20 +00001889 ExprResult ER = ExprResult{From};
George Burgess IV2099b542016-09-02 22:59:57 +00001890 Sema::AssignConvertType Conv =
1891 S.CheckSingleAssignmentConstraints(ToType, ER,
1892 /*Diagnose=*/false,
1893 /*DiagnoseCFAudited=*/false,
1894 /*ConvertRHS=*/false);
George Burgess IV6098fd12016-09-03 00:28:25 +00001895 ImplicitConversionKind SecondConv;
George Burgess IV2099b542016-09-02 22:59:57 +00001896 switch (Conv) {
1897 case Sema::Compatible:
George Burgess IV6098fd12016-09-03 00:28:25 +00001898 SecondConv = ICK_C_Only_Conversion;
George Burgess IV2099b542016-09-02 22:59:57 +00001899 break;
1900 // For our purposes, discarding qualifiers is just as bad as using an
1901 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
1902 // qualifiers, as well.
1903 case Sema::CompatiblePointerDiscardsQualifiers:
1904 case Sema::IncompatiblePointer:
1905 case Sema::IncompatiblePointerSign:
George Burgess IV6098fd12016-09-03 00:28:25 +00001906 SecondConv = ICK_Incompatible_Pointer_Conversion;
George Burgess IV2099b542016-09-02 22:59:57 +00001907 break;
1908 default:
George Burgess IV45461812015-10-11 20:13:20 +00001909 return false;
George Burgess IV2099b542016-09-02 22:59:57 +00001910 }
George Burgess IV45461812015-10-11 20:13:20 +00001911
George Burgess IV6098fd12016-09-03 00:28:25 +00001912 // First can only be an lvalue conversion, so we pretend that this was the
1913 // second conversion. First should already be valid from earlier in the
1914 // function.
1915 SCS.Second = SecondConv;
1916 SCS.setToType(1, ToType);
1917
1918 // Third is Identity, because Second should rank us worse than any other
1919 // conversion. This could also be ICK_Qualification, but it's simpler to just
1920 // lump everything in with the second conversion, and we don't gain anything
1921 // from making this ICK_Qualification.
1922 SCS.Third = ICK_Identity;
1923 SCS.setToType(2, ToType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001924 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001925}
George Burgess IV2099b542016-09-02 22:59:57 +00001926
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001927static bool
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00001928IsTransparentUnionStandardConversion(Sema &S, Expr* From,
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001929 QualType &ToType,
1930 bool InOverloadResolution,
1931 StandardConversionSequence &SCS,
1932 bool CStyle) {
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00001933
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001934 const RecordType *UT = ToType->getAsUnionType();
1935 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1936 return false;
1937 // The field to initialize within the transparent union.
1938 RecordDecl *UD = UT->getDecl();
1939 // It's compatible if the expression matches any of the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001940 for (const auto *it : UD->fields()) {
John McCall31168b02011-06-15 23:02:42 +00001941 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1942 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001943 ToType = it->getType();
1944 return true;
1945 }
1946 }
1947 return false;
1948}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001949
1950/// IsIntegralPromotion - Determines whether the conversion from the
1951/// expression From (whose potentially-adjusted type is FromType) to
1952/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1953/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001954bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001955 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001956 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001957 if (!To) {
1958 return false;
1959 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001960
1961 // An rvalue of type char, signed char, unsigned char, short int, or
1962 // unsigned short int can be converted to an rvalue of type int if
1963 // int can represent all the values of the source type; otherwise,
1964 // the source rvalue can be converted to an rvalue of type unsigned
1965 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001966 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1967 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001968 if (// We can promote any signed, promotable integer type to an int
1969 (FromType->isSignedIntegerType() ||
1970 // We can promote any unsigned integer type whose size is
1971 // less than int to an int.
Benjamin Kramer5ff67472016-04-11 08:26:13 +00001972 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001973 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001974 }
1975
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001976 return To->getKind() == BuiltinType::UInt;
1977 }
1978
Richard Smithb9c5a602012-09-13 21:18:54 +00001979 // C++11 [conv.prom]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001980 // A prvalue of an unscoped enumeration type whose underlying type is not
1981 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1982 // following types that can represent all the values of the enumeration
1983 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1984 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001985 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001986 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001987 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001988 // with lowest integer conversion rank (4.13) greater than the rank of long
1989 // long in which all the values of the enumeration can be represented. If
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001990 // there are two such extended types, the signed one is chosen.
Richard Smithb9c5a602012-09-13 21:18:54 +00001991 // C++11 [conv.prom]p4:
1992 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1993 // can be converted to a prvalue of its underlying type. Moreover, if
1994 // integral promotion can be applied to its underlying type, a prvalue of an
1995 // unscoped enumeration type whose underlying type is fixed can also be
1996 // converted to a prvalue of the promoted underlying type.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001997 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1998 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1999 // provided for a scoped enumeration.
2000 if (FromEnumType->getDecl()->isScoped())
2001 return false;
2002
Richard Smithb9c5a602012-09-13 21:18:54 +00002003 // We can perform an integral promotion to the underlying type of the enum,
Richard Smithac8c1752015-03-28 00:31:40 +00002004 // even if that's not the promoted type. Note that the check for promoting
2005 // the underlying type is based on the type alone, and does not consider
2006 // the bitfield-ness of the actual source expression.
Richard Smithb9c5a602012-09-13 21:18:54 +00002007 if (FromEnumType->getDecl()->isFixed()) {
2008 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2009 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
Richard Smithac8c1752015-03-28 00:31:40 +00002010 IsIntegralPromotion(nullptr, Underlying, ToType);
Richard Smithb9c5a602012-09-13 21:18:54 +00002011 }
2012
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00002013 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002014 if (ToType->isIntegerType() &&
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002015 isCompleteType(From->getBeginLoc(), FromType))
Richard Smith88f4bba2015-03-26 00:16:07 +00002016 return Context.hasSameUnqualifiedType(
2017 ToType, FromEnumType->getDecl()->getPromotionType());
Richard Smithaadb2542018-06-28 21:17:55 +00002018
2019 // C++ [conv.prom]p5:
2020 // If the bit-field has an enumerated type, it is treated as any other
2021 // value of that type for promotion purposes.
2022 //
2023 // ... so do not fall through into the bit-field checks below in C++.
2024 if (getLangOpts().CPlusPlus)
2025 return false;
Douglas Gregor0bf31402010-10-08 23:50:27 +00002026 }
John McCall56774992009-12-09 09:09:27 +00002027
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00002028 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002029 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2030 // to an rvalue a prvalue of the first of the following types that can
2031 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00002032 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002033 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00002034 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002035 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00002036 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002037 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00002038 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002039 // Determine whether the type we're converting from is signed or
2040 // unsigned.
David Majnemerfa01a582011-07-22 21:09:04 +00002041 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002042 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002043
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002044 // The types we'll try to promote to, in the appropriate
2045 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00002046 QualType PromoteTypes[6] = {
2047 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00002048 Context.LongTy, Context.UnsignedLongTy ,
2049 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002050 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00002051 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002052 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2053 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00002054 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002055 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2056 // We found the type that we can promote to. If this is the
2057 // type we wanted, we have a promotion. Otherwise, no
2058 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002059 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002060 }
2061 }
2062 }
2063
2064 // An rvalue for an integral bit-field (9.6) can be converted to an
2065 // rvalue of type int if int can represent all the values of the
2066 // bit-field; otherwise, it can be converted to unsigned int if
2067 // unsigned int can represent all the values of the bit-field. If
2068 // the bit-field is larger yet, no integral promotion applies to
2069 // it. If the bit-field has an enumerated type, it is treated as any
2070 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00002071 // FIXME: We should delay checking of bit-fields until we actually perform the
2072 // conversion.
Richard Smithaadb2542018-06-28 21:17:55 +00002073 //
2074 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2075 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2076 // bit-fields and those whose underlying type is larger than int) for GCC
2077 // compatibility.
Richard Smith88f4bba2015-03-26 00:16:07 +00002078 if (From) {
John McCalld25db7e2013-05-06 21:39:12 +00002079 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
Richard Smith88f4bba2015-03-26 00:16:07 +00002080 llvm::APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00002081 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00002082 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
Richard Smith88f4bba2015-03-26 00:16:07 +00002083 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
Douglas Gregor71235ec2009-05-02 02:18:30 +00002084 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00002085
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00002086 // Are we promoting to an int from a bitfield that fits in an int?
2087 if (BitWidth < ToSize ||
2088 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
2089 return To->getKind() == BuiltinType::Int;
2090 }
Mike Stump11289f42009-09-09 15:08:12 +00002091
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00002092 // Are we promoting to an unsigned int from an unsigned bitfield
2093 // that fits into an unsigned int?
2094 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
2095 return To->getKind() == BuiltinType::UInt;
2096 }
Mike Stump11289f42009-09-09 15:08:12 +00002097
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00002098 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002099 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002100 }
Richard Smith88f4bba2015-03-26 00:16:07 +00002101 }
Mike Stump11289f42009-09-09 15:08:12 +00002102
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002103 // An rvalue of type bool can be converted to an rvalue of type int,
2104 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002105 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002106 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002107 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002108
2109 return false;
2110}
2111
2112/// IsFloatingPointPromotion - Determines whether the conversion from
2113/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2114/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00002115bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00002116 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2117 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002118 /// An rvalue of type float can be converted to an rvalue of type
2119 /// double. (C++ 4.6p1).
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002120 if (FromBuiltin->getKind() == BuiltinType::Float &&
2121 ToBuiltin->getKind() == BuiltinType::Double)
2122 return true;
2123
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002124 // C99 6.3.1.5p1:
2125 // When a float is promoted to double or long double, or a
2126 // double is promoted to long double [...].
David Blaikiebbafb8a2012-03-11 07:00:24 +00002127 if (!getLangOpts().CPlusPlus &&
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002128 (FromBuiltin->getKind() == BuiltinType::Float ||
2129 FromBuiltin->getKind() == BuiltinType::Double) &&
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002130 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2131 ToBuiltin->getKind() == BuiltinType::Float128))
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002132 return true;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002133
2134 // Half can be promoted to float.
Joey Goulydd7f4562013-01-23 11:56:20 +00002135 if (!getLangOpts().NativeHalfType &&
2136 FromBuiltin->getKind() == BuiltinType::Half &&
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002137 ToBuiltin->getKind() == BuiltinType::Float)
2138 return true;
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002139 }
2140
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002141 return false;
2142}
2143
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002144/// Determine if a conversion is a complex promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002145///
2146/// A complex promotion is defined as a complex -> complex conversion
2147/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00002148/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002149bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00002150 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002151 if (!FromComplex)
2152 return false;
2153
John McCall9dd450b2009-09-21 23:43:11 +00002154 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002155 if (!ToComplex)
2156 return false;
2157
2158 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00002159 ToComplex->getElementType()) ||
Craig Topperc3ec1492014-05-26 06:22:03 +00002160 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00002161 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002162}
2163
Douglas Gregor237f96c2008-11-26 23:31:11 +00002164/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2165/// the pointer type FromPtr to a pointer to type ToPointee, with the
2166/// same type qualifiers as FromPtr has on its pointee type. ToType,
2167/// if non-empty, will be a pointer to ToType that may or may not have
2168/// the right set of qualifiers on its pointee.
John McCall31168b02011-06-15 23:02:42 +00002169///
Mike Stump11289f42009-09-09 15:08:12 +00002170static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002171BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002172 QualType ToPointee, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002173 ASTContext &Context,
2174 bool StripObjCLifetime = false) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002175 assert((FromPtr->getTypeClass() == Type::Pointer ||
2176 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2177 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002178
John McCall31168b02011-06-15 23:02:42 +00002179 /// Conversions to 'id' subsume cv-qualifier conversions.
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002180 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00002181 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002182
2183 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002184 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00002185 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00002186 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00002187
John McCall31168b02011-06-15 23:02:42 +00002188 if (StripObjCLifetime)
2189 Quals.removeObjCLifetime();
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002190
Mike Stump11289f42009-09-09 15:08:12 +00002191 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002192 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00002193 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00002194 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00002195 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002196
2197 // Build a pointer to ToPointee. It has the right qualifiers
2198 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002199 if (isa<ObjCObjectPointerType>(ToType))
2200 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00002201 return Context.getPointerType(ToPointee);
2202 }
2203
2204 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002205 QualType QualifiedCanonToPointee
2206 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002207
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002208 if (isa<ObjCObjectPointerType>(ToType))
2209 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2210 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002211}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002212
Mike Stump11289f42009-09-09 15:08:12 +00002213static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00002214 bool InOverloadResolution,
2215 ASTContext &Context) {
2216 // Handle value-dependent integral null pointer constants correctly.
2217 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2218 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00002219 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00002220 return !InOverloadResolution;
2221
Douglas Gregor56751b52009-09-25 04:25:58 +00002222 return Expr->isNullPointerConstant(Context,
2223 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2224 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00002225}
Mike Stump11289f42009-09-09 15:08:12 +00002226
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002227/// IsPointerConversion - Determines whether the conversion of the
2228/// expression From, which has the (possibly adjusted) type FromType,
2229/// can be converted to the type ToType via a pointer conversion (C++
2230/// 4.10). If so, returns true and places the converted type (that
2231/// might differ from ToType in its cv-qualifiers at some level) into
2232/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00002233///
Douglas Gregora29dc052008-11-27 01:19:21 +00002234/// This routine also supports conversions to and from block pointers
2235/// and conversions with Objective-C's 'id', 'id<protocols...>', and
2236/// pointers to interfaces. FIXME: Once we've determined the
2237/// appropriate overloading rules for Objective-C, we may want to
2238/// split the Objective-C checks into a different routine; however,
2239/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00002240/// conversions, so for now they live here. IncompatibleObjC will be
2241/// set if the conversion is an allowed Objective-C conversion that
2242/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002243bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00002244 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00002245 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00002246 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00002247 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00002248 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2249 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00002250 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00002251
Mike Stump11289f42009-09-09 15:08:12 +00002252 // Conversion from a null pointer constant to any Objective-C pointer type.
2253 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002254 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00002255 ConvertedType = ToType;
2256 return true;
2257 }
2258
Douglas Gregor231d1c62008-11-27 00:15:41 +00002259 // Blocks: Block pointers can be converted to void*.
2260 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002261 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00002262 ConvertedType = ToType;
2263 return true;
2264 }
2265 // Blocks: A null pointer constant can be converted to a block
2266 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00002267 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002268 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00002269 ConvertedType = ToType;
2270 return true;
2271 }
2272
Sebastian Redl576fd422009-05-10 18:38:11 +00002273 // If the left-hand-side is nullptr_t, the right side can be a null
2274 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00002275 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002276 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00002277 ConvertedType = ToType;
2278 return true;
2279 }
2280
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002281 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002282 if (!ToTypePtr)
2283 return false;
2284
2285 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00002286 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002287 ConvertedType = ToType;
2288 return true;
2289 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002290
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002291 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002292 // , including objective-c pointers.
2293 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00002294 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002295 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002296 ConvertedType = BuildSimilarlyQualifiedPointerType(
2297 FromType->getAs<ObjCObjectPointerType>(),
2298 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002299 ToType, Context);
2300 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002301 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002302 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002303 if (!FromTypePtr)
2304 return false;
2305
2306 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002307
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002308 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-08-18 21:25:30 +00002309 // pointer conversion, so don't do all of the work below.
2310 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2311 return false;
2312
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002313 // An rvalue of type "pointer to cv T," where T is an object type,
2314 // can be converted to an rvalue of type "pointer to cv void" (C++
2315 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00002316 if (FromPointeeType->isIncompleteOrObjectType() &&
2317 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002318 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002319 ToPointeeType,
John McCall31168b02011-06-15 23:02:42 +00002320 ToType, Context,
2321 /*StripObjCLifetime=*/true);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002322 return true;
2323 }
2324
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002325 // MSVC allows implicit function to void* type conversion.
David Majnemer6bf02822015-10-31 08:42:14 +00002326 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002327 ToPointeeType->isVoidType()) {
2328 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2329 ToPointeeType,
2330 ToType, Context);
2331 return true;
2332 }
2333
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002334 // When we're overloading in C, we allow a special kind of pointer
2335 // conversion for compatible-but-not-identical pointee types.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002336 if (!getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002337 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002338 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002339 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00002340 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002341 return true;
2342 }
2343
Douglas Gregor5c407d92008-10-23 00:40:37 +00002344 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002345 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00002346 // An rvalue of type "pointer to cv D," where D is a class type,
2347 // can be converted to an rvalue of type "pointer to cv B," where
2348 // B is a base class (clause 10) of D. If B is an inaccessible
2349 // (clause 11) or ambiguous (10.2) base class of D, a program that
2350 // necessitates this conversion is ill-formed. The result of the
2351 // conversion is a pointer to the base class sub-object of the
2352 // derived class object. The null pointer value is converted to
2353 // the null pointer value of the destination type.
2354 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00002355 // Note that we do not check for ambiguity or inaccessibility
2356 // here. That is handled by CheckPointerConversion.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002357 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
2358 ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00002359 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002360 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002361 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002362 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002363 ToType, Context);
2364 return true;
2365 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002366
Fariborz Jahanianbc2ee932011-04-14 20:33:36 +00002367 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2368 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2369 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2370 ToPointeeType,
2371 ToType, Context);
2372 return true;
2373 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002374
Douglas Gregora119f102008-12-19 19:13:09 +00002375 return false;
2376}
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002377
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002378/// Adopt the given qualifiers for the given type.
Douglas Gregoraec25842011-04-26 23:16:46 +00002379static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2380 Qualifiers TQs = T.getQualifiers();
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002381
Douglas Gregoraec25842011-04-26 23:16:46 +00002382 // Check whether qualifiers already match.
2383 if (TQs == Qs)
2384 return T;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002385
Douglas Gregoraec25842011-04-26 23:16:46 +00002386 if (Qs.compatiblyIncludes(TQs))
2387 return Context.getQualifiedType(T, Qs);
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002388
Douglas Gregoraec25842011-04-26 23:16:46 +00002389 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2390}
Douglas Gregora119f102008-12-19 19:13:09 +00002391
2392/// isObjCPointerConversion - Determines whether this is an
2393/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2394/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00002395bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00002396 QualType& ConvertedType,
2397 bool &IncompatibleObjC) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002398 if (!getLangOpts().ObjC1)
Douglas Gregora119f102008-12-19 19:13:09 +00002399 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002400
Douglas Gregoraec25842011-04-26 23:16:46 +00002401 // The set of qualifiers on the type we're converting from.
2402 Qualifiers FromQualifiers = FromType.getQualifiers();
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002403
Steve Naroff7cae42b2009-07-10 23:34:53 +00002404 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00002405 const ObjCObjectPointerType* ToObjCPtr =
2406 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00002407 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00002408 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002409
Steve Naroff7cae42b2009-07-10 23:34:53 +00002410 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002411 // If the pointee types are the same (ignoring qualifications),
2412 // then this is not a pointer conversion.
2413 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2414 FromObjCPtr->getPointeeType()))
2415 return false;
2416
Douglas Gregorab209d82015-07-07 03:58:42 +00002417 // Conversion between Objective-C pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00002418 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002419 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2420 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002421 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002422 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2423 FromObjCPtr->getPointeeType()))
2424 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002425 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002426 ToObjCPtr->getPointeeType(),
2427 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002428 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002429 return true;
2430 }
2431
2432 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2433 // Okay: this is some kind of implicit downcast of Objective-C
2434 // interfaces, which is permitted. However, we're going to
2435 // complain about it.
2436 IncompatibleObjC = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002437 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002438 ToObjCPtr->getPointeeType(),
2439 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002440 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002441 return true;
2442 }
Mike Stump11289f42009-09-09 15:08:12 +00002443 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00002444 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00002445 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002446 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002447 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002448 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002449 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002450 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002451 // to a block pointer type.
2452 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002453 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002454 return true;
2455 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002456 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002457 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002458 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002459 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002460 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002461 // pointer to any object.
Douglas Gregoraec25842011-04-26 23:16:46 +00002462 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002463 return true;
2464 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002465 else
Douglas Gregora119f102008-12-19 19:13:09 +00002466 return false;
2467
Douglas Gregor033f56d2008-12-23 00:53:59 +00002468 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002469 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002470 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00002471 else if (const BlockPointerType *FromBlockPtr =
2472 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00002473 FromPointeeType = FromBlockPtr->getPointeeType();
2474 else
Douglas Gregora119f102008-12-19 19:13:09 +00002475 return false;
2476
Douglas Gregora119f102008-12-19 19:13:09 +00002477 // If we have pointers to pointers, recursively check whether this
2478 // is an Objective-C conversion.
2479 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2480 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2481 IncompatibleObjC)) {
2482 // We always complain about this conversion.
2483 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002484 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002485 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002486 return true;
2487 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002488 // Allow conversion of pointee being objective-c pointer to another one;
2489 // as in I* to id.
2490 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2491 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2492 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2493 IncompatibleObjC)) {
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002494
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002495 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002496 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002497 return true;
2498 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002499
Douglas Gregor033f56d2008-12-23 00:53:59 +00002500 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00002501 // differences in the argument and result types are in Objective-C
2502 // pointer conversions. If so, we permit the conversion (but
2503 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00002504 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002505 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002506 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002507 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002508 if (FromFunctionType && ToFunctionType) {
2509 // If the function types are exactly the same, this isn't an
2510 // Objective-C pointer conversion.
2511 if (Context.getCanonicalType(FromPointeeType)
2512 == Context.getCanonicalType(ToPointeeType))
2513 return false;
2514
2515 // Perform the quick checks that will tell us whether these
2516 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002517 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Douglas Gregora119f102008-12-19 19:13:09 +00002518 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2519 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2520 return false;
2521
2522 bool HasObjCConversion = false;
Alp Toker314cc812014-01-25 16:55:45 +00002523 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2524 Context.getCanonicalType(ToFunctionType->getReturnType())) {
Douglas Gregora119f102008-12-19 19:13:09 +00002525 // Okay, the types match exactly. Nothing to do.
Alp Toker314cc812014-01-25 16:55:45 +00002526 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2527 ToFunctionType->getReturnType(),
Douglas Gregora119f102008-12-19 19:13:09 +00002528 ConvertedType, IncompatibleObjC)) {
2529 // Okay, we have an Objective-C pointer conversion.
2530 HasObjCConversion = true;
2531 } else {
2532 // Function types are too different. Abort.
2533 return false;
2534 }
Mike Stump11289f42009-09-09 15:08:12 +00002535
Douglas Gregora119f102008-12-19 19:13:09 +00002536 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002537 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Douglas Gregora119f102008-12-19 19:13:09 +00002538 ArgIdx != NumArgs; ++ArgIdx) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002539 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2540 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Douglas Gregora119f102008-12-19 19:13:09 +00002541 if (Context.getCanonicalType(FromArgType)
2542 == Context.getCanonicalType(ToArgType)) {
2543 // Okay, the types match exactly. Nothing to do.
2544 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2545 ConvertedType, IncompatibleObjC)) {
2546 // Okay, we have an Objective-C pointer conversion.
2547 HasObjCConversion = true;
2548 } else {
2549 // Argument types are too different. Abort.
2550 return false;
2551 }
2552 }
2553
2554 if (HasObjCConversion) {
2555 // We had an Objective-C conversion. Allow this pointer
2556 // conversion, but complain about it.
Douglas Gregoraec25842011-04-26 23:16:46 +00002557 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002558 IncompatibleObjC = true;
2559 return true;
2560 }
2561 }
2562
Sebastian Redl72b597d2009-01-25 19:43:20 +00002563 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002564}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002565
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002566/// Determine whether this is an Objective-C writeback conversion,
John McCall31168b02011-06-15 23:02:42 +00002567/// used for parameter passing when performing automatic reference counting.
2568///
2569/// \param FromType The type we're converting form.
2570///
2571/// \param ToType The type we're converting to.
2572///
2573/// \param ConvertedType The type that will be produced after applying
2574/// this conversion.
2575bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2576 QualType &ConvertedType) {
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002577 if (!getLangOpts().ObjCAutoRefCount ||
John McCall31168b02011-06-15 23:02:42 +00002578 Context.hasSameUnqualifiedType(FromType, ToType))
2579 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002580
John McCall31168b02011-06-15 23:02:42 +00002581 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2582 QualType ToPointee;
2583 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2584 ToPointee = ToPointer->getPointeeType();
2585 else
2586 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002587
John McCall31168b02011-06-15 23:02:42 +00002588 Qualifiers ToQuals = ToPointee.getQualifiers();
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002589 if (!ToPointee->isObjCLifetimeType() ||
John McCall31168b02011-06-15 23:02:42 +00002590 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall18ce25e2012-02-08 00:46:36 +00002591 !ToQuals.withoutObjCLifetime().empty())
John McCall31168b02011-06-15 23:02:42 +00002592 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002593
John McCall31168b02011-06-15 23:02:42 +00002594 // Argument must be a pointer to __strong to __weak.
2595 QualType FromPointee;
2596 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2597 FromPointee = FromPointer->getPointeeType();
2598 else
2599 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002600
John McCall31168b02011-06-15 23:02:42 +00002601 Qualifiers FromQuals = FromPointee.getQualifiers();
2602 if (!FromPointee->isObjCLifetimeType() ||
2603 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2604 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2605 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002606
John McCall31168b02011-06-15 23:02:42 +00002607 // Make sure that we have compatible qualifiers.
2608 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2609 if (!ToQuals.compatiblyIncludes(FromQuals))
2610 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002611
John McCall31168b02011-06-15 23:02:42 +00002612 // Remove qualifiers from the pointee type we're converting from; they
2613 // aren't used in the compatibility check belong, and we'll be adding back
2614 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2615 FromPointee = FromPointee.getUnqualifiedType();
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002616
John McCall31168b02011-06-15 23:02:42 +00002617 // The unqualified form of the pointee types must be compatible.
2618 ToPointee = ToPointee.getUnqualifiedType();
2619 bool IncompatibleObjC;
2620 if (Context.typesAreCompatible(FromPointee, ToPointee))
2621 FromPointee = ToPointee;
2622 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2623 IncompatibleObjC))
2624 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002625
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002626 /// Construct the type we're converting to, which is a pointer to
John McCall31168b02011-06-15 23:02:42 +00002627 /// __autoreleasing pointee.
2628 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2629 ConvertedType = Context.getPointerType(FromPointee);
2630 return true;
2631}
2632
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002633bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2634 QualType& ConvertedType) {
2635 QualType ToPointeeType;
2636 if (const BlockPointerType *ToBlockPtr =
2637 ToType->getAs<BlockPointerType>())
2638 ToPointeeType = ToBlockPtr->getPointeeType();
2639 else
2640 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002641
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002642 QualType FromPointeeType;
2643 if (const BlockPointerType *FromBlockPtr =
2644 FromType->getAs<BlockPointerType>())
2645 FromPointeeType = FromBlockPtr->getPointeeType();
2646 else
2647 return false;
2648 // We have pointer to blocks, check whether the only
2649 // differences in the argument and result types are in Objective-C
2650 // pointer conversions. If so, we permit the conversion.
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002651
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002652 const FunctionProtoType *FromFunctionType
2653 = FromPointeeType->getAs<FunctionProtoType>();
2654 const FunctionProtoType *ToFunctionType
2655 = ToPointeeType->getAs<FunctionProtoType>();
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002656
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002657 if (!FromFunctionType || !ToFunctionType)
2658 return false;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002659
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002660 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002661 return true;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002662
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002663 // Perform the quick checks that will tell us whether these
2664 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002665 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002666 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2667 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002668
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002669 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2670 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2671 if (FromEInfo != ToEInfo)
2672 return false;
2673
2674 bool IncompatibleObjC = false;
Alp Toker314cc812014-01-25 16:55:45 +00002675 if (Context.hasSameType(FromFunctionType->getReturnType(),
2676 ToFunctionType->getReturnType())) {
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002677 // Okay, the types match exactly. Nothing to do.
2678 } else {
Alp Toker314cc812014-01-25 16:55:45 +00002679 QualType RHS = FromFunctionType->getReturnType();
2680 QualType LHS = ToFunctionType->getReturnType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002681 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002682 !RHS.hasQualifiers() && LHS.hasQualifiers())
2683 LHS = LHS.getUnqualifiedType();
2684
2685 if (Context.hasSameType(RHS,LHS)) {
2686 // OK exact match.
2687 } else if (isObjCPointerConversion(RHS, LHS,
2688 ConvertedType, IncompatibleObjC)) {
2689 if (IncompatibleObjC)
2690 return false;
2691 // Okay, we have an Objective-C pointer conversion.
2692 }
2693 else
2694 return false;
2695 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002696
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002697 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002698 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002699 ArgIdx != NumArgs; ++ArgIdx) {
2700 IncompatibleObjC = false;
Alp Toker9cacbab2014-01-20 20:26:09 +00002701 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2702 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002703 if (Context.hasSameType(FromArgType, ToArgType)) {
2704 // Okay, the types match exactly. Nothing to do.
2705 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2706 ConvertedType, IncompatibleObjC)) {
2707 if (IncompatibleObjC)
2708 return false;
2709 // Okay, we have an Objective-C pointer conversion.
2710 } else
2711 // Argument types are too different. Abort.
2712 return false;
2713 }
Akira Hatanaka98a49332017-09-22 00:41:05 +00002714
2715 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
2716 bool CanUseToFPT, CanUseFromFPT;
2717 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
2718 CanUseToFPT, CanUseFromFPT,
2719 NewParamInfos))
Fariborz Jahanian97676972011-09-28 21:52:05 +00002720 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002721
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002722 ConvertedType = ToType;
2723 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002724}
2725
Richard Trieucaff2472011-11-23 22:32:32 +00002726enum {
2727 ft_default,
2728 ft_different_class,
2729 ft_parameter_arity,
2730 ft_parameter_mismatch,
2731 ft_return_type,
Richard Smith3c4f8d22016-10-16 17:54:23 +00002732 ft_qualifer_mismatch,
2733 ft_noexcept
Richard Trieucaff2472011-11-23 22:32:32 +00002734};
2735
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002736/// Attempts to get the FunctionProtoType from a Type. Handles
2737/// MemberFunctionPointers properly.
2738static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2739 if (auto *FPT = FromType->getAs<FunctionProtoType>())
2740 return FPT;
2741
2742 if (auto *MPT = FromType->getAs<MemberPointerType>())
2743 return MPT->getPointeeType()->getAs<FunctionProtoType>();
2744
2745 return nullptr;
2746}
2747
Richard Trieucaff2472011-11-23 22:32:32 +00002748/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2749/// function types. Catches different number of parameter, mismatch in
2750/// parameter types, and different return types.
2751void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2752 QualType FromType, QualType ToType) {
Richard Trieu96ed5b62011-12-13 23:19:45 +00002753 // If either type is not valid, include no extra info.
2754 if (FromType.isNull() || ToType.isNull()) {
2755 PDiag << ft_default;
2756 return;
2757 }
2758
Richard Trieucaff2472011-11-23 22:32:32 +00002759 // Get the function type from the pointers.
2760 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2761 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2762 *ToMember = ToType->getAs<MemberPointerType>();
Richard Trieu9098c9f2014-05-22 01:39:16 +00002763 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
Richard Trieucaff2472011-11-23 22:32:32 +00002764 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2765 << QualType(FromMember->getClass(), 0);
2766 return;
2767 }
2768 FromType = FromMember->getPointeeType();
2769 ToType = ToMember->getPointeeType();
Richard Trieucaff2472011-11-23 22:32:32 +00002770 }
2771
Richard Trieu96ed5b62011-12-13 23:19:45 +00002772 if (FromType->isPointerType())
2773 FromType = FromType->getPointeeType();
2774 if (ToType->isPointerType())
2775 ToType = ToType->getPointeeType();
2776
2777 // Remove references.
Richard Trieucaff2472011-11-23 22:32:32 +00002778 FromType = FromType.getNonReferenceType();
2779 ToType = ToType.getNonReferenceType();
2780
Richard Trieucaff2472011-11-23 22:32:32 +00002781 // Don't print extra info for non-specialized template functions.
2782 if (FromType->isInstantiationDependentType() &&
2783 !FromType->getAs<TemplateSpecializationType>()) {
2784 PDiag << ft_default;
2785 return;
2786 }
2787
Richard Trieu96ed5b62011-12-13 23:19:45 +00002788 // No extra info for same types.
2789 if (Context.hasSameType(FromType, ToType)) {
2790 PDiag << ft_default;
2791 return;
2792 }
2793
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002794 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2795 *ToFunction = tryGetFunctionProtoType(ToType);
Richard Trieucaff2472011-11-23 22:32:32 +00002796
2797 // Both types need to be function types.
2798 if (!FromFunction || !ToFunction) {
2799 PDiag << ft_default;
2800 return;
2801 }
2802
Alp Toker9cacbab2014-01-20 20:26:09 +00002803 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2804 PDiag << ft_parameter_arity << ToFunction->getNumParams()
2805 << FromFunction->getNumParams();
Richard Trieucaff2472011-11-23 22:32:32 +00002806 return;
2807 }
2808
2809 // Handle different parameter types.
2810 unsigned ArgPos;
Alp Toker9cacbab2014-01-20 20:26:09 +00002811 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
Richard Trieucaff2472011-11-23 22:32:32 +00002812 PDiag << ft_parameter_mismatch << ArgPos + 1
Alp Toker9cacbab2014-01-20 20:26:09 +00002813 << ToFunction->getParamType(ArgPos)
2814 << FromFunction->getParamType(ArgPos);
Richard Trieucaff2472011-11-23 22:32:32 +00002815 return;
2816 }
2817
2818 // Handle different return type.
Alp Toker314cc812014-01-25 16:55:45 +00002819 if (!Context.hasSameType(FromFunction->getReturnType(),
2820 ToFunction->getReturnType())) {
2821 PDiag << ft_return_type << ToFunction->getReturnType()
2822 << FromFunction->getReturnType();
Richard Trieucaff2472011-11-23 22:32:32 +00002823 return;
2824 }
2825
2826 unsigned FromQuals = FromFunction->getTypeQuals(),
2827 ToQuals = ToFunction->getTypeQuals();
2828 if (FromQuals != ToQuals) {
2829 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2830 return;
2831 }
2832
Richard Smith3c4f8d22016-10-16 17:54:23 +00002833 // Handle exception specification differences on canonical type (in C++17
2834 // onwards).
2835 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
Richard Smitheaf11ad2018-05-03 03:58:32 +00002836 ->isNothrow() !=
Richard Smith3c4f8d22016-10-16 17:54:23 +00002837 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
Richard Smitheaf11ad2018-05-03 03:58:32 +00002838 ->isNothrow()) {
Richard Smith3c4f8d22016-10-16 17:54:23 +00002839 PDiag << ft_noexcept;
2840 return;
2841 }
2842
Richard Trieucaff2472011-11-23 22:32:32 +00002843 // Unable to find a difference, so add no extra info.
2844 PDiag << ft_default;
2845}
2846
Alp Toker9cacbab2014-01-20 20:26:09 +00002847/// FunctionParamTypesAreEqual - This routine checks two function proto types
Douglas Gregor2039ca02011-12-15 17:15:07 +00002848/// for equality of their argument types. Caller has already checked that
Eli Friedman5f508952013-06-18 22:41:37 +00002849/// they have same number of arguments. If the parameters are different,
2850/// ArgPos will have the parameter index of the first different parameter.
Alp Toker9cacbab2014-01-20 20:26:09 +00002851bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2852 const FunctionProtoType *NewType,
2853 unsigned *ArgPos) {
2854 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2855 N = NewType->param_type_begin(),
2856 E = OldType->param_type_end();
2857 O && (O != E); ++O, ++N) {
Richard Trieu4b03d982013-08-09 21:42:32 +00002858 if (!Context.hasSameType(O->getUnqualifiedType(),
2859 N->getUnqualifiedType())) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002860 if (ArgPos)
2861 *ArgPos = O - OldType->param_type_begin();
Larisse Voufo4154f462013-08-06 03:57:41 +00002862 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002863 }
2864 }
2865 return true;
2866}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002867
Douglas Gregor39c16d42008-10-24 04:54:22 +00002868/// CheckPointerConversion - Check the pointer conversion from the
2869/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00002870/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00002871/// conversions for which IsPointerConversion has already returned
2872/// true. It returns true and produces a diagnostic if there was an
2873/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002874bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002875 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002876 CXXCastPath& BasePath,
George Burgess IV60bc9722016-01-13 23:36:34 +00002877 bool IgnoreBaseAccess,
2878 bool Diagnose) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002879 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00002880 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002881
John McCall8cb679e2010-11-15 09:13:47 +00002882 Kind = CK_BitCast;
2883
George Burgess IV60bc9722016-01-13 23:36:34 +00002884 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
Argyrios Kyrtzidis3e3305d2014-02-02 05:26:43 +00002885 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
George Burgess IV60bc9722016-01-13 23:36:34 +00002886 Expr::NPCK_ZeroExpression) {
David Blaikie1c7c8f72012-08-08 17:33:31 +00002887 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2888 DiagRuntimeBehavior(From->getExprLoc(), From,
2889 PDiag(diag::warn_impcast_bool_to_null_pointer)
2890 << ToType << From->getSourceRange());
2891 else if (!isUnevaluatedContext())
2892 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2893 << ToType << From->getSourceRange();
2894 }
John McCall9320b872011-09-09 05:25:32 +00002895 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2896 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002897 QualType FromPointeeType = FromPtrType->getPointeeType(),
2898 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00002899
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002900 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2901 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002902 // We must have a derived-to-base conversion. Check an
2903 // ambiguous or inaccessible conversion.
George Burgess IV60bc9722016-01-13 23:36:34 +00002904 unsigned InaccessibleID = 0;
2905 unsigned AmbigiousID = 0;
2906 if (Diagnose) {
2907 InaccessibleID = diag::err_upcast_to_inaccessible_base;
2908 AmbigiousID = diag::err_ambiguous_derived_to_base_conv;
2909 }
2910 if (CheckDerivedToBaseConversion(
2911 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID,
2912 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
2913 &BasePath, IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002914 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002915
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002916 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00002917 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002918 }
David Majnemer6bf02822015-10-31 08:42:14 +00002919
George Burgess IV60bc9722016-01-13 23:36:34 +00002920 if (Diagnose && !IsCStyleOrFunctionalCast &&
2921 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
David Majnemer6bf02822015-10-31 08:42:14 +00002922 assert(getLangOpts().MSVCCompat &&
2923 "this should only be possible with MSVCCompat!");
2924 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
2925 << From->getSourceRange();
2926 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00002927 }
John McCall9320b872011-09-09 05:25:32 +00002928 } else if (const ObjCObjectPointerType *ToPtrType =
2929 ToType->getAs<ObjCObjectPointerType>()) {
2930 if (const ObjCObjectPointerType *FromPtrType =
2931 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002932 // Objective-C++ conversions are always okay.
2933 // FIXME: We should have a different class of conversions for the
2934 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00002935 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002936 return false;
John McCall9320b872011-09-09 05:25:32 +00002937 } else if (FromType->isBlockPointerType()) {
2938 Kind = CK_BlockPointerToObjCPointerCast;
2939 } else {
2940 Kind = CK_CPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00002941 }
John McCall9320b872011-09-09 05:25:32 +00002942 } else if (ToType->isBlockPointerType()) {
2943 if (!FromType->isBlockPointerType())
2944 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002945 }
John McCall8cb679e2010-11-15 09:13:47 +00002946
2947 // We shouldn't fall into this case unless it's valid for other
2948 // reasons.
2949 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2950 Kind = CK_NullToPointer;
2951
Douglas Gregor39c16d42008-10-24 04:54:22 +00002952 return false;
2953}
2954
Sebastian Redl72b597d2009-01-25 19:43:20 +00002955/// IsMemberPointerConversion - Determines whether the conversion of the
2956/// expression From, which has the (possibly adjusted) type FromType, can be
2957/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2958/// If so, returns true and places the converted type (that might differ from
2959/// ToType in its cv-qualifiers at some level) into ConvertedType.
2960bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002961 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00002962 bool InOverloadResolution,
2963 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002964 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002965 if (!ToTypePtr)
2966 return false;
2967
2968 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00002969 if (From->isNullPointerConstant(Context,
2970 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2971 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002972 ConvertedType = ToType;
2973 return true;
2974 }
2975
2976 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002977 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002978 if (!FromTypePtr)
2979 return false;
2980
2981 // A pointer to member of B can be converted to a pointer to member of D,
2982 // where D is derived from B (C++ 4.11p2).
2983 QualType FromClass(FromTypePtr->getClass(), 0);
2984 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002985
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002986 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002987 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002988 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2989 ToClass.getTypePtr());
2990 return true;
2991 }
2992
2993 return false;
2994}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002995
Sebastian Redl72b597d2009-01-25 19:43:20 +00002996/// CheckMemberPointerConversion - Check the member pointer conversion from the
2997/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002998/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002999/// for which IsMemberPointerConversion has already returned true. It returns
3000/// true and produces a diagnostic if there was an error, or returns false
3001/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00003002bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00003003 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00003004 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00003005 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00003006 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003007 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00003008 if (!FromPtrType) {
3009 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003010 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00003011 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00003012 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00003013 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00003014 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00003015 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00003016
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003017 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00003018 assert(ToPtrType && "No member pointer cast has a target type "
3019 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00003020
Sebastian Redled8f2002009-01-28 18:33:18 +00003021 QualType FromClass = QualType(FromPtrType->getClass(), 0);
3022 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00003023
Sebastian Redled8f2002009-01-28 18:33:18 +00003024 // FIXME: What about dependent types?
3025 assert(FromClass->isRecordType() && "Pointer into non-class.");
3026 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00003027
Anders Carlsson7d3360f2010-04-24 19:36:51 +00003028 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00003029 /*DetectVirtual=*/true);
Richard Smith0f59cb32015-12-18 21:45:41 +00003030 bool DerivationOkay =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003031 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths);
Sebastian Redled8f2002009-01-28 18:33:18 +00003032 assert(DerivationOkay &&
3033 "Should not have been called if derivation isn't OK.");
3034 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00003035
Sebastian Redled8f2002009-01-28 18:33:18 +00003036 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3037 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00003038 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3039 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3040 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3041 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00003042 }
Sebastian Redled8f2002009-01-28 18:33:18 +00003043
Douglas Gregor89ee6822009-02-28 01:32:25 +00003044 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00003045 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3046 << FromClass << ToClass << QualType(VBase, 0)
3047 << From->getSourceRange();
3048 return true;
3049 }
3050
John McCall5b0829a2010-02-10 09:31:12 +00003051 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00003052 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3053 Paths.front(),
3054 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00003055
Anders Carlssond7923c62009-08-22 23:33:40 +00003056 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00003057 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00003058 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00003059 return false;
3060}
3061
Douglas Gregorc9f019a2013-11-08 02:04:24 +00003062/// Determine whether the lifetime conversion between the two given
3063/// qualifiers sets is nontrivial.
3064static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3065 Qualifiers ToQuals) {
3066 // Converting anything to const __unsafe_unretained is trivial.
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003067 if (ToQuals.hasConst() &&
Douglas Gregorc9f019a2013-11-08 02:04:24 +00003068 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3069 return false;
3070
3071 return true;
3072}
3073
Douglas Gregor9a657932008-10-21 23:43:52 +00003074/// IsQualificationConversion - Determines whether the conversion from
3075/// an rvalue of type FromType to ToType is a qualification conversion
3076/// (C++ 4.4).
John McCall31168b02011-06-15 23:02:42 +00003077///
3078/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3079/// when the qualification conversion involves a change in the Objective-C
3080/// object lifetime.
Mike Stump11289f42009-09-09 15:08:12 +00003081bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003082Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00003083 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor9a657932008-10-21 23:43:52 +00003084 FromType = Context.getCanonicalType(FromType);
3085 ToType = Context.getCanonicalType(ToType);
John McCall31168b02011-06-15 23:02:42 +00003086 ObjCLifetimeConversion = false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003087
Douglas Gregor9a657932008-10-21 23:43:52 +00003088 // If FromType and ToType are the same type, this is not a
3089 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00003090 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00003091 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00003092
Douglas Gregor9a657932008-10-21 23:43:52 +00003093 // (C++ 4.4p4):
3094 // A conversion can add cv-qualifiers at levels other than the first
3095 // in multi-level pointers, subject to the following rules: [...]
3096 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00003097 bool UnwrappedAnyPointer = false;
Richard Smitha3405ff2018-07-11 00:19:19 +00003098 while (Context.UnwrapSimilarTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00003099 // Within each iteration of the loop, we check the qualifiers to
3100 // determine if this still looks like a qualification
3101 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003102 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00003103 // until there are no more pointers or pointers-to-members left to
3104 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003105 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00003106
Douglas Gregor90609aa2011-04-25 18:40:17 +00003107 Qualifiers FromQuals = FromType.getQualifiers();
3108 Qualifiers ToQuals = ToType.getQualifiers();
Andrey Bokhanko45d41322016-05-11 18:38:21 +00003109
3110 // Ignore __unaligned qualifier if this type is void.
3111 if (ToType.getUnqualifiedType()->isVoidType())
3112 FromQuals.removeUnaligned();
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003113
John McCall31168b02011-06-15 23:02:42 +00003114 // Objective-C ARC:
3115 // Check Objective-C lifetime conversions.
3116 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
3117 UnwrappedAnyPointer) {
3118 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00003119 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3120 ObjCLifetimeConversion = true;
John McCall31168b02011-06-15 23:02:42 +00003121 FromQuals.removeObjCLifetime();
3122 ToQuals.removeObjCLifetime();
3123 } else {
3124 // Qualification conversions cannot cast between different
3125 // Objective-C lifetime qualifiers.
3126 return false;
3127 }
3128 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003129
Douglas Gregorf30053d2011-05-08 06:09:53 +00003130 // Allow addition/removal of GC attributes but not changing GC attributes.
3131 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3132 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3133 FromQuals.removeObjCGCAttr();
3134 ToQuals.removeObjCGCAttr();
3135 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003136
Douglas Gregor9a657932008-10-21 23:43:52 +00003137 // -- for every j > 0, if const is in cv 1,j then const is in cv
3138 // 2,j, and similarly for volatile.
Douglas Gregor90609aa2011-04-25 18:40:17 +00003139 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor9a657932008-10-21 23:43:52 +00003140 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003141
Douglas Gregor9a657932008-10-21 23:43:52 +00003142 // -- if the cv 1,j and cv 2,j are different, then const is in
3143 // every cv for 0 < k < j.
Douglas Gregor90609aa2011-04-25 18:40:17 +00003144 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003145 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00003146 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003147
Douglas Gregor9a657932008-10-21 23:43:52 +00003148 // Keep track of whether all prior cv-qualifiers in the "to" type
3149 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00003150 PreviousToQualsIncludeConst
Douglas Gregor90609aa2011-04-25 18:40:17 +00003151 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003152 }
Douglas Gregor9a657932008-10-21 23:43:52 +00003153
Yaxun Liu99a9f752018-07-20 11:32:51 +00003154 // Allows address space promotion by language rules implemented in
3155 // Type::Qualifiers::isAddressSpaceSupersetOf.
3156 Qualifiers FromQuals = FromType.getQualifiers();
3157 Qualifiers ToQuals = ToType.getQualifiers();
3158 if (!ToQuals.isAddressSpaceSupersetOf(FromQuals) &&
3159 !FromQuals.isAddressSpaceSupersetOf(ToQuals)) {
3160 return false;
3161 }
3162
Douglas Gregor9a657932008-10-21 23:43:52 +00003163 // We are left with FromType and ToType being the pointee types
3164 // after unwrapping the original FromType and ToType the same number
3165 // of types. If we unwrapped any pointers, and if FromType and
3166 // ToType have the same unqualified type (since we checked
3167 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003168 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00003169}
3170
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003171/// - Determine whether this is a conversion from a scalar type to an
Douglas Gregorc79862f2012-04-12 17:51:55 +00003172/// atomic type.
3173///
3174/// If successful, updates \c SCS's second and third steps in the conversion
3175/// sequence to finish the conversion.
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00003176static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3177 bool InOverloadResolution,
3178 StandardConversionSequence &SCS,
3179 bool CStyle) {
Douglas Gregorc79862f2012-04-12 17:51:55 +00003180 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3181 if (!ToAtomic)
3182 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003183
Douglas Gregorc79862f2012-04-12 17:51:55 +00003184 StandardConversionSequence InnerSCS;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003185 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
Douglas Gregorc79862f2012-04-12 17:51:55 +00003186 InOverloadResolution, InnerSCS,
3187 CStyle, /*AllowObjCWritebackConversion=*/false))
3188 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003189
Douglas Gregorc79862f2012-04-12 17:51:55 +00003190 SCS.Second = InnerSCS.Second;
3191 SCS.setToType(1, InnerSCS.getToType(1));
3192 SCS.Third = InnerSCS.Third;
3193 SCS.QualificationIncludesObjCLifetime
3194 = InnerSCS.QualificationIncludesObjCLifetime;
3195 SCS.setToType(2, InnerSCS.getToType(2));
3196 return true;
3197}
3198
Sebastian Redle5417162012-03-27 18:33:03 +00003199static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3200 CXXConstructorDecl *Constructor,
3201 QualType Type) {
3202 const FunctionProtoType *CtorType =
3203 Constructor->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00003204 if (CtorType->getNumParams() > 0) {
3205 QualType FirstArg = CtorType->getParamType(0);
Sebastian Redle5417162012-03-27 18:33:03 +00003206 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3207 return true;
3208 }
3209 return false;
3210}
3211
Sebastian Redl82ace982012-02-11 23:51:08 +00003212static OverloadingResult
3213IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3214 CXXRecordDecl *To,
3215 UserDefinedConversionSequence &User,
3216 OverloadCandidateSet &CandidateSet,
3217 bool AllowExplicit) {
Richard Smith67ef14f2017-09-26 18:37:55 +00003218 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
Richard Smithc2bebe92016-05-11 20:37:46 +00003219 for (auto *D : S.LookupConstructors(To)) {
3220 auto Info = getConstructorInfo(D);
Richard Smith5179eb72016-06-28 19:03:57 +00003221 if (!Info)
Richard Smithc2bebe92016-05-11 20:37:46 +00003222 continue;
Sebastian Redl82ace982012-02-11 23:51:08 +00003223
Richard Smithc2bebe92016-05-11 20:37:46 +00003224 bool Usable = !Info.Constructor->isInvalidDecl() &&
3225 S.isInitListConstructor(Info.Constructor) &&
3226 (AllowExplicit || !Info.Constructor->isExplicit());
Sebastian Redl82ace982012-02-11 23:51:08 +00003227 if (Usable) {
Sebastian Redle5417162012-03-27 18:33:03 +00003228 // If the first argument is (a reference to) the target type,
3229 // suppress conversions.
Richard Smithc2bebe92016-05-11 20:37:46 +00003230 bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3231 S.Context, Info.Constructor, ToType);
3232 if (Info.ConstructorTmpl)
3233 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3234 /*ExplicitArgs*/ nullptr, From,
3235 CandidateSet, SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00003236 else
Richard Smithc2bebe92016-05-11 20:37:46 +00003237 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3238 CandidateSet, SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00003239 }
3240 }
3241
3242 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3243
3244 OverloadCandidateSet::iterator Best;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003245 switch (auto Result =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003246 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
Fariborz Jahaniandcf06f42015-04-14 17:21:58 +00003247 case OR_Deleted:
Sebastian Redl82ace982012-02-11 23:51:08 +00003248 case OR_Success: {
3249 // Record the standard conversion we used and the conversion function.
3250 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Sebastian Redl82ace982012-02-11 23:51:08 +00003251 QualType ThisType = Constructor->getThisType(S.Context);
3252 // Initializer lists don't have conversions as such.
3253 User.Before.setAsIdentityConversion();
3254 User.HadMultipleCandidates = HadMultipleCandidates;
3255 User.ConversionFunction = Constructor;
3256 User.FoundConversionFunction = Best->FoundDecl;
3257 User.After.setAsIdentityConversion();
3258 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3259 User.After.setAllToTypes(ToType);
Fariborz Jahaniandcf06f42015-04-14 17:21:58 +00003260 return Result;
Sebastian Redl82ace982012-02-11 23:51:08 +00003261 }
3262
3263 case OR_No_Viable_Function:
3264 return OR_No_Viable_Function;
Sebastian Redl82ace982012-02-11 23:51:08 +00003265 case OR_Ambiguous:
3266 return OR_Ambiguous;
3267 }
3268
3269 llvm_unreachable("Invalid OverloadResult!");
3270}
3271
Douglas Gregor576e98c2009-01-30 23:27:23 +00003272/// Determines whether there is a user-defined conversion sequence
3273/// (C++ [over.ics.user]) that converts expression From to the type
3274/// ToType. If such a conversion exists, User will contain the
3275/// user-defined conversion sequence that performs such a conversion
3276/// and this routine will return true. Otherwise, this routine returns
3277/// false and User is unspecified.
3278///
Douglas Gregor576e98c2009-01-30 23:27:23 +00003279/// \param AllowExplicit true if the conversion should consider C++0x
3280/// "explicit" conversion functions as well as non-explicit conversion
3281/// functions (C++0x [class.conv.fct]p2).
Douglas Gregor4b60a152013-11-07 22:34:54 +00003282///
3283/// \param AllowObjCConversionOnExplicit true if the conversion should
3284/// allow an extra Objective-C pointer conversion on uses of explicit
3285/// constructors. Requires \c AllowExplicit to also be set.
John McCall5c32be02010-08-24 20:38:10 +00003286static OverloadingResult
3287IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl82ace982012-02-11 23:51:08 +00003288 UserDefinedConversionSequence &User,
3289 OverloadCandidateSet &CandidateSet,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003290 bool AllowExplicit,
3291 bool AllowObjCConversionOnExplicit) {
Douglas Gregor2ee1d992013-11-08 01:20:25 +00003292 assert(AllowExplicit || !AllowObjCConversionOnExplicit);
Richard Smith67ef14f2017-09-26 18:37:55 +00003293 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
Douglas Gregor4b60a152013-11-07 22:34:54 +00003294
Douglas Gregor5ab11652010-04-17 22:01:05 +00003295 // Whether we will only visit constructors.
3296 bool ConstructorsOnly = false;
3297
3298 // If the type we are conversion to is a class type, enumerate its
3299 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003300 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00003301 // C++ [over.match.ctor]p1:
3302 // When objects of class type are direct-initialized (8.5), or
3303 // copy-initialized from an expression of the same or a
3304 // derived class type (8.5), overload resolution selects the
3305 // constructor. [...] For copy-initialization, the candidate
3306 // functions are all the converting constructors (12.3.1) of
3307 // that class. The argument list is the expression-list within
3308 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00003309 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00003310 (From->getType()->getAs<RecordType>() &&
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003311 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00003312 ConstructorsOnly = true;
3313
Richard Smithdb0ac552015-12-18 22:40:25 +00003314 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003315 // We're not going to find any constructors.
3316 } else if (CXXRecordDecl *ToRecordDecl
3317 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003318
3319 Expr **Args = &From;
3320 unsigned NumArgs = 1;
3321 bool ListInitializing = false;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003322 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003323 // But first, see if there is an init-list-constructor that will work.
Sebastian Redl82ace982012-02-11 23:51:08 +00003324 OverloadingResult Result = IsInitializerListConstructorConversion(
3325 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3326 if (Result != OR_No_Viable_Function)
3327 return Result;
3328 // Never mind.
Richard Smith67ef14f2017-09-26 18:37:55 +00003329 CandidateSet.clear(
3330 OverloadCandidateSet::CSK_InitByUserDefinedConversion);
Sebastian Redl82ace982012-02-11 23:51:08 +00003331
3332 // If we're list-initializing, we pass the individual elements as
3333 // arguments, not the entire list.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003334 Args = InitList->getInits();
3335 NumArgs = InitList->getNumInits();
3336 ListInitializing = true;
3337 }
3338
Richard Smithc2bebe92016-05-11 20:37:46 +00003339 for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3340 auto Info = getConstructorInfo(D);
Richard Smith5179eb72016-06-28 19:03:57 +00003341 if (!Info)
Richard Smithc2bebe92016-05-11 20:37:46 +00003342 continue;
John McCalla0296f72010-03-19 07:35:19 +00003343
Richard Smithc2bebe92016-05-11 20:37:46 +00003344 bool Usable = !Info.Constructor->isInvalidDecl();
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003345 if (ListInitializing)
Richard Smithc2bebe92016-05-11 20:37:46 +00003346 Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit());
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003347 else
Richard Smithc2bebe92016-05-11 20:37:46 +00003348 Usable = Usable &&
3349 Info.Constructor->isConvertingConstructor(AllowExplicit);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003350 if (Usable) {
Sebastian Redld9170b02012-03-20 21:24:14 +00003351 bool SuppressUserConversions = !ConstructorsOnly;
3352 if (SuppressUserConversions && ListInitializing) {
3353 SuppressUserConversions = false;
3354 if (NumArgs == 1) {
3355 // If the first argument is (a reference to) the target type,
3356 // suppress conversions.
Sebastian Redle5417162012-03-27 18:33:03 +00003357 SuppressUserConversions = isFirstArgumentCompatibleWithType(
Richard Smithc2bebe92016-05-11 20:37:46 +00003358 S.Context, Info.Constructor, ToType);
Sebastian Redld9170b02012-03-20 21:24:14 +00003359 }
3360 }
Richard Smithc2bebe92016-05-11 20:37:46 +00003361 if (Info.ConstructorTmpl)
3362 S.AddTemplateOverloadCandidate(
3363 Info.ConstructorTmpl, Info.FoundDecl,
3364 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3365 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003366 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00003367 // Allow one user-defined conversion when user specifies a
3368 // From->ToType conversion via an static cast (c-style, etc).
Richard Smithc2bebe92016-05-11 20:37:46 +00003369 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003370 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003371 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003372 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00003373 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003374 }
3375 }
3376
Douglas Gregor5ab11652010-04-17 22:01:05 +00003377 // Enumerate conversion functions, if we're allowed to.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003378 if (ConstructorsOnly || isa<InitListExpr>(From)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003379 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003380 // No conversion functions from incomplete types.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003381 } else if (const RecordType *FromRecordType =
3382 From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00003383 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003384 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3385 // Add all of the conversion functions as candidates.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00003386 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3387 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00003388 DeclAccessPair FoundDecl = I.getPair();
3389 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003390 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3391 if (isa<UsingShadowDecl>(D))
3392 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3393
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003394 CXXConversionDecl *Conv;
3395 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00003396 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3397 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003398 else
John McCallda4458e2010-03-31 01:36:47 +00003399 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003400
3401 if (AllowExplicit || !Conv->isExplicit()) {
3402 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00003403 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3404 ActingContext, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003405 CandidateSet,
3406 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003407 else
John McCall5c32be02010-08-24 20:38:10 +00003408 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003409 From, ToType, CandidateSet,
3410 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003411 }
3412 }
3413 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00003414 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003415
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003416 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3417
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003418 OverloadCandidateSet::iterator Best;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003419 switch (auto Result =
3420 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
John McCall5c32be02010-08-24 20:38:10 +00003421 case OR_Success:
Richard Smith48372b62015-01-27 03:30:40 +00003422 case OR_Deleted:
John McCall5c32be02010-08-24 20:38:10 +00003423 // Record the standard conversion we used and the conversion function.
3424 if (CXXConstructorDecl *Constructor
3425 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3426 // C++ [over.ics.user]p1:
3427 // If the user-defined conversion is specified by a
3428 // constructor (12.3.1), the initial standard conversion
3429 // sequence converts the source type to the type required by
3430 // the argument of the constructor.
3431 //
3432 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003433 if (isa<InitListExpr>(From)) {
3434 // Initializer lists don't have conversions as such.
3435 User.Before.setAsIdentityConversion();
3436 } else {
3437 if (Best->Conversions[0].isEllipsis())
3438 User.EllipsisConversion = true;
3439 else {
3440 User.Before = Best->Conversions[0].Standard;
3441 User.EllipsisConversion = false;
3442 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003443 }
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003444 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003445 User.ConversionFunction = Constructor;
John McCall30909032011-09-21 08:36:56 +00003446 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003447 User.After.setAsIdentityConversion();
3448 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3449 User.After.setAllToTypes(ToType);
Richard Smith48372b62015-01-27 03:30:40 +00003450 return Result;
David Blaikie8a40f702012-01-17 06:56:22 +00003451 }
3452 if (CXXConversionDecl *Conversion
John McCall5c32be02010-08-24 20:38:10 +00003453 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3454 // C++ [over.ics.user]p1:
3455 //
3456 // [...] If the user-defined conversion is specified by a
3457 // conversion function (12.3.2), the initial standard
3458 // conversion sequence converts the source type to the
3459 // implicit object parameter of the conversion function.
3460 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003461 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003462 User.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00003463 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003464 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00003465
John McCall5c32be02010-08-24 20:38:10 +00003466 // C++ [over.ics.user]p2:
3467 // The second standard conversion sequence converts the
3468 // result of the user-defined conversion to the target type
3469 // for the sequence. Since an implicit conversion sequence
3470 // is an initialization, the special rules for
3471 // initialization by user-defined conversion apply when
3472 // selecting the best user-defined conversion for a
3473 // user-defined conversion sequence (see 13.3.3 and
3474 // 13.3.3.1).
3475 User.After = Best->FinalConversion;
Richard Smith48372b62015-01-27 03:30:40 +00003476 return Result;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003477 }
David Blaikie8a40f702012-01-17 06:56:22 +00003478 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003479
John McCall5c32be02010-08-24 20:38:10 +00003480 case OR_No_Viable_Function:
3481 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003482
John McCall5c32be02010-08-24 20:38:10 +00003483 case OR_Ambiguous:
3484 return OR_Ambiguous;
3485 }
3486
David Blaikie8a40f702012-01-17 06:56:22 +00003487 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003488}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003489
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003490bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00003491Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003492 ImplicitConversionSequence ICS;
Richard Smith100b24a2014-04-17 01:52:14 +00003493 OverloadCandidateSet CandidateSet(From->getExprLoc(),
3494 OverloadCandidateSet::CSK_Normal);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003495 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00003496 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003497 CandidateSet, false, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00003498 if (OvResult == OR_Ambiguous)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003499 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003500 << From->getType() << ToType << From->getSourceRange();
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003501 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003502 if (!RequireCompleteType(From->getBeginLoc(), ToType,
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003503 diag::err_typecheck_nonviable_condition_incomplete,
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003504 From->getType(), From->getSourceRange()))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003505 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
Nick Lewycky08426e22015-08-25 22:18:46 +00003506 << false << From->getType() << From->getSourceRange() << ToType;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003507 } else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003508 return false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003509 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003510 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003511}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003512
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003513/// Compare the user-defined conversion functions or constructors
Douglas Gregor2837aa22012-02-22 17:32:19 +00003514/// of two user-defined conversion sequences to determine whether any ordering
3515/// is possible.
3516static ImplicitConversionSequence::CompareKind
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003517compareConversionFunctions(Sema &S, FunctionDecl *Function1,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003518 FunctionDecl *Function2) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003519 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
Douglas Gregor2837aa22012-02-22 17:32:19 +00003520 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003521
Douglas Gregor2837aa22012-02-22 17:32:19 +00003522 // Objective-C++:
3523 // If both conversion functions are implicitly-declared conversions from
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003524 // a lambda closure type to a function pointer and a block pointer,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003525 // respectively, always prefer the conversion to a function pointer,
3526 // because the function pointer is more lightweight and is more likely
3527 // to keep code working.
Ted Kremenek8d265c22014-04-01 07:23:18 +00003528 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003529 if (!Conv1)
3530 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003531
Douglas Gregor2837aa22012-02-22 17:32:19 +00003532 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3533 if (!Conv2)
3534 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003535
Douglas Gregor2837aa22012-02-22 17:32:19 +00003536 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3537 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3538 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3539 if (Block1 != Block2)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003540 return Block1 ? ImplicitConversionSequence::Worse
3541 : ImplicitConversionSequence::Better;
Douglas Gregor2837aa22012-02-22 17:32:19 +00003542 }
3543
3544 return ImplicitConversionSequence::Indistinguishable;
3545}
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003546
3547static bool hasDeprecatedStringLiteralToCharPtrConversion(
3548 const ImplicitConversionSequence &ICS) {
3549 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3550 (ICS.isUserDefined() &&
3551 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3552}
3553
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003554/// CompareImplicitConversionSequences - Compare two implicit
3555/// conversion sequences to determine whether one is better than the
3556/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00003557static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +00003558CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +00003559 const ImplicitConversionSequence& ICS1,
3560 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003561{
3562 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3563 // conversion sequences (as defined in 13.3.3.1)
3564 // -- a standard conversion sequence (13.3.3.1.1) is a better
3565 // conversion sequence than a user-defined conversion sequence or
3566 // an ellipsis conversion sequence, and
3567 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3568 // conversion sequence than an ellipsis conversion sequence
3569 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00003570 //
John McCall0d1da222010-01-12 00:44:57 +00003571 // C++0x [over.best.ics]p10:
3572 // For the purpose of ranking implicit conversion sequences as
3573 // described in 13.3.3.2, the ambiguous conversion sequence is
3574 // treated as a user-defined sequence that is indistinguishable
3575 // from any other user-defined conversion sequence.
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003576
3577 // String literal to 'char *' conversion has been deprecated in C++03. It has
3578 // been removed from C++11. We still accept this conversion, if it happens at
3579 // the best viable function. Otherwise, this conversion is considered worse
3580 // than ellipsis conversion. Consider this as an extension; this is not in the
3581 // standard. For example:
3582 //
3583 // int &f(...); // #1
3584 // void f(char*); // #2
3585 // void g() { int &r = f("foo"); }
3586 //
3587 // In C++03, we pick #2 as the best viable function.
3588 // In C++11, we pick #1 as the best viable function, because ellipsis
3589 // conversion is better than string-literal to char* conversion (since there
3590 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3591 // convert arguments, #2 would be the best viable function in C++11.
3592 // If the best viable function has this conversion, a warning will be issued
3593 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3594
3595 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3596 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3597 hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3598 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3599 ? ImplicitConversionSequence::Worse
3600 : ImplicitConversionSequence::Better;
3601
Douglas Gregor5ab11652010-04-17 22:01:05 +00003602 if (ICS1.getKindRank() < ICS2.getKindRank())
3603 return ImplicitConversionSequence::Better;
David Blaikie8a40f702012-01-17 06:56:22 +00003604 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor5ab11652010-04-17 22:01:05 +00003605 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003606
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00003607 // The following checks require both conversion sequences to be of
3608 // the same kind.
3609 if (ICS1.getKind() != ICS2.getKind())
3610 return ImplicitConversionSequence::Indistinguishable;
3611
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003612 ImplicitConversionSequence::CompareKind Result =
3613 ImplicitConversionSequence::Indistinguishable;
3614
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003615 // Two implicit conversion sequences of the same form are
3616 // indistinguishable conversion sequences unless one of the
3617 // following rules apply: (C++ 13.3.3.2p3):
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003618
Larisse Voufo19d08672015-01-27 18:47:05 +00003619 // List-initialization sequence L1 is a better conversion sequence than
3620 // list-initialization sequence L2 if:
3621 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3622 // if not that,
NAKAMURA Takumib01d86b2015-02-25 11:02:00 +00003623 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
Larisse Voufo19d08672015-01-27 18:47:05 +00003624 // and N1 is smaller than N2.,
3625 // even if one of the other rules in this paragraph would otherwise apply.
3626 if (!ICS1.isBad()) {
3627 if (ICS1.isStdInitializerListElement() &&
3628 !ICS2.isStdInitializerListElement())
3629 return ImplicitConversionSequence::Better;
3630 if (!ICS1.isStdInitializerListElement() &&
3631 ICS2.isStdInitializerListElement())
3632 return ImplicitConversionSequence::Worse;
3633 }
3634
John McCall0d1da222010-01-12 00:44:57 +00003635 if (ICS1.isStandard())
Larisse Voufo19d08672015-01-27 18:47:05 +00003636 // Standard conversion sequence S1 is a better conversion sequence than
3637 // standard conversion sequence S2 if [...]
Richard Smith0f59cb32015-12-18 21:45:41 +00003638 Result = CompareStandardConversionSequences(S, Loc,
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003639 ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00003640 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003641 // User-defined conversion sequence U1 is a better conversion
3642 // sequence than another user-defined conversion sequence U2 if
3643 // they contain the same user-defined conversion function or
3644 // constructor and if the second standard conversion sequence of
3645 // U1 is better than the second standard conversion sequence of
3646 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00003647 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003648 ICS2.UserDefined.ConversionFunction)
Richard Smith0f59cb32015-12-18 21:45:41 +00003649 Result = CompareStandardConversionSequences(S, Loc,
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003650 ICS1.UserDefined.After,
3651 ICS2.UserDefined.After);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003652 else
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003653 Result = compareConversionFunctions(S,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003654 ICS1.UserDefined.ConversionFunction,
3655 ICS2.UserDefined.ConversionFunction);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003656 }
3657
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003658 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003659}
3660
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003661// Per 13.3.3.2p3, compare the given standard conversion sequences to
3662// determine if one is a proper subset of the other.
3663static ImplicitConversionSequence::CompareKind
3664compareStandardConversionSubsets(ASTContext &Context,
3665 const StandardConversionSequence& SCS1,
3666 const StandardConversionSequence& SCS2) {
3667 ImplicitConversionSequence::CompareKind Result
3668 = ImplicitConversionSequence::Indistinguishable;
3669
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003670 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00003671 // any non-identity conversion sequence
Douglas Gregor377c1092011-06-05 06:15:20 +00003672 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3673 return ImplicitConversionSequence::Better;
3674 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3675 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003676
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003677 if (SCS1.Second != SCS2.Second) {
3678 if (SCS1.Second == ICK_Identity)
3679 Result = ImplicitConversionSequence::Better;
3680 else if (SCS2.Second == ICK_Identity)
3681 Result = ImplicitConversionSequence::Worse;
3682 else
3683 return ImplicitConversionSequence::Indistinguishable;
Richard Smitha3405ff2018-07-11 00:19:19 +00003684 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003685 return ImplicitConversionSequence::Indistinguishable;
3686
3687 if (SCS1.Third == SCS2.Third) {
3688 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3689 : ImplicitConversionSequence::Indistinguishable;
3690 }
3691
3692 if (SCS1.Third == ICK_Identity)
3693 return Result == ImplicitConversionSequence::Worse
3694 ? ImplicitConversionSequence::Indistinguishable
3695 : ImplicitConversionSequence::Better;
3696
3697 if (SCS2.Third == ICK_Identity)
3698 return Result == ImplicitConversionSequence::Better
3699 ? ImplicitConversionSequence::Indistinguishable
3700 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003701
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003702 return ImplicitConversionSequence::Indistinguishable;
3703}
3704
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003705/// Determine whether one of the given reference bindings is better
Douglas Gregore696ebb2011-01-26 14:52:12 +00003706/// than the other based on what kind of bindings they are.
Richard Smith19172c42014-07-14 02:28:44 +00003707static bool
3708isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3709 const StandardConversionSequence &SCS2) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003710 // C++0x [over.ics.rank]p3b4:
3711 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3712 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003713 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00003714 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003715 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00003716 // reference*.
3717 //
3718 // FIXME: Rvalue references. We're going rogue with the above edits,
3719 // because the semantics in the current C++0x working paper (N3225 at the
3720 // time of this writing) break the standard definition of std::forward
3721 // and std::reference_wrapper when dealing with references to functions.
3722 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00003723 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3724 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3725 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003726
Douglas Gregore696ebb2011-01-26 14:52:12 +00003727 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3728 SCS2.IsLvalueReference) ||
3729 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
Richard Smith19172c42014-07-14 02:28:44 +00003730 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
Douglas Gregore696ebb2011-01-26 14:52:12 +00003731}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003732
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003733/// CompareStandardConversionSequences - Compare two standard
3734/// conversion sequences to determine whether one is better than the
3735/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00003736static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +00003737CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +00003738 const StandardConversionSequence& SCS1,
3739 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003740{
3741 // Standard conversion sequence S1 is a better conversion sequence
3742 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3743
3744 // -- S1 is a proper subsequence of S2 (comparing the conversion
3745 // sequences in the canonical form defined by 13.3.3.1.1,
3746 // excluding any Lvalue Transformation; the identity conversion
3747 // sequence is considered to be a subsequence of any
3748 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003749 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00003750 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003751 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003752
3753 // -- the rank of S1 is better than the rank of S2 (by the rules
3754 // defined below), or, if not that,
3755 ImplicitConversionRank Rank1 = SCS1.getRank();
3756 ImplicitConversionRank Rank2 = SCS2.getRank();
3757 if (Rank1 < Rank2)
3758 return ImplicitConversionSequence::Better;
3759 else if (Rank2 < Rank1)
3760 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003761
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003762 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3763 // are indistinguishable unless one of the following rules
3764 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00003765
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003766 // A conversion that is not a conversion of a pointer, or
3767 // pointer to member, to bool is better than another conversion
3768 // that is such a conversion.
3769 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3770 return SCS2.isPointerConversionToBool()
3771 ? ImplicitConversionSequence::Better
3772 : ImplicitConversionSequence::Worse;
3773
Douglas Gregor5c407d92008-10-23 00:40:37 +00003774 // C++ [over.ics.rank]p4b2:
3775 //
3776 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003777 // conversion of B* to A* is better than conversion of B* to
3778 // void*, and conversion of A* to void* is better than conversion
3779 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00003780 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003781 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00003782 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003783 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003784 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3785 // Exactly one of the conversion sequences is a conversion to
3786 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003787 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3788 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003789 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3790 // Neither conversion sequence converts to a void pointer; compare
3791 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003792 if (ImplicitConversionSequence::CompareKind DerivedCK
Richard Smith0f59cb32015-12-18 21:45:41 +00003793 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003794 return DerivedCK;
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003795 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3796 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003797 // Both conversion sequences are conversions to void
3798 // pointers. Compare the source types to determine if there's an
3799 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00003800 QualType FromType1 = SCS1.getFromType();
3801 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003802
3803 // Adjust the types we're converting from via the array-to-pointer
3804 // conversion, if we need to.
3805 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003806 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003807 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003808 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003809
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003810 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3811 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003812
Richard Smith0f59cb32015-12-18 21:45:41 +00003813 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003814 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00003815 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003816 return ImplicitConversionSequence::Worse;
3817
3818 // Objective-C++: If one interface is more specific than the
3819 // other, it is the better one.
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003820 const ObjCObjectPointerType* FromObjCPtr1
3821 = FromType1->getAs<ObjCObjectPointerType>();
3822 const ObjCObjectPointerType* FromObjCPtr2
3823 = FromType2->getAs<ObjCObjectPointerType>();
3824 if (FromObjCPtr1 && FromObjCPtr2) {
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003825 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003826 FromObjCPtr2);
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003827 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003828 FromObjCPtr1);
3829 if (AssignLeft != AssignRight) {
3830 return AssignLeft? ImplicitConversionSequence::Better
3831 : ImplicitConversionSequence::Worse;
3832 }
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003833 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003834 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003835
3836 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3837 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00003838 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00003839 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003840 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003841
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003842 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003843 // Check for a better reference binding based on the kind of bindings.
3844 if (isBetterReferenceBindingKind(SCS1, SCS2))
3845 return ImplicitConversionSequence::Better;
3846 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3847 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003848
Sebastian Redlb28b4072009-03-22 23:49:27 +00003849 // C++ [over.ics.rank]p3b4:
3850 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3851 // which the references refer are the same type except for
3852 // top-level cv-qualifiers, and the type to which the reference
3853 // initialized by S2 refers is more cv-qualified than the type
3854 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003855 QualType T1 = SCS1.getToType(2);
3856 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003857 T1 = S.Context.getCanonicalType(T1);
3858 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003859 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003860 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3861 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003862 if (UnqualT1 == UnqualT2) {
John McCall31168b02011-06-15 23:02:42 +00003863 // Objective-C++ ARC: If the references refer to objects with different
3864 // lifetimes, prefer bindings that don't change lifetime.
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003865 if (SCS1.ObjCLifetimeConversionBinding !=
John McCall31168b02011-06-15 23:02:42 +00003866 SCS2.ObjCLifetimeConversionBinding) {
3867 return SCS1.ObjCLifetimeConversionBinding
3868 ? ImplicitConversionSequence::Worse
3869 : ImplicitConversionSequence::Better;
3870 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003871
Chandler Carruth8e543b32010-12-12 08:17:55 +00003872 // If the type is an array type, promote the element qualifiers to the
3873 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003874 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003875 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003876 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003877 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003878 if (T2.isMoreQualifiedThan(T1))
3879 return ImplicitConversionSequence::Better;
3880 else if (T1.isMoreQualifiedThan(T2))
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003881 return ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003882 }
3883 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003884
Francois Pichet08d2fa02011-09-18 21:37:37 +00003885 // In Microsoft mode, prefer an integral conversion to a
3886 // floating-to-integral conversion if the integral conversion
3887 // is between types of the same size.
3888 // For example:
3889 // void f(float);
3890 // void f(int);
3891 // int main {
3892 // long a;
3893 // f(a);
3894 // }
3895 // Here, MSVC will call f(int) instead of generating a compile error
3896 // as clang will do in standard mode.
Alp Tokerbfa39342014-01-14 12:51:41 +00003897 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3898 SCS2.Second == ICK_Floating_Integral &&
Francois Pichet08d2fa02011-09-18 21:37:37 +00003899 S.Context.getTypeSize(SCS1.getFromType()) ==
Alp Tokerbfa39342014-01-14 12:51:41 +00003900 S.Context.getTypeSize(SCS1.getToType(2)))
Francois Pichet08d2fa02011-09-18 21:37:37 +00003901 return ImplicitConversionSequence::Better;
3902
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003903 return ImplicitConversionSequence::Indistinguishable;
3904}
3905
3906/// CompareQualificationConversions - Compares two standard conversion
3907/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00003908/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
Richard Smith17c00b42014-11-12 01:24:00 +00003909static ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003910CompareQualificationConversions(Sema &S,
3911 const StandardConversionSequence& SCS1,
3912 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00003913 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003914 // -- S1 and S2 differ only in their qualification conversion and
3915 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3916 // cv-qualification signature of type T1 is a proper subset of
3917 // the cv-qualification signature of type T2, and S1 is not the
3918 // deprecated string literal array-to-pointer conversion (4.2).
3919 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3920 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3921 return ImplicitConversionSequence::Indistinguishable;
3922
3923 // FIXME: the example in the standard doesn't use a qualification
3924 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003925 QualType T1 = SCS1.getToType(2);
3926 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003927 T1 = S.Context.getCanonicalType(T1);
3928 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003929 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003930 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3931 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003932
3933 // If the types are the same, we won't learn anything by unwrapped
3934 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003935 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003936 return ImplicitConversionSequence::Indistinguishable;
3937
Chandler Carruth607f38e2009-12-29 07:16:59 +00003938 // If the type is an array type, promote the element qualifiers to the type
3939 // for comparison.
3940 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003941 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003942 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003943 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003944
Mike Stump11289f42009-09-09 15:08:12 +00003945 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003946 = ImplicitConversionSequence::Indistinguishable;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003947
John McCall31168b02011-06-15 23:02:42 +00003948 // Objective-C++ ARC:
3949 // Prefer qualification conversions not involving a change in lifetime
3950 // to qualification conversions that do not change lifetime.
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003951 if (SCS1.QualificationIncludesObjCLifetime !=
John McCall31168b02011-06-15 23:02:42 +00003952 SCS2.QualificationIncludesObjCLifetime) {
3953 Result = SCS1.QualificationIncludesObjCLifetime
3954 ? ImplicitConversionSequence::Worse
3955 : ImplicitConversionSequence::Better;
3956 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003957
Richard Smitha3405ff2018-07-11 00:19:19 +00003958 while (S.Context.UnwrapSimilarTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003959 // Within each iteration of the loop, we check the qualifiers to
3960 // determine if this still looks like a qualification
3961 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003962 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003963 // until there are no more pointers or pointers-to-members left
3964 // to unwrap. This essentially mimics what
3965 // IsQualificationConversion does, but here we're checking for a
3966 // strict subset of qualifiers.
3967 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3968 // The qualifiers are the same, so this doesn't tell us anything
3969 // about how the sequences rank.
3970 ;
3971 else if (T2.isMoreQualifiedThan(T1)) {
3972 // T1 has fewer qualifiers, so it could be the better sequence.
3973 if (Result == ImplicitConversionSequence::Worse)
3974 // Neither has qualifiers that are a subset of the other's
3975 // qualifiers.
3976 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003977
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003978 Result = ImplicitConversionSequence::Better;
3979 } else if (T1.isMoreQualifiedThan(T2)) {
3980 // T2 has fewer qualifiers, so it could be the better sequence.
3981 if (Result == ImplicitConversionSequence::Better)
3982 // Neither has qualifiers that are a subset of the other's
3983 // qualifiers.
3984 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003985
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003986 Result = ImplicitConversionSequence::Worse;
3987 } else {
3988 // Qualifiers are disjoint.
3989 return ImplicitConversionSequence::Indistinguishable;
3990 }
3991
3992 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00003993 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003994 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003995 }
3996
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003997 // Check that the winning standard conversion sequence isn't using
3998 // the deprecated string literal array to pointer conversion.
3999 switch (Result) {
4000 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00004001 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00004002 Result = ImplicitConversionSequence::Indistinguishable;
4003 break;
4004
4005 case ImplicitConversionSequence::Indistinguishable:
4006 break;
4007
4008 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00004009 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00004010 Result = ImplicitConversionSequence::Indistinguishable;
4011 break;
4012 }
4013
4014 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004015}
4016
Douglas Gregor5c407d92008-10-23 00:40:37 +00004017/// CompareDerivedToBaseConversions - Compares two standard conversion
4018/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00004019/// various kinds of derived-to-base conversions (C++
4020/// [over.ics.rank]p4b3). As part of these checks, we also look at
4021/// conversions between Objective-C interface types.
Richard Smith17c00b42014-11-12 01:24:00 +00004022static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +00004023CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +00004024 const StandardConversionSequence& SCS1,
4025 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00004026 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004027 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00004028 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004029 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00004030
4031 // Adjust the types we're converting from via the array-to-pointer
4032 // conversion, if we need to.
4033 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00004034 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00004035 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00004036 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00004037
4038 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00004039 FromType1 = S.Context.getCanonicalType(FromType1);
4040 ToType1 = S.Context.getCanonicalType(ToType1);
4041 FromType2 = S.Context.getCanonicalType(FromType2);
4042 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00004043
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004044 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00004045 //
4046 // If class B is derived directly or indirectly from class A and
4047 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00004048 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004049 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00004050 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00004051 SCS2.Second == ICK_Pointer_Conversion &&
4052 /*FIXME: Remove if Objective-C id conversions get their own rank*/
4053 FromType1->isPointerType() && FromType2->isPointerType() &&
4054 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00004055 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004056 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00004057 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004058 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00004059 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004060 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00004061 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004062 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00004063
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004064 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00004065 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004066 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00004067 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004068 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00004069 return ImplicitConversionSequence::Worse;
4070 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004071
4072 // -- conversion of B* to A* is better than conversion of C* to A*,
4073 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004074 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004075 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004076 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004077 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00004078 }
4079 } else if (SCS1.Second == ICK_Pointer_Conversion &&
4080 SCS2.Second == ICK_Pointer_Conversion) {
4081 const ObjCObjectPointerType *FromPtr1
4082 = FromType1->getAs<ObjCObjectPointerType>();
4083 const ObjCObjectPointerType *FromPtr2
4084 = FromType2->getAs<ObjCObjectPointerType>();
4085 const ObjCObjectPointerType *ToPtr1
4086 = ToType1->getAs<ObjCObjectPointerType>();
4087 const ObjCObjectPointerType *ToPtr2
4088 = ToType2->getAs<ObjCObjectPointerType>();
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00004089
Douglas Gregor058d3de2011-01-31 18:51:41 +00004090 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4091 // Apply the same conversion ranking rules for Objective-C pointer types
4092 // that we do for C++ pointers to class types. However, we employ the
4093 // Objective-C pseudo-subtyping relationship used for assignment of
4094 // Objective-C pointer types.
4095 bool FromAssignLeft
4096 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4097 bool FromAssignRight
4098 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4099 bool ToAssignLeft
4100 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4101 bool ToAssignRight
4102 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
Alex Lorenza9832132017-04-06 13:06:34 +00004103
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00004104 // A conversion to an a non-id object pointer type or qualified 'id'
Douglas Gregor058d3de2011-01-31 18:51:41 +00004105 // type is better than a conversion to 'id'.
4106 if (ToPtr1->isObjCIdType() &&
4107 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4108 return ImplicitConversionSequence::Worse;
4109 if (ToPtr2->isObjCIdType() &&
4110 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4111 return ImplicitConversionSequence::Better;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00004112
4113 // A conversion to a non-id object pointer type is better than a
4114 // conversion to a qualified 'id' type
Douglas Gregor058d3de2011-01-31 18:51:41 +00004115 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4116 return ImplicitConversionSequence::Worse;
4117 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4118 return ImplicitConversionSequence::Better;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00004119
4120 // A conversion to an a non-Class object pointer type or qualified 'Class'
Douglas Gregor058d3de2011-01-31 18:51:41 +00004121 // type is better than a conversion to 'Class'.
4122 if (ToPtr1->isObjCClassType() &&
4123 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4124 return ImplicitConversionSequence::Worse;
4125 if (ToPtr2->isObjCClassType() &&
4126 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4127 return ImplicitConversionSequence::Better;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00004128
4129 // A conversion to a non-Class object pointer type is better than a
Douglas Gregor058d3de2011-01-31 18:51:41 +00004130 // conversion to a qualified 'Class' type.
4131 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4132 return ImplicitConversionSequence::Worse;
4133 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4134 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00004135
Douglas Gregor058d3de2011-01-31 18:51:41 +00004136 // -- "conversion of C* to B* is better than conversion of C* to A*,"
Alex Lorenza9832132017-04-06 13:06:34 +00004137 if (S.Context.hasSameType(FromType1, FromType2) &&
Douglas Gregor058d3de2011-01-31 18:51:41 +00004138 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
Alex Lorenza9832132017-04-06 13:06:34 +00004139 (ToAssignLeft != ToAssignRight)) {
4140 if (FromPtr1->isSpecialized()) {
4141 // "conversion of B<A> * to B * is better than conversion of B * to
4142 // C *.
4143 bool IsFirstSame =
4144 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4145 bool IsSecondSame =
4146 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4147 if (IsFirstSame) {
4148 if (!IsSecondSame)
4149 return ImplicitConversionSequence::Better;
4150 } else if (IsSecondSame)
4151 return ImplicitConversionSequence::Worse;
4152 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00004153 return ToAssignLeft? ImplicitConversionSequence::Worse
4154 : ImplicitConversionSequence::Better;
Alex Lorenza9832132017-04-06 13:06:34 +00004155 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00004156
4157 // -- "conversion of B* to A* is better than conversion of C* to A*,"
4158 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4159 (FromAssignLeft != FromAssignRight))
4160 return FromAssignLeft? ImplicitConversionSequence::Better
4161 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004162 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00004163 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00004164
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00004165 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004166 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4167 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4168 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004169 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004170 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004171 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004172 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004173 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004174 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004175 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004176 ToType2->getAs<MemberPointerType>();
4177 const Type *FromPointeeType1 = FromMemPointer1->getClass();
4178 const Type *ToPointeeType1 = ToMemPointer1->getClass();
4179 const Type *FromPointeeType2 = FromMemPointer2->getClass();
4180 const Type *ToPointeeType2 = ToMemPointer2->getClass();
4181 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4182 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4183 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4184 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00004185 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004186 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004187 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004188 return ImplicitConversionSequence::Worse;
Richard Smith0f59cb32015-12-18 21:45:41 +00004189 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004190 return ImplicitConversionSequence::Better;
4191 }
4192 // conversion of B::* to C::* is better than conversion of A::* to C::*
4193 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004194 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004195 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004196 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004197 return ImplicitConversionSequence::Worse;
4198 }
4199 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004200
Douglas Gregor5ab11652010-04-17 22:01:05 +00004201 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00004202 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00004203 // -- binding of an expression of type C to a reference of type
4204 // B& is better than binding an expression of type C to a
4205 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00004206 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4207 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004208 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004209 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004210 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004211 return ImplicitConversionSequence::Worse;
4212 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004213
Douglas Gregor2fe98832008-11-03 19:09:14 +00004214 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00004215 // -- binding of an expression of type B to a reference of type
4216 // A& is better than binding an expression of type C to a
4217 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00004218 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4219 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004220 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004221 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004222 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004223 return ImplicitConversionSequence::Worse;
4224 }
4225 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004226
Douglas Gregor5c407d92008-10-23 00:40:37 +00004227 return ImplicitConversionSequence::Indistinguishable;
4228}
4229
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004230/// Determine whether the given type is valid, e.g., it is not an invalid
Douglas Gregor45bb4832013-03-26 23:36:30 +00004231/// C++ class.
4232static bool isTypeValid(QualType T) {
4233 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4234 return !Record->isInvalidDecl();
4235
4236 return true;
4237}
4238
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004239/// CompareReferenceRelationship - Compare the two types T1 and T2 to
4240/// determine whether they are reference-related,
4241/// reference-compatible, reference-compatible with added
4242/// qualification, or incompatible, for use in C++ initialization by
4243/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4244/// type, and the first type (T1) is the pointee type of the reference
4245/// type being initialized.
4246Sema::ReferenceCompareResult
4247Sema::CompareReferenceRelationship(SourceLocation Loc,
4248 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004249 bool &DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004250 bool &ObjCConversion,
4251 bool &ObjCLifetimeConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004252 assert(!OrigT1->isReferenceType() &&
4253 "T1 must be the pointee type of the reference type");
4254 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4255
4256 QualType T1 = Context.getCanonicalType(OrigT1);
4257 QualType T2 = Context.getCanonicalType(OrigT2);
4258 Qualifiers T1Quals, T2Quals;
4259 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4260 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4261
4262 // C++ [dcl.init.ref]p4:
4263 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4264 // reference-related to "cv2 T2" if T1 is the same type as T2, or
4265 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004266 DerivedToBase = false;
4267 ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004268 ObjCLifetimeConversion = false;
Richard Smith1be59c52016-10-22 01:32:19 +00004269 QualType ConvertedT2;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004270 if (UnqualT1 == UnqualT2) {
4271 // Nothing to do.
Richard Smithdb0ac552015-12-18 22:40:25 +00004272 } else if (isCompleteType(Loc, OrigT2) &&
Douglas Gregor45bb4832013-03-26 23:36:30 +00004273 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00004274 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004275 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004276 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4277 UnqualT2->isObjCObjectOrInterfaceType() &&
4278 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4279 ObjCConversion = true;
Richard Smith1be59c52016-10-22 01:32:19 +00004280 else if (UnqualT2->isFunctionType() &&
4281 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2))
4282 // C++1z [dcl.init.ref]p4:
4283 // cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept
4284 // function" and T1 is "function"
4285 //
4286 // We extend this to also apply to 'noreturn', so allow any function
4287 // conversion between function types.
4288 return Ref_Compatible;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004289 else
4290 return Ref_Incompatible;
4291
4292 // At this point, we know that T1 and T2 are reference-related (at
4293 // least).
4294
4295 // If the type is an array type, promote the element qualifiers to the type
4296 // for comparison.
4297 if (isa<ArrayType>(T1) && T1Quals)
4298 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4299 if (isa<ArrayType>(T2) && T2Quals)
4300 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4301
4302 // C++ [dcl.init.ref]p4:
4303 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4304 // reference-related to T2 and cv1 is the same cv-qualification
4305 // as, or greater cv-qualification than, cv2. For purposes of
4306 // overload resolution, cases for which cv1 is greater
4307 // cv-qualification than cv2 are identified as
4308 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregord517d552011-04-28 17:56:11 +00004309 //
4310 // Note that we also require equivalence of Objective-C GC and address-space
4311 // qualifiers when performing these computations, so that e.g., an int in
4312 // address space 1 is not reference-compatible with an int in address
4313 // space 2.
John McCall31168b02011-06-15 23:02:42 +00004314 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4315 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00004316 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4317 ObjCLifetimeConversion = true;
4318
John McCall31168b02011-06-15 23:02:42 +00004319 T1Quals.removeObjCLifetime();
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00004320 T2Quals.removeObjCLifetime();
John McCall31168b02011-06-15 23:02:42 +00004321 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00004322
Andrey Bokhanko45d41322016-05-11 18:38:21 +00004323 // MS compiler ignores __unaligned qualifier for references; do the same.
4324 T1Quals.removeUnaligned();
4325 T2Quals.removeUnaligned();
4326
Richard Smithce766292016-10-21 23:01:55 +00004327 if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004328 return Ref_Compatible;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004329 else
4330 return Ref_Related;
4331}
4332
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004333/// Look for a user-defined conversion to a value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00004334/// with DeclType. Return true if something definite is found.
4335static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00004336FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4337 QualType DeclType, SourceLocation DeclLoc,
4338 Expr *Init, QualType T2, bool AllowRvalues,
4339 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004340 assert(T2->isRecordType() && "Can only find conversions of record types.");
4341 CXXRecordDecl *T2RecordDecl
4342 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4343
Richard Smith67ef14f2017-09-26 18:37:55 +00004344 OverloadCandidateSet CandidateSet(
4345 DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004346 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4347 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004348 NamedDecl *D = *I;
4349 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4350 if (isa<UsingShadowDecl>(D))
4351 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4352
4353 FunctionTemplateDecl *ConvTemplate
4354 = dyn_cast<FunctionTemplateDecl>(D);
4355 CXXConversionDecl *Conv;
4356 if (ConvTemplate)
4357 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4358 else
4359 Conv = cast<CXXConversionDecl>(D);
4360
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004361 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00004362 // explicit conversions, skip it.
4363 if (!AllowExplicit && Conv->isExplicit())
4364 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004365
Douglas Gregor836a7e82010-08-11 02:15:33 +00004366 if (AllowRvalues) {
4367 bool DerivedToBase = false;
4368 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004369 bool ObjCLifetimeConversion = false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00004370
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004371 // If we are initializing an rvalue reference, don't permit conversion
4372 // functions that return lvalues.
4373 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4374 const ReferenceType *RefType
4375 = Conv->getConversionType()->getAs<LValueReferenceType>();
4376 if (RefType && !RefType->getPointeeType()->isFunctionType())
4377 continue;
4378 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00004379
Douglas Gregor836a7e82010-08-11 02:15:33 +00004380 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00004381 S.CompareReferenceRelationship(
4382 DeclLoc,
4383 Conv->getConversionType().getNonReferenceType()
4384 .getUnqualifiedType(),
4385 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCall31168b02011-06-15 23:02:42 +00004386 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth8e543b32010-12-12 08:17:55 +00004387 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00004388 continue;
4389 } else {
4390 // If the conversion function doesn't return a reference type,
4391 // it can't be considered for this conversion. An rvalue reference
4392 // is only acceptable if its referencee is a function type.
4393
4394 const ReferenceType *RefType =
4395 Conv->getConversionType()->getAs<ReferenceType>();
4396 if (!RefType ||
4397 (!RefType->isLValueReferenceType() &&
4398 !RefType->getPointeeType()->isFunctionType()))
4399 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00004400 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004401
Douglas Gregor836a7e82010-08-11 02:15:33 +00004402 if (ConvTemplate)
4403 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004404 Init, DeclType, CandidateSet,
4405 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor836a7e82010-08-11 02:15:33 +00004406 else
4407 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004408 DeclType, CandidateSet,
4409 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redld92badf2010-06-30 18:13:39 +00004410 }
4411
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004412 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4413
Sebastian Redld92badf2010-06-30 18:13:39 +00004414 OverloadCandidateSet::iterator Best;
Richard Smith67ef14f2017-09-26 18:37:55 +00004415 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004416 case OR_Success:
4417 // C++ [over.ics.ref]p1:
4418 //
4419 // [...] If the parameter binds directly to the result of
4420 // applying a conversion function to the argument
4421 // expression, the implicit conversion sequence is a
4422 // user-defined conversion sequence (13.3.3.1.2), with the
4423 // second standard conversion sequence either an identity
4424 // conversion or, if the conversion function returns an
4425 // entity of a type that is a derived class of the parameter
4426 // type, a derived-to-base Conversion.
4427 if (!Best->FinalConversion.DirectBinding)
4428 return false;
4429
4430 ICS.setUserDefined();
4431 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4432 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004433 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redld92badf2010-06-30 18:13:39 +00004434 ICS.UserDefined.ConversionFunction = Best->Function;
John McCall30909032011-09-21 08:36:56 +00004435 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redld92badf2010-06-30 18:13:39 +00004436 ICS.UserDefined.EllipsisConversion = false;
4437 assert(ICS.UserDefined.After.ReferenceBinding &&
4438 ICS.UserDefined.After.DirectBinding &&
4439 "Expected a direct reference binding!");
4440 return true;
4441
4442 case OR_Ambiguous:
4443 ICS.setAmbiguous();
4444 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4445 Cand != CandidateSet.end(); ++Cand)
4446 if (Cand->Viable)
Richard Smithc2bebe92016-05-11 20:37:46 +00004447 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
Sebastian Redld92badf2010-06-30 18:13:39 +00004448 return true;
4449
4450 case OR_No_Viable_Function:
4451 case OR_Deleted:
4452 // There was no suitable conversion, or we found a deleted
4453 // conversion; continue with other checks.
4454 return false;
4455 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004456
David Blaikie8a40f702012-01-17 06:56:22 +00004457 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redld92badf2010-06-30 18:13:39 +00004458}
4459
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004460/// Compute an implicit conversion sequence for reference
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004461/// initialization.
4462static ImplicitConversionSequence
Sebastian Redldf888642011-12-03 14:54:30 +00004463TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004464 SourceLocation DeclLoc,
4465 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00004466 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004467 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4468
4469 // Most paths end in a failed conversion.
4470 ImplicitConversionSequence ICS;
4471 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4472
4473 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4474 QualType T2 = Init->getType();
4475
4476 // If the initializer is the address of an overloaded function, try
4477 // to resolve the overloaded function. If all goes well, T2 is the
4478 // type of the resulting function.
4479 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4480 DeclAccessPair Found;
4481 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4482 false, Found))
4483 T2 = Fn->getType();
4484 }
4485
4486 // Compute some basic properties of the types and the initializer.
4487 bool isRValRef = DeclType->isRValueReferenceType();
4488 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004489 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004490 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00004491 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004492 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004493 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004494 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004495
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004496
Sebastian Redld92badf2010-06-30 18:13:39 +00004497 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00004498 // A reference to type "cv1 T1" is initialized by an expression
4499 // of type "cv2 T2" as follows:
4500
Sebastian Redld92badf2010-06-30 18:13:39 +00004501 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00004502 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004503 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4504 // reference-compatible with "cv2 T2," or
4505 //
4506 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
Richard Smithce766292016-10-21 23:01:55 +00004507 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004508 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00004509 // When a parameter of reference type binds directly (8.5.3)
4510 // to an argument expression, the implicit conversion sequence
4511 // is the identity conversion, unless the argument expression
4512 // has a type that is a derived class of the parameter type,
4513 // in which case the implicit conversion sequence is a
4514 // derived-to-base Conversion (13.3.3.1).
4515 ICS.setStandard();
4516 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004517 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4518 : ObjCConversion? ICK_Compatible_Conversion
4519 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00004520 ICS.Standard.Third = ICK_Identity;
4521 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4522 ICS.Standard.setToType(0, T2);
4523 ICS.Standard.setToType(1, T1);
4524 ICS.Standard.setToType(2, T1);
4525 ICS.Standard.ReferenceBinding = true;
4526 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004527 ICS.Standard.IsLvalueReference = !isRValRef;
4528 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4529 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004530 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004531 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Craig Topperc3ec1492014-05-26 06:22:03 +00004532 ICS.Standard.CopyConstructor = nullptr;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004533 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004534
Sebastian Redld92badf2010-06-30 18:13:39 +00004535 // Nothing more to do: the inaccessibility/ambiguity check for
4536 // derived-to-base conversions is suppressed when we're
4537 // computing the implicit conversion sequence (C++
4538 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004539 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00004540 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004541
Sebastian Redld92badf2010-06-30 18:13:39 +00004542 // -- has a class type (i.e., T2 is a class type), where T1 is
4543 // not reference-related to T2, and can be implicitly
4544 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4545 // is reference-compatible with "cv3 T3" 92) (this
4546 // conversion is selected by enumerating the applicable
4547 // conversion functions (13.3.1.6) and choosing the best
4548 // one through overload resolution (13.3)),
4549 if (!SuppressUserConversions && T2->isRecordType() &&
Richard Smithdb0ac552015-12-18 22:40:25 +00004550 S.isCompleteType(DeclLoc, T2) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00004551 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00004552 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4553 Init, T2, /*AllowRvalues=*/false,
4554 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00004555 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004556 }
4557 }
4558
Sebastian Redld92badf2010-06-30 18:13:39 +00004559 // -- Otherwise, the reference shall be an lvalue reference to a
4560 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00004561 // shall be an rvalue reference.
Richard Smithce4f6082012-05-24 04:29:20 +00004562 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004563 return ICS;
4564
Douglas Gregorf143cd52011-01-24 16:14:37 +00004565 // -- If the initializer expression
4566 //
4567 // -- is an xvalue, class prvalue, array prvalue or function
John McCall31168b02011-06-15 23:02:42 +00004568 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Richard Smithce766292016-10-21 23:01:55 +00004569 if (RefRelationship == Sema::Ref_Compatible &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004570 (InitCategory.isXValue() ||
Richard Smithce766292016-10-21 23:01:55 +00004571 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4572 (InitCategory.isLValue() && T2->isFunctionType()))) {
Douglas Gregorf143cd52011-01-24 16:14:37 +00004573 ICS.setStandard();
4574 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004575 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004576 : ObjCConversion? ICK_Compatible_Conversion
4577 : ICK_Identity;
4578 ICS.Standard.Third = ICK_Identity;
4579 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4580 ICS.Standard.setToType(0, T2);
4581 ICS.Standard.setToType(1, T1);
4582 ICS.Standard.setToType(2, T1);
4583 ICS.Standard.ReferenceBinding = true;
4584 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4585 // binding unless we're binding to a class prvalue.
4586 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4587 // allow the use of rvalue references in C++98/03 for the benefit of
4588 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004589 ICS.Standard.DirectBinding =
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004590 S.getLangOpts().CPlusPlus11 ||
Richard Smithb94afe12014-07-14 19:54:05 +00004591 !(InitCategory.isPRValue() || T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00004592 ICS.Standard.IsLvalueReference = !isRValRef;
4593 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004594 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00004595 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004596 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Craig Topperc3ec1492014-05-26 06:22:03 +00004597 ICS.Standard.CopyConstructor = nullptr;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004598 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004599 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00004600 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004601
Douglas Gregorf143cd52011-01-24 16:14:37 +00004602 // -- has a class type (i.e., T2 is a class type), where T1 is not
4603 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004604 // an xvalue, class prvalue, or function lvalue of type
4605 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00004606 // "cv3 T3",
4607 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004608 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00004609 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004610 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004611 // class subobject).
4612 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
Richard Smithdb0ac552015-12-18 22:40:25 +00004613 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004614 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4615 Init, T2, /*AllowRvalues=*/true,
4616 AllowExplicit)) {
4617 // In the second case, if the reference is an rvalue reference
4618 // and the second standard conversion sequence of the
4619 // user-defined conversion sequence includes an lvalue-to-rvalue
4620 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004621 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004622 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4623 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4624
Douglas Gregor95273c32011-01-21 16:36:05 +00004625 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00004626 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004627
Richard Smith19172c42014-07-14 02:28:44 +00004628 // A temporary of function type cannot be created; don't even try.
4629 if (T1->isFunctionType())
4630 return ICS;
4631
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004632 // -- Otherwise, a temporary of type "cv1 T1" is created and
4633 // initialized from the initializer expression using the
4634 // rules for a non-reference copy initialization (8.5). The
4635 // reference is then bound to the temporary. If T1 is
4636 // reference-related to T2, cv1 must be the same
4637 // cv-qualification as, or greater cv-qualification than,
4638 // cv2; otherwise, the program is ill-formed.
4639 if (RefRelationship == Sema::Ref_Related) {
4640 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4641 // we would be reference-compatible or reference-compatible with
4642 // added qualification. But that wasn't the case, so the reference
4643 // initialization fails.
John McCall31168b02011-06-15 23:02:42 +00004644 //
4645 // Note that we only want to check address spaces and cvr-qualifiers here.
Andrey Bokhanko45d41322016-05-11 18:38:21 +00004646 // ObjC GC, lifetime and unaligned qualifiers aren't important.
John McCall31168b02011-06-15 23:02:42 +00004647 Qualifiers T1Quals = T1.getQualifiers();
4648 Qualifiers T2Quals = T2.getQualifiers();
4649 T1Quals.removeObjCGCAttr();
4650 T1Quals.removeObjCLifetime();
4651 T2Quals.removeObjCGCAttr();
4652 T2Quals.removeObjCLifetime();
Andrey Bokhanko45d41322016-05-11 18:38:21 +00004653 // MS compiler ignores __unaligned qualifier for references; do the same.
4654 T1Quals.removeUnaligned();
4655 T2Quals.removeUnaligned();
John McCall31168b02011-06-15 23:02:42 +00004656 if (!T1Quals.compatiblyIncludes(T2Quals))
4657 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004658 }
4659
4660 // If at least one of the types is a class type, the types are not
4661 // related, and we aren't allowed any user conversions, the
4662 // reference binding fails. This case is important for breaking
4663 // recursion, since TryImplicitConversion below will attempt to
4664 // create a temporary through the use of a copy constructor.
4665 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4666 (T1->isRecordType() || T2->isRecordType()))
4667 return ICS;
4668
Douglas Gregorcba72b12011-01-21 05:18:22 +00004669 // If T1 is reference-related to T2 and the reference is an rvalue
4670 // reference, the initializer expression shall not be an lvalue.
4671 if (RefRelationship >= Sema::Ref_Related &&
4672 isRValRef && Init->Classify(S.Context).isLValue())
4673 return ICS;
4674
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004675 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004676 // When a parameter of reference type is not bound directly to
4677 // an argument expression, the conversion sequence is the one
4678 // required to convert the argument expression to the
4679 // underlying type of the reference according to
4680 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4681 // to copy-initializing a temporary of the underlying type with
4682 // the argument expression. Any difference in top-level
4683 // cv-qualification is subsumed by the initialization itself
4684 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00004685 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4686 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004687 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004688 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004689 /*AllowObjCWritebackConversion=*/false,
4690 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004691
4692 // Of course, that's still a reference binding.
4693 if (ICS.isStandard()) {
4694 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004695 ICS.Standard.IsLvalueReference = !isRValRef;
Richard Smith19172c42014-07-14 02:28:44 +00004696 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004697 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004698 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004699 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004700 } else if (ICS.isUserDefined()) {
Richard Smith19172c42014-07-14 02:28:44 +00004701 const ReferenceType *LValRefType =
4702 ICS.UserDefined.ConversionFunction->getReturnType()
4703 ->getAs<LValueReferenceType>();
4704
4705 // C++ [over.ics.ref]p3:
4706 // Except for an implicit object parameter, for which see 13.3.1, a
4707 // standard conversion sequence cannot be formed if it requires [...]
4708 // binding an rvalue reference to an lvalue other than a function
4709 // lvalue.
4710 // Note that the function case is not possible here.
4711 if (DeclType->isRValueReferenceType() && LValRefType) {
4712 // FIXME: This is the wrong BadConversionSequence. The problem is binding
4713 // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4714 // reference to an rvalue!
4715 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4716 return ICS;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004717 }
Richard Smith19172c42014-07-14 02:28:44 +00004718
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004719 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004720 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
Richard Smith19172c42014-07-14 02:28:44 +00004721 ICS.UserDefined.After.BindsToFunctionLvalue = false;
4722 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004723 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4724 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004725 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00004726
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004727 return ICS;
4728}
4729
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004730static ImplicitConversionSequence
4731TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4732 bool SuppressUserConversions,
4733 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004734 bool AllowObjCWritebackConversion,
4735 bool AllowExplicit = false);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004736
4737/// TryListConversion - Try to copy-initialize a value of type ToType from the
4738/// initializer list From.
4739static ImplicitConversionSequence
4740TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4741 bool SuppressUserConversions,
4742 bool InOverloadResolution,
4743 bool AllowObjCWritebackConversion) {
4744 // C++11 [over.ics.list]p1:
4745 // When an argument is an initializer list, it is not an expression and
4746 // special rules apply for converting it to a parameter type.
4747
4748 ImplicitConversionSequence Result;
4749 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4750
Sebastian Redl09edce02012-01-23 22:09:39 +00004751 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004752 // initialized from init lists.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004753 if (!S.isCompleteType(From->getBeginLoc(), ToType))
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004754 return Result;
4755
Larisse Voufo19d08672015-01-27 18:47:05 +00004756 // Per DR1467:
4757 // If the parameter type is a class X and the initializer list has a single
4758 // element of type cv U, where U is X or a class derived from X, the
4759 // implicit conversion sequence is the one required to convert the element
4760 // to the parameter type.
4761 //
4762 // Otherwise, if the parameter type is a character array [... ]
4763 // and the initializer list has a single element that is an
4764 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4765 // implicit conversion sequence is the identity conversion.
4766 if (From->getNumInits() == 1) {
4767 if (ToType->isRecordType()) {
4768 QualType InitType = From->getInit(0)->getType();
4769 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004770 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
Larisse Voufo19d08672015-01-27 18:47:05 +00004771 return TryCopyInitialization(S, From->getInit(0), ToType,
4772 SuppressUserConversions,
4773 InOverloadResolution,
4774 AllowObjCWritebackConversion);
4775 }
Richard Smith1bbaba82015-01-27 23:23:39 +00004776 // FIXME: Check the other conditions here: array of character type,
4777 // initializer is a string literal.
4778 if (ToType->isArrayType()) {
Larisse Voufo19d08672015-01-27 18:47:05 +00004779 InitializedEntity Entity =
4780 InitializedEntity::InitializeParameter(S.Context, ToType,
4781 /*Consumed=*/false);
4782 if (S.CanPerformCopyInitialization(Entity, From)) {
4783 Result.setStandard();
4784 Result.Standard.setAsIdentityConversion();
4785 Result.Standard.setFromType(ToType);
4786 Result.Standard.setAllToTypes(ToType);
4787 return Result;
4788 }
4789 }
4790 }
4791
4792 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004793 // C++11 [over.ics.list]p2:
4794 // If the parameter type is std::initializer_list<X> or "array of X" and
4795 // all the elements can be implicitly converted to X, the implicit
4796 // conversion sequence is the worst conversion necessary to convert an
4797 // element of the list to X.
Larisse Voufo19d08672015-01-27 18:47:05 +00004798 //
4799 // C++14 [over.ics.list]p3:
NAKAMURA Takumib01d86b2015-02-25 11:02:00 +00004800 // Otherwise, if the parameter type is "array of N X", if the initializer
Larisse Voufo19d08672015-01-27 18:47:05 +00004801 // list has exactly N elements or if it has fewer than N elements and X is
4802 // default-constructible, and if all the elements of the initializer list
4803 // can be implicitly converted to X, the implicit conversion sequence is
4804 // the worst conversion necessary to convert an element of the list to X.
Richard Smith1bbaba82015-01-27 23:23:39 +00004805 //
4806 // FIXME: We're missing a lot of these checks.
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004807 bool toStdInitializerList = false;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004808 QualType X;
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004809 if (ToType->isArrayType())
Richard Smith0db1ea52012-12-09 06:48:56 +00004810 X = S.Context.getAsArrayType(ToType)->getElementType();
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004811 else
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004812 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004813 if (!X.isNull()) {
4814 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4815 Expr *Init = From->getInit(i);
4816 ImplicitConversionSequence ICS =
4817 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4818 InOverloadResolution,
4819 AllowObjCWritebackConversion);
4820 // If a single element isn't convertible, fail.
4821 if (ICS.isBad()) {
4822 Result = ICS;
4823 break;
4824 }
4825 // Otherwise, look for the worst conversion.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004826 if (Result.isBad() || CompareImplicitConversionSequences(
4827 S, From->getBeginLoc(), ICS, Result) ==
4828 ImplicitConversionSequence::Worse)
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004829 Result = ICS;
4830 }
Douglas Gregor0f5c1c02012-04-04 23:09:20 +00004831
4832 // For an empty list, we won't have computed any conversion sequence.
4833 // Introduce the identity conversion sequence.
4834 if (From->getNumInits() == 0) {
4835 Result.setStandard();
4836 Result.Standard.setAsIdentityConversion();
4837 Result.Standard.setFromType(ToType);
4838 Result.Standard.setAllToTypes(ToType);
4839 }
4840
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004841 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004842 return Result;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004843 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004844
Larisse Voufo19d08672015-01-27 18:47:05 +00004845 // C++14 [over.ics.list]p4:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004846 // C++11 [over.ics.list]p3:
4847 // Otherwise, if the parameter is a non-aggregate class X and overload
4848 // resolution chooses a single best constructor [...] the implicit
4849 // conversion sequence is a user-defined conversion sequence. If multiple
4850 // constructors are viable but none is better than the others, the
4851 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004852 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4853 // This function can deal with initializer lists.
Richard Smitha93f1022013-09-06 22:30:28 +00004854 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4855 /*AllowExplicit=*/false,
4856 InOverloadResolution, /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004857 AllowObjCWritebackConversion,
4858 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004859 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004860
Larisse Voufo19d08672015-01-27 18:47:05 +00004861 // C++14 [over.ics.list]p5:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004862 // C++11 [over.ics.list]p4:
4863 // Otherwise, if the parameter has an aggregate type which can be
4864 // initialized from the initializer list [...] the implicit conversion
4865 // sequence is a user-defined conversion sequence.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004866 if (ToType->isAggregateType()) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004867 // Type is an aggregate, argument is an init list. At this point it comes
4868 // down to checking whether the initialization works.
4869 // FIXME: Find out whether this parameter is consumed or not.
Richard Smithb8c0f552016-12-09 18:49:13 +00004870 // FIXME: Expose SemaInit's aggregate initialization code so that we don't
4871 // need to call into the initialization code here; overload resolution
4872 // should not be doing that.
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004873 InitializedEntity Entity =
4874 InitializedEntity::InitializeParameter(S.Context, ToType,
4875 /*Consumed=*/false);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004876 if (S.CanPerformCopyInitialization(Entity, From)) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004877 Result.setUserDefined();
4878 Result.UserDefined.Before.setAsIdentityConversion();
4879 // Initializer lists don't have a type.
4880 Result.UserDefined.Before.setFromType(QualType());
4881 Result.UserDefined.Before.setAllToTypes(QualType());
4882
4883 Result.UserDefined.After.setAsIdentityConversion();
4884 Result.UserDefined.After.setFromType(ToType);
4885 Result.UserDefined.After.setAllToTypes(ToType);
Craig Topperc3ec1492014-05-26 06:22:03 +00004886 Result.UserDefined.ConversionFunction = nullptr;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004887 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004888 return Result;
4889 }
4890
Larisse Voufo19d08672015-01-27 18:47:05 +00004891 // C++14 [over.ics.list]p6:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004892 // C++11 [over.ics.list]p5:
4893 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redldf888642011-12-03 14:54:30 +00004894 if (ToType->isReferenceType()) {
4895 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4896 // mention initializer lists in any way. So we go by what list-
4897 // initialization would do and try to extrapolate from that.
4898
4899 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4900
4901 // If the initializer list has a single element that is reference-related
4902 // to the parameter type, we initialize the reference from that.
4903 if (From->getNumInits() == 1) {
4904 Expr *Init = From->getInit(0);
4905
4906 QualType T2 = Init->getType();
4907
4908 // If the initializer is the address of an overloaded function, try
4909 // to resolve the overloaded function. If all goes well, T2 is the
4910 // type of the resulting function.
4911 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4912 DeclAccessPair Found;
4913 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4914 Init, ToType, false, Found))
4915 T2 = Fn->getType();
4916 }
4917
4918 // Compute some basic properties of the types and the initializer.
4919 bool dummy1 = false;
4920 bool dummy2 = false;
4921 bool dummy3 = false;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004922 Sema::ReferenceCompareResult RefRelationship =
4923 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2, dummy1,
Sebastian Redldf888642011-12-03 14:54:30 +00004924 dummy2, dummy3);
4925
Richard Smith4d2bbd72013-09-06 01:22:42 +00004926 if (RefRelationship >= Sema::Ref_Related) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004927 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
Richard Smitha93f1022013-09-06 22:30:28 +00004928 SuppressUserConversions,
4929 /*AllowExplicit=*/false);
Richard Smith4d2bbd72013-09-06 01:22:42 +00004930 }
Sebastian Redldf888642011-12-03 14:54:30 +00004931 }
4932
4933 // Otherwise, we bind the reference to a temporary created from the
4934 // initializer list.
4935 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4936 InOverloadResolution,
4937 AllowObjCWritebackConversion);
4938 if (Result.isFailure())
4939 return Result;
4940 assert(!Result.isEllipsis() &&
4941 "Sub-initialization cannot result in ellipsis conversion.");
4942
4943 // Can we even bind to a temporary?
4944 if (ToType->isRValueReferenceType() ||
4945 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4946 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4947 Result.UserDefined.After;
4948 SCS.ReferenceBinding = true;
4949 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4950 SCS.BindsToRvalue = true;
4951 SCS.BindsToFunctionLvalue = false;
4952 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4953 SCS.ObjCLifetimeConversionBinding = false;
4954 } else
4955 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4956 From, ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004957 return Result;
Sebastian Redldf888642011-12-03 14:54:30 +00004958 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004959
Larisse Voufo19d08672015-01-27 18:47:05 +00004960 // C++14 [over.ics.list]p7:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004961 // C++11 [over.ics.list]p6:
4962 // Otherwise, if the parameter type is not a class:
4963 if (!ToType->isRecordType()) {
Larisse Voufo19d08672015-01-27 18:47:05 +00004964 // - if the initializer list has one element that is not itself an
4965 // initializer list, the implicit conversion sequence is the one
4966 // required to convert the element to the parameter type.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004967 unsigned NumInits = From->getNumInits();
Richard Smith1bbaba82015-01-27 23:23:39 +00004968 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004969 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4970 SuppressUserConversions,
4971 InOverloadResolution,
4972 AllowObjCWritebackConversion);
4973 // - if the initializer list has no elements, the implicit conversion
4974 // sequence is the identity conversion.
4975 else if (NumInits == 0) {
4976 Result.setStandard();
4977 Result.Standard.setAsIdentityConversion();
John McCallb73bc9a2012-04-04 02:40:27 +00004978 Result.Standard.setFromType(ToType);
4979 Result.Standard.setAllToTypes(ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004980 }
4981 return Result;
4982 }
4983
Larisse Voufo19d08672015-01-27 18:47:05 +00004984 // C++14 [over.ics.list]p8:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004985 // C++11 [over.ics.list]p7:
4986 // In all cases other than those enumerated above, no conversion is possible
4987 return Result;
4988}
4989
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004990/// TryCopyInitialization - Try to copy-initialize a value of type
4991/// ToType from the expression From. Return the implicit conversion
4992/// sequence required to pass this argument, which may be a bad
4993/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00004994/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00004995/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004996static ImplicitConversionSequence
4997TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004998 bool SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004999 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005000 bool AllowObjCWritebackConversion,
5001 bool AllowExplicit) {
Sebastian Redlb17be8d2011-10-16 18:19:34 +00005002 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
5003 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
5004 InOverloadResolution,AllowObjCWritebackConversion);
5005
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00005006 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005007 return TryReferenceInit(S, From, ToType,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005008 /*FIXME:*/ From->getBeginLoc(),
5009 SuppressUserConversions, AllowExplicit);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00005010
John McCall5c32be02010-08-24 20:38:10 +00005011 return TryImplicitConversion(S, From, ToType,
5012 SuppressUserConversions,
5013 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00005014 InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00005015 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005016 AllowObjCWritebackConversion,
5017 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00005018}
5019
Anna Zaks1b068122011-07-28 19:46:48 +00005020static bool TryCopyInitialization(const CanQualType FromQTy,
5021 const CanQualType ToQTy,
5022 Sema &S,
5023 SourceLocation Loc,
5024 ExprValueKind FromVK) {
5025 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5026 ImplicitConversionSequence ICS =
5027 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5028
5029 return !ICS.isBad();
5030}
5031
Douglas Gregor436424c2008-11-18 23:14:02 +00005032/// TryObjectArgumentInitialization - Try to initialize the object
5033/// parameter of the given member function (@c Method) from the
5034/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00005035static ImplicitConversionSequence
Richard Smith0f59cb32015-12-18 21:45:41 +00005036TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00005037 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00005038 CXXMethodDecl *Method,
5039 CXXRecordDecl *ActingContext) {
5040 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00005041 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
5042 // const volatile object.
5043 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
5044 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00005045 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00005046
5047 // Set up the conversion sequence as a "bad" conversion, to allow us
5048 // to exit early.
5049 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00005050
5051 // We need to have an object of class type.
Douglas Gregor02824322011-01-26 19:30:28 +00005052 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005053 FromType = PT->getPointeeType();
5054
Douglas Gregor02824322011-01-26 19:30:28 +00005055 // When we had a pointer, it's implicitly dereferenced, so we
5056 // better have an lvalue.
5057 assert(FromClassification.isLValue());
5058 }
5059
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005060 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00005061
Douglas Gregor02824322011-01-26 19:30:28 +00005062 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005063 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00005064 // parameter is
5065 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005066 // - "lvalue reference to cv X" for functions declared without a
5067 // ref-qualifier or with the & ref-qualifier
5068 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00005069 // ref-qualifier
5070 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005071 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00005072 // cv-qualification on the member function declaration.
5073 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005074 // However, when finding an implicit conversion sequence for the argument, we
Richard Smith122f88d2016-12-06 23:52:28 +00005075 // are not allowed to perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00005076 // (C++ [over.match.funcs]p5). We perform a simplified version of
5077 // reference binding here, that allows class rvalues to bind to
5078 // non-constant references.
5079
Douglas Gregor02824322011-01-26 19:30:28 +00005080 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00005081 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005082 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005083 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00005084 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00005085 ICS.setBad(BadConversionSequence::bad_qualifiers,
Richard Smith03c66d32013-01-26 02:07:32 +00005086 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00005087 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00005088 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005089
5090 // Check that we have either the same type or a derived type. It
5091 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00005092 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00005093 ImplicitConversionKind SecondKind;
5094 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5095 SecondKind = ICK_Identity;
Richard Smith0f59cb32015-12-18 21:45:41 +00005096 } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00005097 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00005098 else {
John McCall65eb8792010-02-25 01:37:24 +00005099 ICS.setBad(BadConversionSequence::unrelated_class,
5100 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00005101 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00005102 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005103
Douglas Gregor02824322011-01-26 19:30:28 +00005104 // Check the ref-qualifier.
5105 switch (Method->getRefQualifier()) {
5106 case RQ_None:
5107 // Do nothing; we don't care about lvalueness or rvalueness.
5108 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005109
Douglas Gregor02824322011-01-26 19:30:28 +00005110 case RQ_LValue:
5111 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
5112 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005113 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00005114 ImplicitParamType);
5115 return ICS;
5116 }
5117 break;
5118
5119 case RQ_RValue:
5120 if (!FromClassification.isRValue()) {
5121 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005122 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00005123 ImplicitParamType);
5124 return ICS;
5125 }
5126 break;
5127 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005128
Douglas Gregor436424c2008-11-18 23:14:02 +00005129 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00005130 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00005131 ICS.Standard.setAsIdentityConversion();
5132 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00005133 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00005134 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00005135 ICS.Standard.ReferenceBinding = true;
5136 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005137 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00005138 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00005139 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5140 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5141 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00005142 return ICS;
5143}
5144
5145/// PerformObjectArgumentInitialization - Perform initialization of
5146/// the implicit object parameter for the given Method with the given
5147/// expression.
John Wiegley01296292011-04-08 18:41:53 +00005148ExprResult
5149Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005150 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00005151 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00005152 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005153 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00005154 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005155 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00005156
Douglas Gregor02824322011-01-26 19:30:28 +00005157 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005158 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005159 FromRecordType = PT->getPointeeType();
5160 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00005161 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005162 } else {
5163 FromRecordType = From->getType();
5164 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00005165 FromClassification = From->Classify(Context);
Richard Smith7ed5fb22018-07-27 17:13:18 +00005166
5167 // When performing member access on an rvalue, materialize a temporary.
5168 if (From->isRValue()) {
5169 From = CreateMaterializeTemporaryExpr(FromRecordType, From,
5170 Method->getRefQualifier() !=
5171 RefQualifierKind::RQ_RValue);
5172 }
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005173 }
5174
John McCall6e9f8f62009-12-03 04:06:58 +00005175 // Note that we always use the true parent context when performing
5176 // the actual argument initialization.
Nico Weberb58e51c2014-11-19 05:21:39 +00005177 ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005178 *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
Richard Smith0f59cb32015-12-18 21:45:41 +00005179 Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005180 if (ICS.isBad()) {
Jacob Bandes-Storchbb935782017-12-31 18:27:29 +00005181 switch (ICS.Bad.Kind) {
5182 case BadConversionSequence::bad_qualifiers: {
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005183 Qualifiers FromQs = FromRecordType.getQualifiers();
5184 Qualifiers ToQs = DestType.getQualifiers();
5185 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5186 if (CVR) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005187 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
5188 << Method->getDeclName() << FromRecordType << (CVR - 1)
5189 << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005190 Diag(Method->getLocation(), diag::note_previous_decl)
5191 << Method->getDeclName();
John Wiegley01296292011-04-08 18:41:53 +00005192 return ExprError();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005193 }
Jacob Bandes-Storchbb935782017-12-31 18:27:29 +00005194 break;
5195 }
5196
5197 case BadConversionSequence::lvalue_ref_to_rvalue:
5198 case BadConversionSequence::rvalue_ref_to_lvalue: {
5199 bool IsRValueQualified =
5200 Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005201 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
5202 << Method->getDeclName() << FromClassification.isRValue()
5203 << IsRValueQualified;
Jacob Bandes-Storchbb935782017-12-31 18:27:29 +00005204 Diag(Method->getLocation(), diag::note_previous_decl)
5205 << Method->getDeclName();
5206 return ExprError();
5207 }
5208
5209 case BadConversionSequence::no_conversion:
5210 case BadConversionSequence::unrelated_class:
5211 break;
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005212 }
5213
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005214 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
5215 << ImplicitParamRecordType << FromRecordType
5216 << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005217 }
Mike Stump11289f42009-09-09 15:08:12 +00005218
John Wiegley01296292011-04-08 18:41:53 +00005219 if (ICS.Standard.Second == ICK_Derived_To_Base) {
5220 ExprResult FromRes =
5221 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5222 if (FromRes.isInvalid())
5223 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005224 From = FromRes.get();
John Wiegley01296292011-04-08 18:41:53 +00005225 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005226
Douglas Gregorcc3f3252010-03-03 23:55:11 +00005227 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley01296292011-04-08 18:41:53 +00005228 From = ImpCastExprToType(From, DestType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005229 From->getValueKind()).get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005230 return From;
Douglas Gregor436424c2008-11-18 23:14:02 +00005231}
5232
Douglas Gregor5fb53972009-01-14 15:45:31 +00005233/// TryContextuallyConvertToBool - Attempt to contextually convert the
5234/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00005235static ImplicitConversionSequence
5236TryContextuallyConvertToBool(Sema &S, Expr *From) {
John McCall5c32be02010-08-24 20:38:10 +00005237 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00005238 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00005239 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00005240 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00005241 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005242 /*AllowObjCWritebackConversion=*/false,
5243 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00005244}
5245
5246/// PerformContextuallyConvertToBool - Perform a contextual conversion
5247/// of the expression From to bool (C++0x [conv]p3).
John Wiegley01296292011-04-08 18:41:53 +00005248ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00005249 if (checkPlaceholderForOverload(*this, From))
5250 return ExprError();
5251
John McCall5c32be02010-08-24 20:38:10 +00005252 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00005253 if (!ICS.isBad())
5254 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005255
Fariborz Jahanian76197412009-11-18 18:26:29 +00005256 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005257 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
5258 << From->getType() << From->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00005259 return ExprError();
Douglas Gregor5fb53972009-01-14 15:45:31 +00005260}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005261
Richard Smithf8379a02012-01-18 23:55:52 +00005262/// Check that the specified conversion is permitted in a converted constant
5263/// expression, according to C++11 [expr.const]p3. Return true if the conversion
5264/// is acceptable.
5265static bool CheckConvertedConstantConversions(Sema &S,
5266 StandardConversionSequence &SCS) {
5267 // Since we know that the target type is an integral or unscoped enumeration
5268 // type, most conversion kinds are impossible. All possible First and Third
5269 // conversions are fine.
5270 switch (SCS.Second) {
5271 case ICK_Identity:
Richard Smith3c4f8d22016-10-16 17:54:23 +00005272 case ICK_Function_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005273 case ICK_Integral_Promotion:
Richard Smith410cc892014-11-26 03:26:53 +00005274 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
Egor Churaev89831422016-12-23 14:55:49 +00005275 case ICK_Zero_Queue_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005276 return true;
5277
5278 case ICK_Boolean_Conversion:
Richard Smithca24ed42012-09-13 22:00:12 +00005279 // Conversion from an integral or unscoped enumeration type to bool is
Richard Smith410cc892014-11-26 03:26:53 +00005280 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5281 // conversion, so we allow it in a converted constant expression.
5282 //
5283 // FIXME: Per core issue 1407, we should not allow this, but that breaks
5284 // a lot of popular code. We should at least add a warning for this
5285 // (non-conforming) extension.
Richard Smithca24ed42012-09-13 22:00:12 +00005286 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5287 SCS.getToType(2)->isBooleanType();
5288
Richard Smith410cc892014-11-26 03:26:53 +00005289 case ICK_Pointer_Conversion:
5290 case ICK_Pointer_Member:
5291 // C++1z: null pointer conversions and null member pointer conversions are
5292 // only permitted if the source type is std::nullptr_t.
5293 return SCS.getFromType()->isNullPtrType();
5294
5295 case ICK_Floating_Promotion:
5296 case ICK_Complex_Promotion:
5297 case ICK_Floating_Conversion:
5298 case ICK_Complex_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005299 case ICK_Floating_Integral:
Richard Smith410cc892014-11-26 03:26:53 +00005300 case ICK_Compatible_Conversion:
5301 case ICK_Derived_To_Base:
5302 case ICK_Vector_Conversion:
5303 case ICK_Vector_Splat:
Richard Smithf8379a02012-01-18 23:55:52 +00005304 case ICK_Complex_Real:
Richard Smith410cc892014-11-26 03:26:53 +00005305 case ICK_Block_Pointer_Conversion:
5306 case ICK_TransparentUnionConversion:
5307 case ICK_Writeback_Conversion:
5308 case ICK_Zero_Event_Conversion:
George Burgess IV45461812015-10-11 20:13:20 +00005309 case ICK_C_Only_Conversion:
George Burgess IV2099b542016-09-02 22:59:57 +00005310 case ICK_Incompatible_Pointer_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005311 return false;
5312
5313 case ICK_Lvalue_To_Rvalue:
5314 case ICK_Array_To_Pointer:
5315 case ICK_Function_To_Pointer:
Richard Smith410cc892014-11-26 03:26:53 +00005316 llvm_unreachable("found a first conversion kind in Second");
5317
Richard Smithf8379a02012-01-18 23:55:52 +00005318 case ICK_Qualification:
Richard Smith410cc892014-11-26 03:26:53 +00005319 llvm_unreachable("found a third conversion kind in Second");
Richard Smithf8379a02012-01-18 23:55:52 +00005320
5321 case ICK_Num_Conversion_Kinds:
5322 break;
5323 }
5324
5325 llvm_unreachable("unknown conversion kind");
5326}
5327
5328/// CheckConvertedConstantExpression - Check that the expression From is a
5329/// converted constant expression of type T, perform the conversion and produce
5330/// the converted expression, per C++11 [expr.const]p3.
Richard Smith410cc892014-11-26 03:26:53 +00005331static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5332 QualType T, APValue &Value,
5333 Sema::CCEKind CCE,
5334 bool RequireInt) {
5335 assert(S.getLangOpts().CPlusPlus11 &&
5336 "converted constant expression outside C++11");
Richard Smithf8379a02012-01-18 23:55:52 +00005337
Richard Smith410cc892014-11-26 03:26:53 +00005338 if (checkPlaceholderForOverload(S, From))
Richard Smithf8379a02012-01-18 23:55:52 +00005339 return ExprError();
5340
Richard Smith410cc892014-11-26 03:26:53 +00005341 // C++1z [expr.const]p3:
5342 // A converted constant expression of type T is an expression,
5343 // implicitly converted to type T, where the converted
5344 // expression is a constant expression and the implicit conversion
5345 // sequence contains only [... list of conversions ...].
Ismail Pazarbasi4a007742016-09-07 18:24:54 +00005346 // C++1z [stmt.if]p2:
5347 // If the if statement is of the form if constexpr, the value of the
5348 // condition shall be a contextually converted constant expression of type
5349 // bool.
Richard Smithf8379a02012-01-18 23:55:52 +00005350 ImplicitConversionSequence ICS =
Ismail Pazarbasi4a007742016-09-07 18:24:54 +00005351 CCE == Sema::CCEK_ConstexprIf
5352 ? TryContextuallyConvertToBool(S, From)
5353 : TryCopyInitialization(S, From, T,
5354 /*SuppressUserConversions=*/false,
5355 /*InOverloadResolution=*/false,
5356 /*AllowObjcWritebackConversion=*/false,
5357 /*AllowExplicit=*/false);
Craig Topperc3ec1492014-05-26 06:22:03 +00005358 StandardConversionSequence *SCS = nullptr;
Richard Smithf8379a02012-01-18 23:55:52 +00005359 switch (ICS.getKind()) {
5360 case ImplicitConversionSequence::StandardConversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005361 SCS = &ICS.Standard;
5362 break;
5363 case ImplicitConversionSequence::UserDefinedConversion:
Richard Smith410cc892014-11-26 03:26:53 +00005364 // We are converting to a non-class type, so the Before sequence
5365 // must be trivial.
Richard Smithf8379a02012-01-18 23:55:52 +00005366 SCS = &ICS.UserDefined.After;
5367 break;
5368 case ImplicitConversionSequence::AmbiguousConversion:
5369 case ImplicitConversionSequence::BadConversion:
Richard Smith410cc892014-11-26 03:26:53 +00005370 if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005371 return S.Diag(From->getBeginLoc(),
Richard Smith410cc892014-11-26 03:26:53 +00005372 diag::err_typecheck_converted_constant_expression)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005373 << From->getType() << From->getSourceRange() << T;
Richard Smithf8379a02012-01-18 23:55:52 +00005374 return ExprError();
5375
5376 case ImplicitConversionSequence::EllipsisConversion:
5377 llvm_unreachable("ellipsis conversion in converted constant expression");
5378 }
5379
Richard Smith410cc892014-11-26 03:26:53 +00005380 // Check that we would only use permitted conversions.
5381 if (!CheckConvertedConstantConversions(S, *SCS)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005382 return S.Diag(From->getBeginLoc(),
Richard Smith410cc892014-11-26 03:26:53 +00005383 diag::err_typecheck_converted_constant_expression_disallowed)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005384 << From->getType() << From->getSourceRange() << T;
Richard Smith410cc892014-11-26 03:26:53 +00005385 }
5386 // [...] and where the reference binding (if any) binds directly.
5387 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005388 return S.Diag(From->getBeginLoc(),
Richard Smith410cc892014-11-26 03:26:53 +00005389 diag::err_typecheck_converted_constant_expression_indirect)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005390 << From->getType() << From->getSourceRange() << T;
Richard Smith410cc892014-11-26 03:26:53 +00005391 }
5392
5393 ExprResult Result =
5394 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
Richard Smithf8379a02012-01-18 23:55:52 +00005395 if (Result.isInvalid())
5396 return Result;
5397
5398 // Check for a narrowing implicit conversion.
5399 APValue PreNarrowingValue;
Richard Smith5614ca72012-03-23 23:55:39 +00005400 QualType PreNarrowingType;
Richard Smith410cc892014-11-26 03:26:53 +00005401 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
Richard Smith5614ca72012-03-23 23:55:39 +00005402 PreNarrowingType)) {
Richard Smith52e624f2016-12-21 21:42:57 +00005403 case NK_Dependent_Narrowing:
5404 // Implicit conversion to a narrower type, but the expression is
5405 // value-dependent so we can't tell whether it's actually narrowing.
Richard Smithf8379a02012-01-18 23:55:52 +00005406 case NK_Variable_Narrowing:
5407 // Implicit conversion to a narrower type, and the value is not a constant
5408 // expression. We'll diagnose this in a moment.
5409 case NK_Not_Narrowing:
5410 break;
5411
5412 case NK_Constant_Narrowing:
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005413 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5414 << CCE << /*Constant*/ 1
5415 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
Richard Smithf8379a02012-01-18 23:55:52 +00005416 break;
5417
5418 case NK_Type_Narrowing:
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005419 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5420 << CCE << /*Constant*/ 0 << From->getType() << T;
Richard Smithf8379a02012-01-18 23:55:52 +00005421 break;
5422 }
5423
Richard Smith52e624f2016-12-21 21:42:57 +00005424 if (Result.get()->isValueDependent()) {
5425 Value = APValue();
5426 return Result;
5427 }
5428
Richard Smithf8379a02012-01-18 23:55:52 +00005429 // Check the expression is a constant expression.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005430 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithf8379a02012-01-18 23:55:52 +00005431 Expr::EvalResult Eval;
5432 Eval.Diag = &Notes;
Reid Kleckner1a840d22018-05-10 18:57:35 +00005433 Expr::ConstExprUsage Usage = CCE == Sema::CCEK_TemplateArg
5434 ? Expr::EvaluateForMangling
5435 : Expr::EvaluateForCodeGen;
Richard Smithf8379a02012-01-18 23:55:52 +00005436
Reid Kleckner1a840d22018-05-10 18:57:35 +00005437 if (!Result.get()->EvaluateAsConstantExpr(Eval, Usage, S.Context) ||
Richard Smith410cc892014-11-26 03:26:53 +00005438 (RequireInt && !Eval.Val.isInt())) {
Richard Smithf8379a02012-01-18 23:55:52 +00005439 // The expression can't be folded, so we can't keep it at this position in
5440 // the AST.
5441 Result = ExprError();
Richard Smith911e1422012-01-30 22:27:01 +00005442 } else {
Richard Smith410cc892014-11-26 03:26:53 +00005443 Value = Eval.Val;
Richard Smith911e1422012-01-30 22:27:01 +00005444
5445 if (Notes.empty()) {
5446 // It's a constant expression.
5447 return Result;
5448 }
Richard Smithf8379a02012-01-18 23:55:52 +00005449 }
5450
5451 // It's not a constant expression. Produce an appropriate diagnostic.
5452 if (Notes.size() == 1 &&
5453 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
Richard Smith410cc892014-11-26 03:26:53 +00005454 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
Richard Smithf8379a02012-01-18 23:55:52 +00005455 else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005456 S.Diag(From->getBeginLoc(), diag::err_expr_not_cce)
5457 << CCE << From->getSourceRange();
Richard Smithf8379a02012-01-18 23:55:52 +00005458 for (unsigned I = 0; I < Notes.size(); ++I)
Richard Smith410cc892014-11-26 03:26:53 +00005459 S.Diag(Notes[I].first, Notes[I].second);
Richard Smithf8379a02012-01-18 23:55:52 +00005460 }
Richard Smith410cc892014-11-26 03:26:53 +00005461 return ExprError();
Richard Smithf8379a02012-01-18 23:55:52 +00005462}
5463
Richard Smith410cc892014-11-26 03:26:53 +00005464ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5465 APValue &Value, CCEKind CCE) {
5466 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5467}
5468
5469ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5470 llvm::APSInt &Value,
5471 CCEKind CCE) {
5472 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5473
5474 APValue V;
5475 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
Richard Smith01bfa682016-12-27 02:02:09 +00005476 if (!R.isInvalid() && !R.get()->isValueDependent())
Richard Smith410cc892014-11-26 03:26:53 +00005477 Value = V.getInt();
5478 return R;
5479}
5480
5481
John McCallfec112d2011-09-09 06:11:02 +00005482/// dropPointerConversions - If the given standard conversion sequence
5483/// involves any pointer conversions, remove them. This may change
5484/// the result type of the conversion sequence.
5485static void dropPointerConversion(StandardConversionSequence &SCS) {
5486 if (SCS.Second == ICK_Pointer_Conversion) {
5487 SCS.Second = ICK_Identity;
5488 SCS.Third = ICK_Identity;
5489 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5490 }
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005491}
John McCall5c32be02010-08-24 20:38:10 +00005492
John McCallfec112d2011-09-09 06:11:02 +00005493/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5494/// convert the expression From to an Objective-C pointer type.
5495static ImplicitConversionSequence
5496TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5497 // Do an implicit conversion to 'id'.
5498 QualType Ty = S.Context.getObjCIdType();
5499 ImplicitConversionSequence ICS
5500 = TryImplicitConversion(S, From, Ty,
5501 // FIXME: Are these flags correct?
5502 /*SuppressUserConversions=*/false,
5503 /*AllowExplicit=*/true,
5504 /*InOverloadResolution=*/false,
5505 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005506 /*AllowObjCWritebackConversion=*/false,
5507 /*AllowObjCConversionOnExplicit=*/true);
John McCallfec112d2011-09-09 06:11:02 +00005508
5509 // Strip off any final conversions to 'id'.
5510 switch (ICS.getKind()) {
5511 case ImplicitConversionSequence::BadConversion:
5512 case ImplicitConversionSequence::AmbiguousConversion:
5513 case ImplicitConversionSequence::EllipsisConversion:
5514 break;
5515
5516 case ImplicitConversionSequence::UserDefinedConversion:
5517 dropPointerConversion(ICS.UserDefined.After);
5518 break;
5519
5520 case ImplicitConversionSequence::StandardConversion:
5521 dropPointerConversion(ICS.Standard);
5522 break;
5523 }
5524
5525 return ICS;
5526}
5527
5528/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5529/// conversion of the expression From to an Objective-C pointer type.
Richard Smithe15a3702016-10-06 23:12:58 +00005530/// Returns a valid but null ExprResult if no conversion sequence exists.
John McCallfec112d2011-09-09 06:11:02 +00005531ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00005532 if (checkPlaceholderForOverload(*this, From))
5533 return ExprError();
5534
John McCall8b07ec22010-05-15 11:32:37 +00005535 QualType Ty = Context.getObjCIdType();
John McCallfec112d2011-09-09 06:11:02 +00005536 ImplicitConversionSequence ICS =
5537 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005538 if (!ICS.isBad())
5539 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
Richard Smithe15a3702016-10-06 23:12:58 +00005540 return ExprResult();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005541}
Douglas Gregor5fb53972009-01-14 15:45:31 +00005542
Richard Smith8dd34252012-02-04 07:07:42 +00005543/// Determine whether the provided type is an integral type, or an enumeration
5544/// type of a permitted flavor.
Richard Smithccc11812013-05-21 19:05:48 +00005545bool Sema::ICEConvertDiagnoser::match(QualType T) {
5546 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5547 : T->isIntegralOrUnscopedEnumerationType();
Richard Smith8dd34252012-02-04 07:07:42 +00005548}
5549
Larisse Voufo236bec22013-06-10 06:50:24 +00005550static ExprResult
5551diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5552 Sema::ContextualImplicitConverter &Converter,
5553 QualType T, UnresolvedSetImpl &ViableConversions) {
5554
5555 if (Converter.Suppress)
5556 return ExprError();
5557
5558 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5559 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5560 CXXConversionDecl *Conv =
5561 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5562 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5563 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5564 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005565 return From;
Larisse Voufo236bec22013-06-10 06:50:24 +00005566}
5567
5568static bool
5569diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5570 Sema::ContextualImplicitConverter &Converter,
5571 QualType T, bool HadMultipleCandidates,
5572 UnresolvedSetImpl &ExplicitConversions) {
5573 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5574 DeclAccessPair Found = ExplicitConversions[0];
5575 CXXConversionDecl *Conversion =
5576 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5577
5578 // The user probably meant to invoke the given explicit
5579 // conversion; use it.
5580 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5581 std::string TypeStr;
5582 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5583
5584 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005585 << FixItHint::CreateInsertion(From->getBeginLoc(),
Larisse Voufo236bec22013-06-10 06:50:24 +00005586 "static_cast<" + TypeStr + ">(")
5587 << FixItHint::CreateInsertion(
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005588 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
Larisse Voufo236bec22013-06-10 06:50:24 +00005589 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5590
5591 // If we aren't in a SFINAE context, build a call to the
5592 // explicit conversion function.
5593 if (SemaRef.isSFINAEContext())
5594 return true;
5595
Craig Topperc3ec1492014-05-26 06:22:03 +00005596 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
Larisse Voufo236bec22013-06-10 06:50:24 +00005597 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5598 HadMultipleCandidates);
5599 if (Result.isInvalid())
5600 return true;
5601 // Record usage of conversion in an implicit cast.
5602 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005603 CK_UserDefinedConversion, Result.get(),
5604 nullptr, Result.get()->getValueKind());
Larisse Voufo236bec22013-06-10 06:50:24 +00005605 }
5606 return false;
5607}
5608
5609static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5610 Sema::ContextualImplicitConverter &Converter,
5611 QualType T, bool HadMultipleCandidates,
5612 DeclAccessPair &Found) {
5613 CXXConversionDecl *Conversion =
5614 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00005615 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
Larisse Voufo236bec22013-06-10 06:50:24 +00005616
5617 QualType ToType = Conversion->getConversionType().getNonReferenceType();
5618 if (!Converter.SuppressConversion) {
5619 if (SemaRef.isSFINAEContext())
5620 return true;
5621
5622 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5623 << From->getSourceRange();
5624 }
5625
5626 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5627 HadMultipleCandidates);
5628 if (Result.isInvalid())
5629 return true;
5630 // Record usage of conversion in an implicit cast.
5631 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005632 CK_UserDefinedConversion, Result.get(),
5633 nullptr, Result.get()->getValueKind());
Larisse Voufo236bec22013-06-10 06:50:24 +00005634 return false;
5635}
5636
5637static ExprResult finishContextualImplicitConversion(
5638 Sema &SemaRef, SourceLocation Loc, Expr *From,
5639 Sema::ContextualImplicitConverter &Converter) {
5640 if (!Converter.match(From->getType()) && !Converter.Suppress)
5641 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5642 << From->getSourceRange();
5643
5644 return SemaRef.DefaultLvalueConversion(From);
5645}
5646
5647static void
5648collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5649 UnresolvedSetImpl &ViableConversions,
5650 OverloadCandidateSet &CandidateSet) {
5651 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5652 DeclAccessPair FoundDecl = ViableConversions[I];
5653 NamedDecl *D = FoundDecl.getDecl();
5654 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5655 if (isa<UsingShadowDecl>(D))
5656 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5657
5658 CXXConversionDecl *Conv;
5659 FunctionTemplateDecl *ConvTemplate;
5660 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5661 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5662 else
5663 Conv = cast<CXXConversionDecl>(D);
5664
5665 if (ConvTemplate)
5666 SemaRef.AddTemplateConversionCandidate(
Douglas Gregor4b60a152013-11-07 22:34:54 +00005667 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5668 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005669 else
5670 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005671 ToType, CandidateSet,
5672 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005673 }
5674}
5675
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005676/// Attempt to convert the given expression to a type which is accepted
Richard Smithccc11812013-05-21 19:05:48 +00005677/// by the given converter.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005678///
Richard Smithccc11812013-05-21 19:05:48 +00005679/// This routine will attempt to convert an expression of class type to a
5680/// type accepted by the specified converter. In C++11 and before, the class
5681/// must have a single non-explicit conversion function converting to a matching
5682/// type. In C++1y, there can be multiple such conversion functions, but only
5683/// one target type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005684///
Douglas Gregor4799d032010-06-30 00:20:43 +00005685/// \param Loc The source location of the construct that requires the
5686/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005687///
James Dennett18348b62012-06-22 08:52:37 +00005688/// \param From The expression we're converting from.
Douglas Gregor4799d032010-06-30 00:20:43 +00005689///
Richard Smithccc11812013-05-21 19:05:48 +00005690/// \param Converter Used to control and diagnose the conversion process.
Richard Smith8dd34252012-02-04 07:07:42 +00005691///
Douglas Gregor4799d032010-06-30 00:20:43 +00005692/// \returns The expression, converted to an integral or enumeration type if
5693/// successful.
Richard Smithccc11812013-05-21 19:05:48 +00005694ExprResult Sema::PerformContextualImplicitConversion(
5695 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005696 // We can't perform any more checking for type-dependent expressions.
5697 if (From->isTypeDependent())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005698 return From;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005699
Eli Friedman1da70392012-01-26 00:26:18 +00005700 // Process placeholders immediately.
5701 if (From->hasPlaceholderType()) {
5702 ExprResult result = CheckPlaceholderExpr(From);
Larisse Voufo236bec22013-06-10 06:50:24 +00005703 if (result.isInvalid())
5704 return result;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005705 From = result.get();
Eli Friedman1da70392012-01-26 00:26:18 +00005706 }
5707
Richard Smithccc11812013-05-21 19:05:48 +00005708 // If the expression already has a matching type, we're golden.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005709 QualType T = From->getType();
Richard Smithccc11812013-05-21 19:05:48 +00005710 if (Converter.match(T))
Eli Friedman1da70392012-01-26 00:26:18 +00005711 return DefaultLvalueConversion(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005712
5713 // FIXME: Check for missing '()' if T is a function type?
5714
Richard Smithccc11812013-05-21 19:05:48 +00005715 // We can only perform contextual implicit conversions on objects of class
5716 // type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005717 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikiebbafb8a2012-03-11 07:00:24 +00005718 if (!RecordTy || !getLangOpts().CPlusPlus) {
Richard Smithccc11812013-05-21 19:05:48 +00005719 if (!Converter.Suppress)
5720 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005721 return From;
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005722 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005723
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005724 // We must have a complete class type.
Douglas Gregora6c5abb2012-05-04 16:48:41 +00005725 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
Richard Smithccc11812013-05-21 19:05:48 +00005726 ContextualImplicitConverter &Converter;
Douglas Gregore2b37442012-05-04 22:38:52 +00005727 Expr *From;
Richard Smithccc11812013-05-21 19:05:48 +00005728
5729 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
Richard Smithdb0ac552015-12-18 22:40:25 +00005730 : Converter(Converter), From(From) {}
Richard Smithccc11812013-05-21 19:05:48 +00005731
Craig Toppere14c0f82014-03-12 04:55:44 +00005732 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00005733 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005734 }
Richard Smithccc11812013-05-21 19:05:48 +00005735 } IncompleteDiagnoser(Converter, From);
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005736
Richard Smithdb0ac552015-12-18 22:40:25 +00005737 if (Converter.Suppress ? !isCompleteType(Loc, T)
5738 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005739 return From;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005740
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005741 // Look for a conversion to an integral or enumeration type.
Larisse Voufo236bec22013-06-10 06:50:24 +00005742 UnresolvedSet<4>
5743 ViableConversions; // These are *potentially* viable in C++1y.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005744 UnresolvedSet<4> ExplicitConversions;
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005745 const auto &Conversions =
Larisse Voufo236bec22013-06-10 06:50:24 +00005746 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005747
Larisse Voufo236bec22013-06-10 06:50:24 +00005748 bool HadMultipleCandidates =
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005749 (std::distance(Conversions.begin(), Conversions.end()) > 1);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005750
Larisse Voufo236bec22013-06-10 06:50:24 +00005751 // To check that there is only one target type, in C++1y:
5752 QualType ToType;
5753 bool HasUniqueTargetType = true;
5754
5755 // Collect explicit or viable (potentially in C++1y) conversions.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005756 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005757 NamedDecl *D = (*I)->getUnderlyingDecl();
5758 CXXConversionDecl *Conversion;
5759 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5760 if (ConvTemplate) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005761 if (getLangOpts().CPlusPlus14)
Larisse Voufo236bec22013-06-10 06:50:24 +00005762 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5763 else
5764 continue; // C++11 does not consider conversion operator templates(?).
5765 } else
5766 Conversion = cast<CXXConversionDecl>(D);
5767
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005768 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
Larisse Voufo236bec22013-06-10 06:50:24 +00005769 "Conversion operator templates are considered potentially "
5770 "viable in C++1y");
5771
5772 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5773 if (Converter.match(CurToType) || ConvTemplate) {
5774
5775 if (Conversion->isExplicit()) {
5776 // FIXME: For C++1y, do we need this restriction?
5777 // cf. diagnoseNoViableConversion()
5778 if (!ConvTemplate)
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005779 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
Larisse Voufo236bec22013-06-10 06:50:24 +00005780 } else {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005781 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005782 if (ToType.isNull())
5783 ToType = CurToType.getUnqualifiedType();
5784 else if (HasUniqueTargetType &&
5785 (CurToType.getUnqualifiedType() != ToType))
5786 HasUniqueTargetType = false;
5787 }
5788 ViableConversions.addDecl(I.getDecl(), I.getAccess());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005789 }
Richard Smith8dd34252012-02-04 07:07:42 +00005790 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005791 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005792
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005793 if (getLangOpts().CPlusPlus14) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005794 // C++1y [conv]p6:
5795 // ... An expression e of class type E appearing in such a context
5796 // is said to be contextually implicitly converted to a specified
5797 // type T and is well-formed if and only if e can be implicitly
5798 // converted to a type T that is determined as follows: E is searched
Larisse Voufo67170bd2013-06-10 08:25:58 +00005799 // for conversion functions whose return type is cv T or reference to
5800 // cv T such that T is allowed by the context. There shall be
Larisse Voufo236bec22013-06-10 06:50:24 +00005801 // exactly one such T.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005802
Larisse Voufo236bec22013-06-10 06:50:24 +00005803 // If no unique T is found:
5804 if (ToType.isNull()) {
5805 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5806 HadMultipleCandidates,
5807 ExplicitConversions))
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005808 return ExprError();
Larisse Voufo236bec22013-06-10 06:50:24 +00005809 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005810 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005811
Larisse Voufo236bec22013-06-10 06:50:24 +00005812 // If more than one unique Ts are found:
5813 if (!HasUniqueTargetType)
5814 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5815 ViableConversions);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005816
Larisse Voufo236bec22013-06-10 06:50:24 +00005817 // If one unique T is found:
5818 // First, build a candidate set from the previously recorded
5819 // potentially viable conversions.
Richard Smith100b24a2014-04-17 01:52:14 +00005820 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Larisse Voufo236bec22013-06-10 06:50:24 +00005821 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5822 CandidateSet);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005823
Larisse Voufo236bec22013-06-10 06:50:24 +00005824 // Then, perform overload resolution over the candidate set.
5825 OverloadCandidateSet::iterator Best;
5826 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5827 case OR_Success: {
5828 // Apply this conversion.
5829 DeclAccessPair Found =
5830 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5831 if (recordConversion(*this, Loc, From, Converter, T,
5832 HadMultipleCandidates, Found))
5833 return ExprError();
5834 break;
5835 }
5836 case OR_Ambiguous:
5837 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5838 ViableConversions);
5839 case OR_No_Viable_Function:
5840 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5841 HadMultipleCandidates,
5842 ExplicitConversions))
5843 return ExprError();
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00005844 LLVM_FALLTHROUGH;
Larisse Voufo236bec22013-06-10 06:50:24 +00005845 case OR_Deleted:
5846 // We'll complain below about a non-integral condition type.
5847 break;
5848 }
5849 } else {
5850 switch (ViableConversions.size()) {
5851 case 0: {
5852 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5853 HadMultipleCandidates,
5854 ExplicitConversions))
Douglas Gregor4799d032010-06-30 00:20:43 +00005855 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005856
Larisse Voufo236bec22013-06-10 06:50:24 +00005857 // We'll complain below about a non-integral condition type.
5858 break;
Douglas Gregor4799d032010-06-30 00:20:43 +00005859 }
Larisse Voufo236bec22013-06-10 06:50:24 +00005860 case 1: {
5861 // Apply this conversion.
5862 DeclAccessPair Found = ViableConversions[0];
5863 if (recordConversion(*this, Loc, From, Converter, T,
5864 HadMultipleCandidates, Found))
5865 return ExprError();
5866 break;
5867 }
5868 default:
5869 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5870 ViableConversions);
5871 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005872 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005873
Larisse Voufo236bec22013-06-10 06:50:24 +00005874 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005875}
5876
Richard Smith100b24a2014-04-17 01:52:14 +00005877/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5878/// an acceptable non-member overloaded operator for a call whose
5879/// arguments have types T1 (and, if non-empty, T2). This routine
5880/// implements the check in C++ [over.match.oper]p3b2 concerning
5881/// enumeration types.
5882static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5883 FunctionDecl *Fn,
5884 ArrayRef<Expr *> Args) {
5885 QualType T1 = Args[0]->getType();
5886 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5887
5888 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5889 return true;
5890
5891 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5892 return true;
5893
5894 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5895 if (Proto->getNumParams() < 1)
5896 return false;
5897
5898 if (T1->isEnumeralType()) {
5899 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5900 if (Context.hasSameUnqualifiedType(T1, ArgType))
5901 return true;
5902 }
5903
5904 if (Proto->getNumParams() < 2)
5905 return false;
5906
5907 if (!T2.isNull() && T2->isEnumeralType()) {
5908 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5909 if (Context.hasSameUnqualifiedType(T2, ArgType))
5910 return true;
5911 }
5912
5913 return false;
5914}
5915
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005916/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00005917/// candidate functions, using the given function call arguments. If
5918/// @p SuppressUserConversions, then don't allow user-defined
5919/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00005920///
James Dennett2a4d13c2012-06-15 07:13:21 +00005921/// \param PartialOverloading true if we are performing "partial" overloading
Douglas Gregorcabea402009-09-22 15:41:20 +00005922/// based on an incomplete set of function arguments. This feature is used by
5923/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00005924void
5925Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00005926 DeclAccessPair FoundDecl,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005927 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005928 OverloadCandidateSet &CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00005929 bool SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005930 bool PartialOverloading,
Richard Smith6eedfe72017-01-09 08:01:21 +00005931 bool AllowExplicit,
5932 ConversionSequenceList EarlyConversions) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005933 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00005934 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005935 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00005936 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005937 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00005938
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005939 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005940 if (!isa<CXXConstructorDecl>(Method)) {
5941 // If we get here, it's because we're calling a member function
5942 // that is named without a member access expression (e.g.,
5943 // "this->f") that was either written explicitly or created
5944 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00005945 // function, e.g., X::f(). We use an empty type for the implied
5946 // object argument (C++ [over.call.func]p3), and the acting context
5947 // is irrelevant.
Richard Smith6eedfe72017-01-09 08:01:21 +00005948 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
George Burgess IVce6284b2017-01-28 02:19:40 +00005949 Expr::Classification::makeSimpleLValue(), Args,
5950 CandidateSet, SuppressUserConversions,
5951 PartialOverloading, EarlyConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005952 return;
5953 }
5954 // We treat a constructor like a non-member function, since its object
5955 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005956 }
5957
Douglas Gregorff7028a2009-11-13 23:59:09 +00005958 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005959 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00005960
Richard Smith100b24a2014-04-17 01:52:14 +00005961 // C++ [over.match.oper]p3:
5962 // if no operand has a class type, only those non-member functions in the
5963 // lookup set that have a first parameter of type T1 or "reference to
5964 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5965 // is a right operand) a second parameter of type T2 or "reference to
5966 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
5967 // candidate functions.
5968 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5969 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5970 return;
5971
Richard Smith8b86f2d2013-11-04 01:48:18 +00005972 // C++11 [class.copy]p11: [DR1402]
5973 // A defaulted move constructor that is defined as deleted is ignored by
5974 // overload resolution.
5975 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5976 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5977 Constructor->isMoveConstructor())
5978 return;
5979
Douglas Gregor27381f32009-11-23 12:27:39 +00005980 // Overload resolution is always an unevaluated context.
Faisal Valid143a0c2017-04-01 21:30:49 +00005981 EnterExpressionEvaluationContext Unevaluated(
5982 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005983
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005984 // Add this candidate
Richard Smith6eedfe72017-01-09 08:01:21 +00005985 OverloadCandidate &Candidate =
5986 CandidateSet.addCandidate(Args.size(), EarlyConversions);
John McCalla0296f72010-03-19 07:35:19 +00005987 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005988 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005989 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005990 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005991 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005992 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005993
Erich Keane3efe0022018-07-20 14:13:28 +00005994 if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() &&
Erich Keane281d20b2018-01-08 21:34:17 +00005995 !Function->getAttr<TargetAttr>()->isDefaultVersion()) {
5996 Candidate.Viable = false;
5997 Candidate.FailureKind = ovl_non_default_multiversion_function;
5998 return;
5999 }
6000
John McCall578a1f82014-12-14 01:46:53 +00006001 if (Constructor) {
6002 // C++ [class.copy]p3:
6003 // A member function template is never instantiated to perform the copy
6004 // of a class object to an object of its class type.
6005 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
Richard Smith0f59cb32015-12-18 21:45:41 +00006006 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
John McCall578a1f82014-12-14 01:46:53 +00006007 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006008 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
Richard Smith0f59cb32015-12-18 21:45:41 +00006009 ClassType))) {
John McCall578a1f82014-12-14 01:46:53 +00006010 Candidate.Viable = false;
6011 Candidate.FailureKind = ovl_fail_illegal_constructor;
6012 return;
6013 }
Richard Smith836a3b42017-01-13 20:46:54 +00006014
6015 // C++ [over.match.funcs]p8: (proposed DR resolution)
6016 // A constructor inherited from class type C that has a first parameter
6017 // of type "reference to P" (including such a constructor instantiated
6018 // from a template) is excluded from the set of candidate functions when
6019 // constructing an object of type cv D if the argument list has exactly
6020 // one argument and D is reference-related to P and P is reference-related
6021 // to C.
6022 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
6023 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
6024 Constructor->getParamDecl(0)->getType()->isReferenceType()) {
6025 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
6026 QualType C = Context.getRecordType(Constructor->getParent());
6027 QualType D = Context.getRecordType(Shadow->getParent());
6028 SourceLocation Loc = Args.front()->getExprLoc();
6029 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
6030 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
6031 Candidate.Viable = false;
6032 Candidate.FailureKind = ovl_fail_inhctor_slice;
6033 return;
6034 }
6035 }
John McCall578a1f82014-12-14 01:46:53 +00006036 }
6037
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006038 unsigned NumParams = Proto->getNumParams();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006039
6040 // (C++ 13.3.2p2): A candidate function having fewer than m
6041 // parameters is viable only if it has an ellipsis in its parameter
6042 // list (8.3.5).
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006043 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
Douglas Gregor2a920012009-09-23 14:56:09 +00006044 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006045 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006046 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006047 return;
6048 }
6049
6050 // (C++ 13.3.2p2): A candidate function having more than m parameters
6051 // is viable only if the (m+1)st parameter has a default argument
6052 // (8.3.6). For the purposes of overload resolution, the
6053 // parameter list is truncated on the right, so that there are
6054 // exactly m parameters.
6055 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006056 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006057 // Not enough arguments.
6058 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006059 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006060 return;
6061 }
6062
Peter Collingbourne7277fe82011-10-02 23:49:40 +00006063 // (CUDA B.1): Check for invalid calls between targets.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006064 if (getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00006065 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
Eli Bendersky9a220fc2014-09-29 20:38:29 +00006066 // Skip the check for callers that are implicit members, because in this
6067 // case we may not yet know what the member's target is; the target is
6068 // inferred for the member automatically, based on the bases and fields of
6069 // the class.
Justin Lebarb0080032016-08-10 01:09:11 +00006070 if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00006071 Candidate.Viable = false;
6072 Candidate.FailureKind = ovl_fail_bad_target;
6073 return;
6074 }
6075
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006076 // Determine the implicit conversion sequences for each of the
6077 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006078 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Richard Smith6eedfe72017-01-09 08:01:21 +00006079 if (Candidate.Conversions[ArgIdx].isInitialized()) {
6080 // We already formed a conversion sequence for this parameter during
6081 // template argument deduction.
6082 } else if (ArgIdx < NumParams) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006083 // (C++ 13.3.2p3): for F to be a viable function, there shall
6084 // exist for each argument an implicit conversion sequence
6085 // (13.3.3.1) that converts that argument to the corresponding
6086 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00006087 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00006088 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006089 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006090 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00006091 /*InOverloadResolution=*/true,
6092 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006093 getLangOpts().ObjCAutoRefCount,
Douglas Gregor6073dca2012-02-24 23:56:31 +00006094 AllowExplicit);
John McCall0d1da222010-01-12 00:44:57 +00006095 if (Candidate.Conversions[ArgIdx].isBad()) {
6096 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006097 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006098 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00006099 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006100 } else {
6101 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6102 // argument for which there is no corresponding parameter is
6103 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006104 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006105 }
6106 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006107
6108 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
6109 Candidate.Viable = false;
6110 Candidate.FailureKind = ovl_fail_enable_if;
6111 Candidate.DeductionFailure.Data = FailedAttr;
6112 return;
6113 }
Yaxun Liu5b746652016-12-18 05:18:55 +00006114
6115 if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) {
6116 Candidate.Viable = false;
6117 Candidate.FailureKind = ovl_fail_ext_disabled;
6118 return;
6119 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006120}
6121
Manman Rend2a3cd72016-04-07 19:30:20 +00006122ObjCMethodDecl *
6123Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
6124 SmallVectorImpl<ObjCMethodDecl *> &Methods) {
6125 if (Methods.size() <= 1)
Fariborz Jahanian0ded4242014-08-13 21:24:14 +00006126 return nullptr;
Manman Rend2a3cd72016-04-07 19:30:20 +00006127
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006128 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6129 bool Match = true;
6130 ObjCMethodDecl *Method = Methods[b];
6131 unsigned NumNamedArgs = Sel.getNumArgs();
6132 // Method might have more arguments than selector indicates. This is due
6133 // to addition of c-style arguments in method.
6134 if (Method->param_size() > NumNamedArgs)
6135 NumNamedArgs = Method->param_size();
6136 if (Args.size() < NumNamedArgs)
6137 continue;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00006138
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006139 for (unsigned i = 0; i < NumNamedArgs; i++) {
6140 // We can't do any type-checking on a type-dependent argument.
6141 if (Args[i]->isTypeDependent()) {
6142 Match = false;
6143 break;
6144 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00006145
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006146 ParmVarDecl *param = Method->parameters()[i];
6147 Expr *argExpr = Args[i];
6148 assert(argExpr && "SelectBestMethod(): missing expression");
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00006149
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006150 // Strip the unbridged-cast placeholder expression off unless it's
6151 // a consumed argument.
6152 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
6153 !param->hasAttr<CFConsumedAttr>())
6154 argExpr = stripARCUnbridgedCast(argExpr);
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00006155
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006156 // If the parameter is __unknown_anytype, move on to the next method.
6157 if (param->getType() == Context.UnknownAnyTy) {
6158 Match = false;
6159 break;
6160 }
George Burgess IV45461812015-10-11 20:13:20 +00006161
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006162 ImplicitConversionSequence ConversionState
6163 = TryCopyInitialization(*this, argExpr, param->getType(),
6164 /*SuppressUserConversions*/false,
6165 /*InOverloadResolution=*/true,
6166 /*AllowObjCWritebackConversion=*/
6167 getLangOpts().ObjCAutoRefCount,
6168 /*AllowExplicit*/false);
George Burgess IV2099b542016-09-02 22:59:57 +00006169 // This function looks for a reasonably-exact match, so we consider
6170 // incompatible pointer conversions to be a failure here.
6171 if (ConversionState.isBad() ||
6172 (ConversionState.isStandard() &&
6173 ConversionState.Standard.Second ==
6174 ICK_Incompatible_Pointer_Conversion)) {
6175 Match = false;
6176 break;
6177 }
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006178 }
6179 // Promote additional arguments to variadic methods.
6180 if (Match && Method->isVariadic()) {
6181 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6182 if (Args[i]->isTypeDependent()) {
6183 Match = false;
6184 break;
6185 }
6186 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6187 nullptr);
6188 if (Arg.isInvalid()) {
6189 Match = false;
6190 break;
6191 }
6192 }
Fariborz Jahanian180d76b2014-08-27 16:38:47 +00006193 } else {
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006194 // Check for extra arguments to non-variadic methods.
6195 if (Args.size() != NumNamedArgs)
6196 Match = false;
Fariborz Jahanian180d76b2014-08-27 16:38:47 +00006197 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6198 // Special case when selectors have no argument. In this case, select
6199 // one with the most general result type of 'id'.
6200 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6201 QualType ReturnT = Methods[b]->getReturnType();
6202 if (ReturnT->isObjCIdType())
6203 return Methods[b];
6204 }
6205 }
6206 }
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006207
6208 if (Match)
6209 return Method;
6210 }
6211 return nullptr;
6212}
6213
George Burgess IV177399e2017-01-09 04:12:14 +00006214static bool
6215convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg,
6216 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap,
6217 bool MissingImplicitThis, Expr *&ConvertedThis,
6218 SmallVectorImpl<Expr *> &ConvertedArgs) {
6219 if (ThisArg) {
6220 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6221 assert(!isa<CXXConstructorDecl>(Method) &&
6222 "Shouldn't have `this` for ctors!");
6223 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
6224 ExprResult R = S.PerformObjectArgumentInitialization(
6225 ThisArg, /*Qualifier=*/nullptr, Method, Method);
6226 if (R.isInvalid())
6227 return false;
6228 ConvertedThis = R.get();
6229 } else {
6230 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
6231 (void)MD;
6232 assert((MissingImplicitThis || MD->isStatic() ||
6233 isa<CXXConstructorDecl>(MD)) &&
6234 "Expected `this` for non-ctor instance methods");
6235 }
6236 ConvertedThis = nullptr;
6237 }
Nick Lewyckye283c552015-08-25 22:33:16 +00006238
George Burgess IV458b3f32016-08-12 04:19:35 +00006239 // Ignore any variadic arguments. Converting them is pointless, since the
George Burgess IV177399e2017-01-09 04:12:14 +00006240 // user can't refer to them in the function condition.
George Burgess IV53b938d2016-08-12 04:12:31 +00006241 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6242
Nick Lewyckye283c552015-08-25 22:33:16 +00006243 // Convert the arguments.
George Burgess IV53b938d2016-08-12 04:12:31 +00006244 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
George Burgess IVe96abf72016-02-24 22:31:14 +00006245 ExprResult R;
George Burgess IV177399e2017-01-09 04:12:14 +00006246 R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6247 S.Context, Function->getParamDecl(I)),
George Burgess IVe96abf72016-02-24 22:31:14 +00006248 SourceLocation(), Args[I]);
George Burgess IVe96abf72016-02-24 22:31:14 +00006249
George Burgess IV177399e2017-01-09 04:12:14 +00006250 if (R.isInvalid())
6251 return false;
George Burgess IVe96abf72016-02-24 22:31:14 +00006252
George Burgess IVe96abf72016-02-24 22:31:14 +00006253 ConvertedArgs.push_back(R.get());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006254 }
6255
George Burgess IV177399e2017-01-09 04:12:14 +00006256 if (Trap.hasErrorOccurred())
6257 return false;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006258
Nick Lewyckye283c552015-08-25 22:33:16 +00006259 // Push default arguments if needed.
6260 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6261 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6262 ParmVarDecl *P = Function->getParamDecl(i);
Ilya Biryukov1a1dffd2018-03-09 14:43:29 +00006263 Expr *DefArg = P->hasUninstantiatedDefaultArg()
6264 ? P->getUninstantiatedDefaultArg()
6265 : P->getDefaultArg();
6266 // This can only happen in code completion, i.e. when PartialOverloading
6267 // is true.
6268 if (!DefArg)
6269 return false;
6270 ExprResult R =
6271 S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6272 S.Context, Function->getParamDecl(i)),
6273 SourceLocation(), DefArg);
George Burgess IV177399e2017-01-09 04:12:14 +00006274 if (R.isInvalid())
6275 return false;
Nick Lewyckye283c552015-08-25 22:33:16 +00006276 ConvertedArgs.push_back(R.get());
6277 }
6278
George Burgess IV177399e2017-01-09 04:12:14 +00006279 if (Trap.hasErrorOccurred())
6280 return false;
Nick Lewyckye283c552015-08-25 22:33:16 +00006281 }
George Burgess IV177399e2017-01-09 04:12:14 +00006282 return true;
6283}
6284
6285EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
6286 bool MissingImplicitThis) {
Michael Krusedc5ce722018-08-03 01:21:16 +00006287 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
6288 if (EnableIfAttrs.begin() == EnableIfAttrs.end())
George Burgess IV177399e2017-01-09 04:12:14 +00006289 return nullptr;
6290
6291 SFINAETrap Trap(*this);
6292 SmallVector<Expr *, 16> ConvertedArgs;
6293 // FIXME: We should look into making enable_if late-parsed.
6294 Expr *DiscardedThis;
6295 if (!convertArgsForAvailabilityChecks(
6296 *this, Function, /*ThisArg=*/nullptr, Args, Trap,
6297 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
Michael Krusedc5ce722018-08-03 01:21:16 +00006298 return *EnableIfAttrs.begin();
Nick Lewyckye283c552015-08-25 22:33:16 +00006299
George Burgess IV2a6150d2015-10-16 01:17:38 +00006300 for (auto *EIA : EnableIfAttrs) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006301 APValue Result;
George Burgess IVe8f10cc2016-05-11 01:38:27 +00006302 // FIXME: This doesn't consider value-dependent cases, because doing so is
6303 // very difficult. Ideally, we should handle them more gracefully.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006304 if (!EIA->getCond()->EvaluateWithSubstitution(
George Burgess IVe8f10cc2016-05-11 01:38:27 +00006305 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006306 return EIA;
George Burgess IVe8f10cc2016-05-11 01:38:27 +00006307
6308 if (!Result.isInt() || !Result.getInt().getBoolValue())
6309 return EIA;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006310 }
Craig Topperc3ec1492014-05-26 06:22:03 +00006311 return nullptr;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006312}
6313
George Burgess IV177399e2017-01-09 04:12:14 +00006314template <typename CheckFn>
Argyrios Kyrtzidisa7233bd2017-05-24 00:46:27 +00006315static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
George Burgess IVce6284b2017-01-28 02:19:40 +00006316 bool ArgDependent, SourceLocation Loc,
6317 CheckFn &&IsSuccessful) {
6318 SmallVector<const DiagnoseIfAttr *, 8> Attrs;
Argyrios Kyrtzidisa7233bd2017-05-24 00:46:27 +00006319 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
George Burgess IVce6284b2017-01-28 02:19:40 +00006320 if (ArgDependent == DIA->getArgDependent())
6321 Attrs.push_back(DIA);
6322 }
6323
6324 // Common case: No diagnose_if attributes, so we can quit early.
6325 if (Attrs.empty())
6326 return false;
6327
6328 auto WarningBegin = std::stable_partition(
6329 Attrs.begin(), Attrs.end(),
6330 [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
6331
George Burgess IV177399e2017-01-09 04:12:14 +00006332 // Note that diagnose_if attributes are late-parsed, so they appear in the
6333 // correct order (unlike enable_if attributes).
George Burgess IVce6284b2017-01-28 02:19:40 +00006334 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
6335 IsSuccessful);
6336 if (ErrAttr != WarningBegin) {
6337 const DiagnoseIfAttr *DIA = *ErrAttr;
6338 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
6339 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6340 << DIA->getParent() << DIA->getCond()->getSourceRange();
6341 return true;
6342 }
George Burgess IV177399e2017-01-09 04:12:14 +00006343
George Burgess IVce6284b2017-01-28 02:19:40 +00006344 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
6345 if (IsSuccessful(DIA)) {
6346 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
6347 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6348 << DIA->getParent() << DIA->getCond()->getSourceRange();
6349 }
6350
6351 return false;
George Burgess IV177399e2017-01-09 04:12:14 +00006352}
6353
George Burgess IVce6284b2017-01-28 02:19:40 +00006354bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
6355 const Expr *ThisArg,
6356 ArrayRef<const Expr *> Args,
6357 SourceLocation Loc) {
6358 return diagnoseDiagnoseIfAttrsWith(
6359 *this, Function, /*ArgDependent=*/true, Loc,
6360 [&](const DiagnoseIfAttr *DIA) {
6361 APValue Result;
6362 // It's sane to use the same Args for any redecl of this function, since
6363 // EvaluateWithSubstitution only cares about the position of each
6364 // argument in the arg list, not the ParmVarDecl* it maps to.
6365 if (!DIA->getCond()->EvaluateWithSubstitution(
Argyrios Kyrtzidisa7233bd2017-05-24 00:46:27 +00006366 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
George Burgess IVce6284b2017-01-28 02:19:40 +00006367 return false;
6368 return Result.isInt() && Result.getInt().getBoolValue();
6369 });
George Burgess IV177399e2017-01-09 04:12:14 +00006370}
6371
Argyrios Kyrtzidisa7233bd2017-05-24 00:46:27 +00006372bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
George Burgess IVce6284b2017-01-28 02:19:40 +00006373 SourceLocation Loc) {
6374 return diagnoseDiagnoseIfAttrsWith(
Argyrios Kyrtzidisa7233bd2017-05-24 00:46:27 +00006375 *this, ND, /*ArgDependent=*/false, Loc,
George Burgess IVce6284b2017-01-28 02:19:40 +00006376 [&](const DiagnoseIfAttr *DIA) {
6377 bool Result;
6378 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
6379 Result;
6380 });
George Burgess IV177399e2017-01-09 04:12:14 +00006381}
6382
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006383/// Add all of the function declarations in the given function set to
Nick Lewyckyed4265c2013-09-22 10:06:01 +00006384/// the overload candidate set.
John McCall4c4c1df2010-01-26 03:27:55 +00006385void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006386 ArrayRef<Expr *> Args,
Ivan Donchevskiif83cfda2018-06-21 08:34:50 +00006387 OverloadCandidateSet &CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006388 TemplateArgumentListInfo *ExplicitTemplateArgs,
Richard Smithbcc22fc2012-03-09 08:00:36 +00006389 bool SuppressUserConversions,
Benjamin Kramere3962ae2017-10-26 08:41:28 +00006390 bool PartialOverloading,
6391 bool FirstArgumentIsBase) {
John McCall4c4c1df2010-01-26 03:27:55 +00006392 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00006393 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
Ivan Donchevskiif83cfda2018-06-21 08:34:50 +00006394 ArrayRef<Expr *> FunctionArgs = Args;
6395
6396 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
6397 FunctionDecl *FD =
6398 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
6399
6400 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
6401 QualType ObjectType;
6402 Expr::Classification ObjectClassification;
6403 if (Args.size() > 0) {
Erik Verbruggenf1898cf2017-03-28 07:22:21 +00006404 if (Expr *E = Args[0]) {
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00006405 // Use the explicit base to restrict the lookup:
Erik Verbruggenf1898cf2017-03-28 07:22:21 +00006406 ObjectType = E->getType();
6407 ObjectClassification = E->Classify(Context);
Ivan Donchevskiif83cfda2018-06-21 08:34:50 +00006408 } // .. else there is an implicit base.
6409 FunctionArgs = Args.slice(1);
6410 }
6411 if (FunTmpl) {
George Burgess IV177399e2017-01-09 04:12:14 +00006412 AddMethodTemplateCandidate(
6413 FunTmpl, F.getPair(),
6414 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Erik Verbruggenf1898cf2017-03-28 07:22:21 +00006415 ExplicitTemplateArgs, ObjectType, ObjectClassification,
Ivan Donchevskiif83cfda2018-06-21 08:34:50 +00006416 FunctionArgs, CandidateSet, SuppressUserConversions,
Erik Verbruggenf1898cf2017-03-28 07:22:21 +00006417 PartialOverloading);
6418 } else {
Ivan Donchevskiif83cfda2018-06-21 08:34:50 +00006419 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
6420 cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
6421 ObjectClassification, FunctionArgs, CandidateSet,
6422 SuppressUserConversions, PartialOverloading);
6423 }
6424 } else {
6425 // This branch handles both standalone functions and static methods.
6426
6427 // Slice the first argument (which is the base) when we access
6428 // static method as non-static.
6429 if (Args.size() > 0 &&
6430 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
6431 !isa<CXXConstructorDecl>(FD)))) {
6432 assert(cast<CXXMethodDecl>(FD)->isStatic());
6433 FunctionArgs = Args.slice(1);
6434 }
6435 if (FunTmpl) {
6436 AddTemplateOverloadCandidate(
6437 FunTmpl, F.getPair(), ExplicitTemplateArgs, FunctionArgs,
6438 CandidateSet, SuppressUserConversions, PartialOverloading);
6439 } else {
6440 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
6441 SuppressUserConversions, PartialOverloading);
Erik Verbruggenf1898cf2017-03-28 07:22:21 +00006442 }
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006443 }
Douglas Gregor15448f82009-06-27 21:05:07 +00006444 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006445}
6446
John McCallf0f1cf02009-11-17 07:50:12 +00006447/// AddMethodCandidate - Adds a named decl (which is some kind of
6448/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00006449void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006450 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006451 Expr::Classification ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00006452 ArrayRef<Expr *> Args,
John McCallf0f1cf02009-11-17 07:50:12 +00006453 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006454 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00006455 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00006456 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00006457
6458 if (isa<UsingShadowDecl>(Decl))
6459 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006460
John McCallf0f1cf02009-11-17 07:50:12 +00006461 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6462 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6463 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00006464 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
George Burgess IVce6284b2017-01-28 02:19:40 +00006465 /*ExplicitArgs*/ nullptr, ObjectType,
6466 ObjectClassification, Args, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006467 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00006468 } else {
John McCalla0296f72010-03-19 07:35:19 +00006469 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
George Burgess IVce6284b2017-01-28 02:19:40 +00006470 ObjectType, ObjectClassification, Args, CandidateSet,
6471 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00006472 }
6473}
6474
Douglas Gregor436424c2008-11-18 23:14:02 +00006475/// AddMethodCandidate - Adds the given C++ member function to the set
6476/// of candidate functions, using the given function call arguments
6477/// and the object argument (@c Object). For example, in a call
6478/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6479/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6480/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00006481/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00006482void
John McCalla0296f72010-03-19 07:35:19 +00006483Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00006484 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006485 Expr::Classification ObjectClassification,
George Burgess IVce6284b2017-01-28 02:19:40 +00006486 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006487 OverloadCandidateSet &CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006488 bool SuppressUserConversions,
Richard Smith6eedfe72017-01-09 08:01:21 +00006489 bool PartialOverloading,
6490 ConversionSequenceList EarlyConversions) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006491 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00006492 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00006493 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00006494 assert(!isa<CXXConstructorDecl>(Method) &&
6495 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00006496
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006497 if (!CandidateSet.isNewCandidate(Method))
6498 return;
6499
Richard Smith8b86f2d2013-11-04 01:48:18 +00006500 // C++11 [class.copy]p23: [DR1402]
6501 // A defaulted move assignment operator that is defined as deleted is
6502 // ignored by overload resolution.
6503 if (Method->isDefaulted() && Method->isDeleted() &&
6504 Method->isMoveAssignmentOperator())
6505 return;
6506
Douglas Gregor27381f32009-11-23 12:27:39 +00006507 // Overload resolution is always an unevaluated context.
Faisal Valid143a0c2017-04-01 21:30:49 +00006508 EnterExpressionEvaluationContext Unevaluated(
6509 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006510
Douglas Gregor436424c2008-11-18 23:14:02 +00006511 // Add this candidate
Richard Smith6eedfe72017-01-09 08:01:21 +00006512 OverloadCandidate &Candidate =
6513 CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
John McCalla0296f72010-03-19 07:35:19 +00006514 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00006515 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006516 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006517 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006518 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor436424c2008-11-18 23:14:02 +00006519
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006520 unsigned NumParams = Proto->getNumParams();
Douglas Gregor436424c2008-11-18 23:14:02 +00006521
6522 // (C++ 13.3.2p2): A candidate function having fewer than m
6523 // parameters is viable only if it has an ellipsis in its parameter
6524 // list (8.3.5).
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006525 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6526 !Proto->isVariadic()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006527 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006528 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00006529 return;
6530 }
6531
6532 // (C++ 13.3.2p2): A candidate function having more than m parameters
6533 // is viable only if the (m+1)st parameter has a default argument
6534 // (8.3.6). For the purposes of overload resolution, the
6535 // parameter list is truncated on the right, so that there are
6536 // exactly m parameters.
6537 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006538 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006539 // Not enough arguments.
6540 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006541 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00006542 return;
6543 }
6544
6545 Candidate.Viable = true;
Douglas Gregor436424c2008-11-18 23:14:02 +00006546
John McCall6e9f8f62009-12-03 04:06:58 +00006547 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006548 // The implicit object argument is ignored.
6549 Candidate.IgnoreObjectArgument = true;
6550 else {
6551 // Determine the implicit conversion sequence for the object
6552 // parameter.
Richard Smith0f59cb32015-12-18 21:45:41 +00006553 Candidate.Conversions[0] = TryObjectArgumentInitialization(
6554 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6555 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00006556 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006557 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006558 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006559 return;
6560 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006561 }
6562
Eli Bendersky291a57e2014-09-25 23:59:08 +00006563 // (CUDA B.1): Check for invalid calls between targets.
6564 if (getLangOpts().CUDA)
6565 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
Justin Lebarb0080032016-08-10 01:09:11 +00006566 if (!IsAllowedCUDACall(Caller, Method)) {
Eli Bendersky291a57e2014-09-25 23:59:08 +00006567 Candidate.Viable = false;
6568 Candidate.FailureKind = ovl_fail_bad_target;
6569 return;
6570 }
6571
Douglas Gregor436424c2008-11-18 23:14:02 +00006572 // Determine the implicit conversion sequences for each of the
6573 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006574 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Richard Smith6eedfe72017-01-09 08:01:21 +00006575 if (Candidate.Conversions[ArgIdx + 1].isInitialized()) {
6576 // We already formed a conversion sequence for this parameter during
6577 // template argument deduction.
6578 } else if (ArgIdx < NumParams) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006579 // (C++ 13.3.2p3): for F to be a viable function, there shall
6580 // exist for each argument an implicit conversion sequence
6581 // (13.3.3.1) that converts that argument to the corresponding
6582 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00006583 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00006584 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006585 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006586 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00006587 /*InOverloadResolution=*/true,
6588 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006589 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00006590 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006591 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006592 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006593 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00006594 }
6595 } else {
6596 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6597 // argument for which there is no corresponding parameter is
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006598 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006599 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00006600 }
6601 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006602
6603 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6604 Candidate.Viable = false;
6605 Candidate.FailureKind = ovl_fail_enable_if;
6606 Candidate.DeductionFailure.Data = FailedAttr;
6607 return;
6608 }
Erich Keane281d20b2018-01-08 21:34:17 +00006609
Erich Keane3efe0022018-07-20 14:13:28 +00006610 if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() &&
Erich Keane281d20b2018-01-08 21:34:17 +00006611 !Method->getAttr<TargetAttr>()->isDefaultVersion()) {
6612 Candidate.Viable = false;
6613 Candidate.FailureKind = ovl_non_default_multiversion_function;
6614 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006615}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006616
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006617/// Add a C++ member function template as a candidate to the candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00006618/// set, using template argument deduction to produce an appropriate member
6619/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00006620void
Douglas Gregor97628d62009-08-21 00:16:32 +00006621Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00006622 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006623 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006624 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006625 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006626 Expr::Classification ObjectClassification,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006627 ArrayRef<Expr *> Args,
Douglas Gregor97628d62009-08-21 00:16:32 +00006628 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006629 bool SuppressUserConversions,
6630 bool PartialOverloading) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006631 if (!CandidateSet.isNewCandidate(MethodTmpl))
6632 return;
6633
Douglas Gregor97628d62009-08-21 00:16:32 +00006634 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00006635 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00006636 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00006637 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00006638 // candidate functions in the usual way.113) A given name can refer to one
6639 // or more function templates and also to a set of overloaded non-template
6640 // functions. In such a case, the candidate functions generated from each
6641 // function template are combined with the set of non-template candidate
6642 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00006643 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006644 FunctionDecl *Specialization = nullptr;
Richard Smith6eedfe72017-01-09 08:01:21 +00006645 ConversionSequenceList Conversions;
6646 if (TemplateDeductionResult Result = DeduceTemplateArguments(
6647 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
6648 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6649 return CheckNonDependentConversions(
6650 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
6651 SuppressUserConversions, ActingContext, ObjectType,
6652 ObjectClassification);
6653 })) {
6654 OverloadCandidate &Candidate =
6655 CandidateSet.addCandidate(Conversions.size(), Conversions);
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006656 Candidate.FoundDecl = FoundDecl;
6657 Candidate.Function = MethodTmpl->getTemplatedDecl();
6658 Candidate.Viable = false;
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006659 Candidate.IsSurrogate = false;
Richard Smith9d05e152017-01-10 20:52:50 +00006660 Candidate.IgnoreObjectArgument =
6661 cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
6662 ObjectType.isNull();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006663 Candidate.ExplicitCallArguments = Args.size();
Richard Smith6eedfe72017-01-09 08:01:21 +00006664 if (Result == TDK_NonDependentConversionFailure)
6665 Candidate.FailureKind = ovl_fail_bad_conversion;
6666 else {
6667 Candidate.FailureKind = ovl_fail_bad_deduction;
6668 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6669 Info);
6670 }
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006671 return;
6672 }
Mike Stump11289f42009-09-09 15:08:12 +00006673
Douglas Gregor97628d62009-08-21 00:16:32 +00006674 // Add the function template specialization produced by template argument
6675 // deduction as a candidate.
6676 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00006677 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00006678 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00006679 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
George Burgess IVce6284b2017-01-28 02:19:40 +00006680 ActingContext, ObjectType, ObjectClassification, Args,
6681 CandidateSet, SuppressUserConversions, PartialOverloading,
6682 Conversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00006683}
6684
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006685/// Add a C++ function template specialization as a candidate
Douglas Gregor05155d82009-08-21 23:19:43 +00006686/// in the candidate set, using template argument deduction to produce
6687/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00006688void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006689Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00006690 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006691 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006692 ArrayRef<Expr *> Args,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006693 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006694 bool SuppressUserConversions,
6695 bool PartialOverloading) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006696 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6697 return;
6698
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006699 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00006700 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006701 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00006702 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006703 // candidate functions in the usual way.113) A given name can refer to one
6704 // or more function templates and also to a set of overloaded non-template
6705 // functions. In such a case, the candidate functions generated from each
6706 // function template are combined with the set of non-template candidate
6707 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00006708 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006709 FunctionDecl *Specialization = nullptr;
Richard Smith6eedfe72017-01-09 08:01:21 +00006710 ConversionSequenceList Conversions;
6711 if (TemplateDeductionResult Result = DeduceTemplateArguments(
6712 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
6713 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6714 return CheckNonDependentConversions(FunctionTemplate, ParamTypes,
6715 Args, CandidateSet, Conversions,
6716 SuppressUserConversions);
6717 })) {
6718 OverloadCandidate &Candidate =
6719 CandidateSet.addCandidate(Conversions.size(), Conversions);
John McCalla0296f72010-03-19 07:35:19 +00006720 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00006721 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6722 Candidate.Viable = false;
6723 Candidate.IsSurrogate = false;
Richard Smith9d05e152017-01-10 20:52:50 +00006724 // Ignore the object argument if there is one, since we don't have an object
6725 // type.
6726 Candidate.IgnoreObjectArgument =
6727 isa<CXXMethodDecl>(Candidate.Function) &&
6728 !isa<CXXConstructorDecl>(Candidate.Function);
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006729 Candidate.ExplicitCallArguments = Args.size();
Richard Smith6eedfe72017-01-09 08:01:21 +00006730 if (Result == TDK_NonDependentConversionFailure)
6731 Candidate.FailureKind = ovl_fail_bad_conversion;
6732 else {
6733 Candidate.FailureKind = ovl_fail_bad_deduction;
6734 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6735 Info);
6736 }
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006737 return;
6738 }
Mike Stump11289f42009-09-09 15:08:12 +00006739
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006740 // Add the function template specialization produced by template argument
6741 // deduction as a candidate.
6742 assert(Specialization && "Missing function template specialization?");
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006743 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Richard Smith6eedfe72017-01-09 08:01:21 +00006744 SuppressUserConversions, PartialOverloading,
6745 /*AllowExplicit*/false, Conversions);
6746}
6747
6748/// Check that implicit conversion sequences can be formed for each argument
6749/// whose corresponding parameter has a non-dependent type, per DR1391's
6750/// [temp.deduct.call]p10.
6751bool Sema::CheckNonDependentConversions(
6752 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
6753 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
6754 ConversionSequenceList &Conversions, bool SuppressUserConversions,
6755 CXXRecordDecl *ActingContext, QualType ObjectType,
6756 Expr::Classification ObjectClassification) {
6757 // FIXME: The cases in which we allow explicit conversions for constructor
6758 // arguments never consider calling a constructor template. It's not clear
6759 // that is correct.
6760 const bool AllowExplicit = false;
6761
6762 auto *FD = FunctionTemplate->getTemplatedDecl();
6763 auto *Method = dyn_cast<CXXMethodDecl>(FD);
6764 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
6765 unsigned ThisConversions = HasThisConversion ? 1 : 0;
6766
6767 Conversions =
6768 CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
6769
6770 // Overload resolution is always an unevaluated context.
Faisal Valid143a0c2017-04-01 21:30:49 +00006771 EnterExpressionEvaluationContext Unevaluated(
6772 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Richard Smith6eedfe72017-01-09 08:01:21 +00006773
6774 // For a method call, check the 'this' conversion here too. DR1391 doesn't
6775 // require that, but this check should never result in a hard error, and
6776 // overload resolution is permitted to sidestep instantiations.
6777 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
6778 !ObjectType.isNull()) {
6779 Conversions[0] = TryObjectArgumentInitialization(
6780 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6781 Method, ActingContext);
6782 if (Conversions[0].isBad())
6783 return true;
6784 }
6785
6786 for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N;
6787 ++I) {
6788 QualType ParamType = ParamTypes[I];
6789 if (!ParamType->isDependentType()) {
6790 Conversions[ThisConversions + I]
6791 = TryCopyInitialization(*this, Args[I], ParamType,
6792 SuppressUserConversions,
6793 /*InOverloadResolution=*/true,
6794 /*AllowObjCWritebackConversion=*/
6795 getLangOpts().ObjCAutoRefCount,
6796 AllowExplicit);
6797 if (Conversions[ThisConversions + I].isBad())
6798 return true;
6799 }
6800 }
6801
6802 return false;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006803}
Mike Stump11289f42009-09-09 15:08:12 +00006804
Douglas Gregor4b60a152013-11-07 22:34:54 +00006805/// Determine whether this is an allowable conversion from the result
6806/// of an explicit conversion operator to the expected type, per C++
6807/// [over.match.conv]p1 and [over.match.ref]p1.
6808///
6809/// \param ConvType The return type of the conversion function.
6810///
6811/// \param ToType The type we are converting to.
6812///
6813/// \param AllowObjCPointerConversion Allow a conversion from one
6814/// Objective-C pointer to another.
6815///
6816/// \returns true if the conversion is allowable, false otherwise.
6817static bool isAllowableExplicitConversion(Sema &S,
6818 QualType ConvType, QualType ToType,
6819 bool AllowObjCPointerConversion) {
6820 QualType ToNonRefType = ToType.getNonReferenceType();
6821
6822 // Easy case: the types are the same.
6823 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6824 return true;
6825
6826 // Allow qualification conversions.
6827 bool ObjCLifetimeConversion;
6828 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6829 ObjCLifetimeConversion))
6830 return true;
6831
6832 // If we're not allowed to consider Objective-C pointer conversions,
6833 // we're done.
6834 if (!AllowObjCPointerConversion)
6835 return false;
6836
6837 // Is this an Objective-C pointer conversion?
6838 bool IncompatibleObjC = false;
6839 QualType ConvertedType;
6840 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6841 IncompatibleObjC);
6842}
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00006843
Douglas Gregora1f013e2008-11-07 22:36:19 +00006844/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00006845/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00006846/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00006847/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00006848/// (which may or may not be the same type as the type that the
6849/// conversion function produces).
6850void
6851Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006852 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006853 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00006854 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006855 OverloadCandidateSet& CandidateSet,
Richard Smith67ef14f2017-09-26 18:37:55 +00006856 bool AllowObjCConversionOnExplicit,
6857 bool AllowResultConversion) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006858 assert(!Conversion->getDescribedFunctionTemplate() &&
6859 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00006860 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006861 if (!CandidateSet.isNewCandidate(Conversion))
6862 return;
6863
Richard Smith2a7d4812013-05-04 07:00:32 +00006864 // If the conversion function has an undeduced return type, trigger its
6865 // deduction now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006866 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00006867 if (DeduceReturnType(Conversion, From->getExprLoc()))
6868 return;
6869 ConvType = Conversion->getConversionType().getNonReferenceType();
6870 }
6871
Richard Smith67ef14f2017-09-26 18:37:55 +00006872 // If we don't allow any conversion of the result type, ignore conversion
6873 // functions that don't convert to exactly (possibly cv-qualified) T.
6874 if (!AllowResultConversion &&
6875 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
6876 return;
6877
Richard Smith089c3162013-09-21 21:55:46 +00006878 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6879 // operator is only a candidate if its return type is the target type or
6880 // can be converted to the target type with a qualification conversion.
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00006881 if (Conversion->isExplicit() &&
6882 !isAllowableExplicitConversion(*this, ConvType, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006883 AllowObjCConversionOnExplicit))
Richard Smith089c3162013-09-21 21:55:46 +00006884 return;
6885
Douglas Gregor27381f32009-11-23 12:27:39 +00006886 // Overload resolution is always an unevaluated context.
Faisal Valid143a0c2017-04-01 21:30:49 +00006887 EnterExpressionEvaluationContext Unevaluated(
6888 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006889
Douglas Gregora1f013e2008-11-07 22:36:19 +00006890 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006891 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCalla0296f72010-03-19 07:35:19 +00006892 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006893 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006894 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006895 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006896 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00006897 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00006898 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00006899 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006900 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006901
Douglas Gregor6affc782010-08-19 15:37:02 +00006902 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006903 // For conversion functions, the function is considered to be a member of
6904 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00006905 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006906 //
6907 // Determine the implicit conversion sequence for the implicit
6908 // object parameter.
6909 QualType ImplicitParamType = From->getType();
6910 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6911 ImplicitParamType = FromPtrType->getPointeeType();
6912 CXXRecordDecl *ConversionContext
6913 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006914
Richard Smith0f59cb32015-12-18 21:45:41 +00006915 Candidate.Conversions[0] = TryObjectArgumentInitialization(
6916 *this, CandidateSet.getLocation(), From->getType(),
6917 From->Classify(Context), Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006918
John McCall0d1da222010-01-12 00:44:57 +00006919 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006920 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006921 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006922 return;
6923 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006924
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006925 // We won't go through a user-defined type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006926 // derived to base as such conversions are given Conversion Rank. They only
6927 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6928 QualType FromCanon
6929 = Context.getCanonicalType(From->getType().getUnqualifiedType());
6930 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
Richard Smith0f59cb32015-12-18 21:45:41 +00006931 if (FromCanon == ToCanon ||
6932 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006933 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006934 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006935 return;
6936 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006937
Douglas Gregora1f013e2008-11-07 22:36:19 +00006938 // To determine what the conversion from the result of calling the
6939 // conversion function to the type we're eventually trying to
6940 // convert to (ToType), we need to synthesize a call to the
6941 // conversion function and attempt copy initialization from it. This
6942 // makes sure that we get the right semantics with respect to
6943 // lvalues/rvalues and the type. Fortunately, we can allocate this
6944 // call on the stack and we don't need its arguments to be
6945 // well-formed.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006946 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(), VK_LValue,
6947 From->getBeginLoc());
John McCallcf142162010-08-07 06:22:56 +00006948 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6949 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00006950 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00006951 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00006952
Richard Smith48d24642011-07-13 22:53:21 +00006953 QualType ConversionType = Conversion->getConversionType();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006954 if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
Douglas Gregor72ebdab2010-11-13 19:36:57 +00006955 Candidate.Viable = false;
6956 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6957 return;
6958 }
6959
Richard Smith48d24642011-07-13 22:53:21 +00006960 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCall7decc9e2010-11-18 06:31:45 +00006961
Mike Stump11289f42009-09-09 15:08:12 +00006962 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00006963 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6964 // allocator).
Richard Smith48d24642011-07-13 22:53:21 +00006965 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00006966 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006967 From->getBeginLoc());
Mike Stump11289f42009-09-09 15:08:12 +00006968 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006969 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00006970 /*SuppressUserConversions=*/true,
John McCall31168b02011-06-15 23:02:42 +00006971 /*InOverloadResolution=*/false,
6972 /*AllowObjCWritebackConversion=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00006973
John McCall0d1da222010-01-12 00:44:57 +00006974 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006975 case ImplicitConversionSequence::StandardConversion:
6976 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006977
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006978 // C++ [over.ics.user]p3:
6979 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006980 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006981 // shall have exact match rank.
6982 if (Conversion->getPrimaryTemplate() &&
6983 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6984 Candidate.Viable = false;
6985 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006986 return;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006987 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006988
Douglas Gregorcba72b12011-01-21 05:18:22 +00006989 // C++0x [dcl.init.ref]p5:
6990 // In the second case, if the reference is an rvalue reference and
6991 // the second standard conversion sequence of the user-defined
6992 // conversion sequence includes an lvalue-to-rvalue conversion, the
6993 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006994 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00006995 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6996 Candidate.Viable = false;
6997 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006998 return;
Douglas Gregorcba72b12011-01-21 05:18:22 +00006999 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00007000 break;
7001
7002 case ImplicitConversionSequence::BadConversion:
7003 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00007004 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007005 return;
Douglas Gregora1f013e2008-11-07 22:36:19 +00007006
7007 default:
David Blaikie83d382b2011-09-23 05:06:16 +00007008 llvm_unreachable(
Douglas Gregora1f013e2008-11-07 22:36:19 +00007009 "Can only end up with a standard conversion sequence or failure");
7010 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007011
Craig Topper5fc8fc22014-08-27 06:28:36 +00007012 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007013 Candidate.Viable = false;
7014 Candidate.FailureKind = ovl_fail_enable_if;
7015 Candidate.DeductionFailure.Data = FailedAttr;
7016 return;
7017 }
Erich Keane281d20b2018-01-08 21:34:17 +00007018
Erich Keane3efe0022018-07-20 14:13:28 +00007019 if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() &&
Erich Keane281d20b2018-01-08 21:34:17 +00007020 !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) {
7021 Candidate.Viable = false;
7022 Candidate.FailureKind = ovl_non_default_multiversion_function;
7023 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00007024}
7025
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007026/// Adds a conversion function template specialization
Douglas Gregor05155d82009-08-21 23:19:43 +00007027/// candidate to the overload set, using template argument deduction
7028/// to deduce the template arguments of the conversion function
7029/// template from the type that we are converting to (C++
7030/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00007031void
Douglas Gregor05155d82009-08-21 23:19:43 +00007032Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00007033 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00007034 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00007035 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00007036 OverloadCandidateSet &CandidateSet,
Richard Smith67ef14f2017-09-26 18:37:55 +00007037 bool AllowObjCConversionOnExplicit,
7038 bool AllowResultConversion) {
Douglas Gregor05155d82009-08-21 23:19:43 +00007039 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
7040 "Only conversion function templates permitted here");
7041
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00007042 if (!CandidateSet.isNewCandidate(FunctionTemplate))
7043 return;
7044
Craig Toppere6706e42012-09-19 02:26:47 +00007045 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00007046 CXXConversionDecl *Specialization = nullptr;
Douglas Gregor05155d82009-08-21 23:19:43 +00007047 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00007048 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00007049 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00007050 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00007051 Candidate.FoundDecl = FoundDecl;
7052 Candidate.Function = FunctionTemplate->getTemplatedDecl();
7053 Candidate.Viable = false;
7054 Candidate.FailureKind = ovl_fail_bad_deduction;
7055 Candidate.IsSurrogate = false;
7056 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00007057 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007058 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00007059 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00007060 return;
7061 }
Mike Stump11289f42009-09-09 15:08:12 +00007062
Douglas Gregor05155d82009-08-21 23:19:43 +00007063 // Add the conversion function template specialization produced by
7064 // template argument deduction as a candidate.
7065 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00007066 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
Richard Smith67ef14f2017-09-26 18:37:55 +00007067 CandidateSet, AllowObjCConversionOnExplicit,
7068 AllowResultConversion);
Douglas Gregor05155d82009-08-21 23:19:43 +00007069}
7070
Douglas Gregorab7897a2008-11-19 22:57:39 +00007071/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
7072/// converts the given @c Object to a function pointer via the
7073/// conversion function @c Conversion, and then attempts to call it
7074/// with the given arguments (C++ [over.call.object]p2-4). Proto is
7075/// the type of function that we'll eventually be calling.
7076void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00007077 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00007078 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007079 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00007080 Expr *Object,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007081 ArrayRef<Expr *> Args,
Douglas Gregorab7897a2008-11-19 22:57:39 +00007082 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00007083 if (!CandidateSet.isNewCandidate(Conversion))
7084 return;
7085
Douglas Gregor27381f32009-11-23 12:27:39 +00007086 // Overload resolution is always an unevaluated context.
Faisal Valid143a0c2017-04-01 21:30:49 +00007087 EnterExpressionEvaluationContext Unevaluated(
7088 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00007089
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00007090 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00007091 Candidate.FoundDecl = FoundDecl;
Craig Topperc3ec1492014-05-26 06:22:03 +00007092 Candidate.Function = nullptr;
Douglas Gregorab7897a2008-11-19 22:57:39 +00007093 Candidate.Surrogate = Conversion;
7094 Candidate.Viable = true;
7095 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007096 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00007097 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregorab7897a2008-11-19 22:57:39 +00007098
7099 // Determine the implicit conversion sequence for the implicit
7100 // object parameter.
Richard Smith0f59cb32015-12-18 21:45:41 +00007101 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
7102 *this, CandidateSet.getLocation(), Object->getType(),
7103 Object->Classify(Context), Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00007104 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00007105 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00007106 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00007107 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00007108 return;
7109 }
7110
7111 // The first conversion is actually a user-defined conversion whose
7112 // first conversion is ObjectInit's standard conversion (which is
7113 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00007114 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00007115 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00007116 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00007117 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00007118 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00007119 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump11289f42009-09-09 15:08:12 +00007120 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00007121 = Candidate.Conversions[0].UserDefined.Before;
7122 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
7123
Mike Stump11289f42009-09-09 15:08:12 +00007124 // Find the
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00007125 unsigned NumParams = Proto->getNumParams();
Douglas Gregorab7897a2008-11-19 22:57:39 +00007126
7127 // (C++ 13.3.2p2): A candidate function having fewer than m
7128 // parameters is viable only if it has an ellipsis in its parameter
7129 // list (8.3.5).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00007130 if (Args.size() > NumParams && !Proto->isVariadic()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00007131 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00007132 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00007133 return;
7134 }
7135
7136 // Function types don't have any default arguments, so just check if
7137 // we have enough arguments.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00007138 if (Args.size() < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00007139 // Not enough arguments.
7140 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00007141 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00007142 return;
7143 }
7144
7145 // Determine the implicit conversion sequences for each of the
7146 // arguments.
Richard Smithe54c3072013-05-05 15:51:06 +00007147 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00007148 if (ArgIdx < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00007149 // (C++ 13.3.2p3): for F to be a viable function, there shall
7150 // exist for each argument an implicit conversion sequence
7151 // (13.3.3.1) that converts that argument to the corresponding
7152 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00007153 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00007154 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00007155 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00007156 /*SuppressUserConversions=*/false,
John McCall31168b02011-06-15 23:02:42 +00007157 /*InOverloadResolution=*/false,
7158 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00007159 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00007160 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00007161 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00007162 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007163 return;
Douglas Gregorab7897a2008-11-19 22:57:39 +00007164 }
7165 } else {
7166 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7167 // argument for which there is no corresponding parameter is
7168 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00007169 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00007170 }
7171 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007172
Craig Topper5fc8fc22014-08-27 06:28:36 +00007173 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007174 Candidate.Viable = false;
7175 Candidate.FailureKind = ovl_fail_enable_if;
7176 Candidate.DeductionFailure.Data = FailedAttr;
7177 return;
7178 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00007179}
7180
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007181/// Add overload candidates for overloaded operators that are
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007182/// member functions.
7183///
7184/// Add the overloaded operator candidates that are member functions
7185/// for the operator Op that was used in an operator expression such
7186/// as "x Op y". , Args/NumArgs provides the operator arguments, and
7187/// CandidateSet will store the added overload candidates. (C++
7188/// [over.match.oper]).
7189void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
7190 SourceLocation OpLoc,
Richard Smithe54c3072013-05-05 15:51:06 +00007191 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007192 OverloadCandidateSet& CandidateSet,
7193 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00007194 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7195
7196 // C++ [over.match.oper]p3:
7197 // For a unary operator @ with an operand of a type whose
7198 // cv-unqualified version is T1, and for a binary operator @ with
7199 // a left operand of a type whose cv-unqualified version is T1 and
7200 // a right operand of a type whose cv-unqualified version is T2,
7201 // three sets of candidate functions, designated member
7202 // candidates, non-member candidates and built-in candidates, are
7203 // constructed as follows:
7204 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00007205
Richard Smith0feaf0c2013-04-20 12:41:22 +00007206 // -- If T1 is a complete class type or a class currently being
7207 // defined, the set of member candidates is the result of the
7208 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
7209 // the set of member candidates is empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007210 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Richard Smith0feaf0c2013-04-20 12:41:22 +00007211 // Complete the type if it can be completed.
Richard Smithdb0ac552015-12-18 22:40:25 +00007212 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
Richard Smith82b8d4e2015-12-18 22:19:11 +00007213 return;
Richard Smith0feaf0c2013-04-20 12:41:22 +00007214 // If the type is neither complete nor being defined, bail out now.
7215 if (!T1Rec->getDecl()->getDefinition())
Douglas Gregor6a1f9652009-08-27 23:35:55 +00007216 return;
Mike Stump11289f42009-09-09 15:08:12 +00007217
John McCall27b18f82009-11-17 02:14:36 +00007218 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
7219 LookupQualifiedName(Operators, T1Rec->getDecl());
7220 Operators.suppressDiagnostics();
7221
Mike Stump11289f42009-09-09 15:08:12 +00007222 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00007223 OperEnd = Operators.end();
7224 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00007225 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00007226 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
George Burgess IVce6284b2017-01-28 02:19:40 +00007227 Args[0]->Classify(Context), Args.slice(1),
George Burgess IV177399e2017-01-09 04:12:14 +00007228 CandidateSet, /*SuppressUserConversions=*/false);
Douglas Gregor436424c2008-11-18 23:14:02 +00007229 }
Douglas Gregor436424c2008-11-18 23:14:02 +00007230}
7231
Douglas Gregora11693b2008-11-12 17:17:38 +00007232/// AddBuiltinCandidate - Add a candidate for a built-in
7233/// operator. ResultTy and ParamTys are the result and parameter types
7234/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00007235/// arguments being passed to the candidate. IsAssignmentOperator
7236/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00007237/// operator. NumContextualBoolArguments is the number of arguments
7238/// (at the beginning of the argument list) that will be contextually
7239/// converted to bool.
George Burgess IVc07c3892017-06-08 18:19:25 +00007240void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
Douglas Gregorc5e61072009-01-13 00:52:54 +00007241 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00007242 bool IsAssignmentOperator,
7243 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00007244 // Overload resolution is always an unevaluated context.
Faisal Valid143a0c2017-04-01 21:30:49 +00007245 EnterExpressionEvaluationContext Unevaluated(
7246 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00007247
Douglas Gregora11693b2008-11-12 17:17:38 +00007248 // Add this candidate
Richard Smithe54c3072013-05-05 15:51:06 +00007249 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
Craig Topperc3ec1492014-05-26 06:22:03 +00007250 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
7251 Candidate.Function = nullptr;
Douglas Gregor1d248c52008-12-12 02:00:36 +00007252 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007253 Candidate.IgnoreObjectArgument = false;
George Burgess IV5f6ab9a2017-06-08 20:55:21 +00007254 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
Douglas Gregora11693b2008-11-12 17:17:38 +00007255
7256 // Determine the implicit conversion sequences for each of the
7257 // arguments.
7258 Candidate.Viable = true;
Richard Smithe54c3072013-05-05 15:51:06 +00007259 Candidate.ExplicitCallArguments = Args.size();
7260 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00007261 // C++ [over.match.oper]p4:
7262 // For the built-in assignment operators, conversions of the
7263 // left operand are restricted as follows:
7264 // -- no temporaries are introduced to hold the left operand, and
7265 // -- no user-defined conversions are applied to the left
7266 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00007267 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00007268 //
7269 // We block these conversions by turning off user-defined
7270 // conversions, since that is the only way that initialization of
7271 // a reference to a non-class type can occur from something that
7272 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00007273 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00007274 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00007275 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00007276 Candidate.Conversions[ArgIdx]
7277 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00007278 } else {
Mike Stump11289f42009-09-09 15:08:12 +00007279 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00007280 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00007281 ArgIdx == 0 && IsAssignmentOperator,
John McCall31168b02011-06-15 23:02:42 +00007282 /*InOverloadResolution=*/false,
7283 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00007284 getLangOpts().ObjCAutoRefCount);
Douglas Gregor5fb53972009-01-14 15:45:31 +00007285 }
John McCall0d1da222010-01-12 00:44:57 +00007286 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007287 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00007288 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00007289 break;
7290 }
Douglas Gregora11693b2008-11-12 17:17:38 +00007291 }
7292}
7293
Craig Toppercd7b0332013-07-01 06:29:40 +00007294namespace {
7295
Douglas Gregora11693b2008-11-12 17:17:38 +00007296/// BuiltinCandidateTypeSet - A set of types that will be used for the
7297/// candidate operator functions for built-in operators (C++
7298/// [over.built]). The types are separated into pointer types and
7299/// enumeration types.
7300class BuiltinCandidateTypeSet {
7301 /// TypeSet - A set of types.
Richard Smith95853072016-03-25 00:08:53 +00007302 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
7303 llvm::SmallPtrSet<QualType, 8>> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00007304
7305 /// PointerTypes - The set of pointer types that will be used in the
7306 /// built-in candidates.
7307 TypeSet PointerTypes;
7308
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007309 /// MemberPointerTypes - The set of member pointer types that will be
7310 /// used in the built-in candidates.
7311 TypeSet MemberPointerTypes;
7312
Douglas Gregora11693b2008-11-12 17:17:38 +00007313 /// EnumerationTypes - The set of enumeration types that will be
7314 /// used in the built-in candidates.
7315 TypeSet EnumerationTypes;
7316
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007317 /// The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007318 /// candidates.
7319 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00007320
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007321 /// A flag indicating non-record types are viable candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00007322 bool HasNonRecordTypes;
7323
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007324 /// A flag indicating whether either arithmetic or enumeration types
Chandler Carruth00a38332010-12-13 01:44:01 +00007325 /// were present in the candidate set.
7326 bool HasArithmeticOrEnumeralTypes;
7327
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007328 /// A flag indicating whether the nullptr type was present in the
Douglas Gregor80af3132011-05-21 23:15:46 +00007329 /// candidate set.
7330 bool HasNullPtrType;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00007331
Douglas Gregor8a2e6012009-08-24 15:23:48 +00007332 /// Sema - The semantic analysis instance where we are building the
7333 /// candidate type set.
7334 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00007335
Douglas Gregora11693b2008-11-12 17:17:38 +00007336 /// Context - The AST context in which we will build the type sets.
7337 ASTContext &Context;
7338
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007339 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7340 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007341 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00007342
7343public:
7344 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00007345 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00007346
Mike Stump11289f42009-09-09 15:08:12 +00007347 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00007348 : HasNonRecordTypes(false),
7349 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor80af3132011-05-21 23:15:46 +00007350 HasNullPtrType(false),
Chandler Carruth00a38332010-12-13 01:44:01 +00007351 SemaRef(SemaRef),
7352 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00007353
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007354 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007355 SourceLocation Loc,
7356 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007357 bool AllowExplicitConversions,
7358 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00007359
7360 /// pointer_begin - First pointer type found;
7361 iterator pointer_begin() { return PointerTypes.begin(); }
7362
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007363 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00007364 iterator pointer_end() { return PointerTypes.end(); }
7365
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007366 /// member_pointer_begin - First member pointer type found;
7367 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
7368
7369 /// member_pointer_end - Past the last member pointer type found;
7370 iterator member_pointer_end() { return MemberPointerTypes.end(); }
7371
Douglas Gregora11693b2008-11-12 17:17:38 +00007372 /// enumeration_begin - First enumeration type found;
7373 iterator enumeration_begin() { return EnumerationTypes.begin(); }
7374
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007375 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00007376 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007377
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007378 iterator vector_begin() { return VectorTypes.begin(); }
7379 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00007380
7381 bool hasNonRecordTypes() { return HasNonRecordTypes; }
7382 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor80af3132011-05-21 23:15:46 +00007383 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregora11693b2008-11-12 17:17:38 +00007384};
7385
Craig Toppercd7b0332013-07-01 06:29:40 +00007386} // end anonymous namespace
7387
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007388/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00007389/// the set of pointer types along with any more-qualified variants of
7390/// that type. For example, if @p Ty is "int const *", this routine
7391/// will add "int const *", "int const volatile *", "int const
7392/// restrict *", and "int const volatile restrict *" to the set of
7393/// pointer types. Returns true if the add of @p Ty itself succeeded,
7394/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00007395///
7396/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007397bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007398BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7399 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00007400
Douglas Gregora11693b2008-11-12 17:17:38 +00007401 // Insert this type.
Richard Smith95853072016-03-25 00:08:53 +00007402 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00007403 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007404
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00007405 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00007406 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00007407 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00007408 if (!PointerTy) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00007409 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7410 PointeeTy = PTy->getPointeeType();
7411 buildObjCPtr = true;
7412 } else {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00007413 PointeeTy = PointerTy->getPointeeType();
Douglas Gregor5bee2582012-06-04 00:15:09 +00007414 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00007415
Sebastian Redl4990a632009-11-18 20:39:26 +00007416 // Don't add qualified variants of arrays. For one, they're not allowed
7417 // (the qualifier would sink to the element type), and for another, the
7418 // only overload situation where it matters is subscript or pointer +- int,
7419 // and those shouldn't have qualifier variants anyway.
7420 if (PointeeTy->isArrayType())
7421 return true;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00007422
John McCall8ccfcb52009-09-24 19:53:00 +00007423 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007424 bool hasVolatile = VisibleQuals.hasVolatile();
7425 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007426
John McCall8ccfcb52009-09-24 19:53:00 +00007427 // Iterate through all strict supersets of BaseCVR.
7428 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7429 if ((CVR | BaseCVR) != CVR) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00007430 // Skip over volatile if no volatile found anywhere in the types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007431 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00007432
Douglas Gregor5bee2582012-06-04 00:15:09 +00007433 // Skip over restrict if no restrict found anywhere in the types, or if
7434 // the type cannot be restrict-qualified.
7435 if ((CVR & Qualifiers::Restrict) &&
7436 (!hasRestrict ||
7437 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7438 continue;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00007439
Douglas Gregor5bee2582012-06-04 00:15:09 +00007440 // Build qualified pointee type.
John McCall8ccfcb52009-09-24 19:53:00 +00007441 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00007442
Douglas Gregor5bee2582012-06-04 00:15:09 +00007443 // Build qualified pointer type.
7444 QualType QPointerTy;
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00007445 if (!buildObjCPtr)
Douglas Gregor5bee2582012-06-04 00:15:09 +00007446 QPointerTy = Context.getPointerType(QPointeeTy);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00007447 else
Douglas Gregor5bee2582012-06-04 00:15:09 +00007448 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00007449
Douglas Gregor5bee2582012-06-04 00:15:09 +00007450 // Insert qualified pointer type.
7451 PointerTypes.insert(QPointerTy);
Douglas Gregora11693b2008-11-12 17:17:38 +00007452 }
7453
7454 return true;
7455}
7456
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007457/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7458/// to the set of pointer types along with any more-qualified variants of
7459/// that type. For example, if @p Ty is "int const *", this routine
7460/// will add "int const *", "int const volatile *", "int const
7461/// restrict *", and "int const volatile restrict *" to the set of
7462/// pointer types. Returns true if the add of @p Ty itself succeeded,
7463/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00007464///
7465/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007466bool
7467BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7468 QualType Ty) {
7469 // Insert this type.
Richard Smith95853072016-03-25 00:08:53 +00007470 if (!MemberPointerTypes.insert(Ty))
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007471 return false;
7472
John McCall8ccfcb52009-09-24 19:53:00 +00007473 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
7474 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007475
John McCall8ccfcb52009-09-24 19:53:00 +00007476 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00007477 // Don't add qualified variants of arrays. For one, they're not allowed
7478 // (the qualifier would sink to the element type), and for another, the
7479 // only overload situation where it matters is subscript or pointer +- int,
7480 // and those shouldn't have qualifier variants anyway.
7481 if (PointeeTy->isArrayType())
7482 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00007483 const Type *ClassTy = PointerTy->getClass();
7484
7485 // Iterate through all strict supersets of the pointee type's CVR
7486 // qualifiers.
7487 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7488 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7489 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007490
John McCall8ccfcb52009-09-24 19:53:00 +00007491 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00007492 MemberPointerTypes.insert(
7493 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007494 }
7495
7496 return true;
7497}
7498
Douglas Gregora11693b2008-11-12 17:17:38 +00007499/// AddTypesConvertedFrom - Add each of the types to which the type @p
7500/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007501/// primarily interested in pointer types and enumeration types. We also
7502/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00007503/// AllowUserConversions is true if we should look at the conversion
7504/// functions of a class type, and AllowExplicitConversions if we
7505/// should also include the explicit conversion functions of a class
7506/// type.
Mike Stump11289f42009-09-09 15:08:12 +00007507void
Douglas Gregor5fb53972009-01-14 15:45:31 +00007508BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007509 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00007510 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007511 bool AllowExplicitConversions,
7512 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007513 // Only deal with canonical types.
7514 Ty = Context.getCanonicalType(Ty);
7515
7516 // Look through reference types; they aren't part of the type of an
7517 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007518 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00007519 Ty = RefTy->getPointeeType();
7520
John McCall33ddac02011-01-19 10:06:00 +00007521 // If we're dealing with an array type, decay to the pointer.
7522 if (Ty->isArrayType())
7523 Ty = SemaRef.Context.getArrayDecayedType(Ty);
7524
7525 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007526 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00007527
Chandler Carruth00a38332010-12-13 01:44:01 +00007528 // Flag if we ever add a non-record type.
7529 const RecordType *TyRec = Ty->getAs<RecordType>();
7530 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7531
Chandler Carruth00a38332010-12-13 01:44:01 +00007532 // Flag if we encounter an arithmetic type.
7533 HasArithmeticOrEnumeralTypes =
7534 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7535
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00007536 if (Ty->isObjCIdType() || Ty->isObjCClassType())
7537 PointerTypes.insert(Ty);
7538 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007539 // Insert our type, and its more-qualified variants, into the set
7540 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007541 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00007542 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007543 } else if (Ty->isMemberPointerType()) {
7544 // Member pointers are far easier, since the pointee can't be converted.
7545 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7546 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00007547 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007548 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00007549 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007550 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007551 // We treat vector types as arithmetic types in many contexts as an
7552 // extension.
7553 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007554 VectorTypes.insert(Ty);
Douglas Gregor80af3132011-05-21 23:15:46 +00007555 } else if (Ty->isNullPtrType()) {
7556 HasNullPtrType = true;
Chandler Carruth00a38332010-12-13 01:44:01 +00007557 } else if (AllowUserConversions && TyRec) {
7558 // No conversion functions in incomplete types.
Richard Smithdb0ac552015-12-18 22:40:25 +00007559 if (!SemaRef.isCompleteType(Loc, Ty))
Chandler Carruth00a38332010-12-13 01:44:01 +00007560 return;
Mike Stump11289f42009-09-09 15:08:12 +00007561
Chandler Carruth00a38332010-12-13 01:44:01 +00007562 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00007563 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007564 if (isa<UsingShadowDecl>(D))
7565 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00007566
Chandler Carruth00a38332010-12-13 01:44:01 +00007567 // Skip conversion function templates; they don't tell us anything
7568 // about which builtin types we can convert to.
7569 if (isa<FunctionTemplateDecl>(D))
7570 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00007571
Chandler Carruth00a38332010-12-13 01:44:01 +00007572 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7573 if (AllowExplicitConversions || !Conv->isExplicit()) {
7574 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7575 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00007576 }
7577 }
7578 }
7579}
7580
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007581/// Helper function for AddBuiltinOperatorCandidates() that adds
Douglas Gregor84605ae2009-08-24 13:43:27 +00007582/// the volatile- and non-volatile-qualified assignment operators for the
7583/// given type to the candidate set.
7584static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7585 QualType T,
Richard Smithe54c3072013-05-05 15:51:06 +00007586 ArrayRef<Expr *> Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00007587 OverloadCandidateSet &CandidateSet) {
7588 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00007589
Douglas Gregor84605ae2009-08-24 13:43:27 +00007590 // T& operator=(T&, T)
7591 ParamTypes[0] = S.Context.getLValueReferenceType(T);
7592 ParamTypes[1] = T;
George Burgess IVc07c3892017-06-08 18:19:25 +00007593 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Douglas Gregor84605ae2009-08-24 13:43:27 +00007594 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00007595
Douglas Gregor84605ae2009-08-24 13:43:27 +00007596 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7597 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00007598 ParamTypes[0]
7599 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00007600 ParamTypes[1] = T;
George Burgess IVc07c3892017-06-08 18:19:25 +00007601 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00007602 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00007603 }
7604}
Mike Stump11289f42009-09-09 15:08:12 +00007605
Sebastian Redl1054fae2009-10-25 17:03:50 +00007606/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7607/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007608static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7609 Qualifiers VRQuals;
7610 const RecordType *TyRec;
7611 if (const MemberPointerType *RHSMPType =
7612 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00007613 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007614 else
7615 TyRec = ArgExpr->getType()->getAs<RecordType>();
7616 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007617 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007618 VRQuals.addVolatile();
7619 VRQuals.addRestrict();
7620 return VRQuals;
7621 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007622
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007623 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00007624 if (!ClassDecl->hasDefinition())
7625 return VRQuals;
7626
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00007627 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
John McCallda4458e2010-03-31 01:36:47 +00007628 if (isa<UsingShadowDecl>(D))
7629 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7630 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007631 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7632 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7633 CanTy = ResTypeRef->getPointeeType();
7634 // Need to go down the pointer/mempointer chain and add qualifiers
7635 // as see them.
7636 bool done = false;
7637 while (!done) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00007638 if (CanTy.isRestrictQualified())
7639 VRQuals.addRestrict();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007640 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7641 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007642 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007643 CanTy->getAs<MemberPointerType>())
7644 CanTy = ResTypeMPtr->getPointeeType();
7645 else
7646 done = true;
7647 if (CanTy.isVolatileQualified())
7648 VRQuals.addVolatile();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007649 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7650 return VRQuals;
7651 }
7652 }
7653 }
7654 return VRQuals;
7655}
John McCall52872982010-11-13 05:51:15 +00007656
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007657namespace {
John McCall52872982010-11-13 05:51:15 +00007658
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007659/// Helper class to manage the addition of builtin operator overload
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007660/// candidates. It provides shared state and utility methods used throughout
7661/// the process, as well as a helper method to add each group of builtin
7662/// operator overloads from the standard to a candidate set.
7663class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007664 // Common instance state available to all overload candidate addition methods.
7665 Sema &S;
Richard Smithe54c3072013-05-05 15:51:06 +00007666 ArrayRef<Expr *> Args;
Chandler Carruthc6586e52010-12-12 10:35:00 +00007667 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00007668 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007669 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruthc6586e52010-12-12 10:35:00 +00007670 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007671
Hans Wennborg82371412017-11-15 17:11:53 +00007672 static constexpr int ArithmeticTypesCap = 24;
7673 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
7674
7675 // Define some indices used to iterate over the arithemetic types in
7676 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic
John McCall52872982010-11-13 05:51:15 +00007677 // types are that preserved by promotion (C++ [over.built]p2).
Hans Wennborg82371412017-11-15 17:11:53 +00007678 unsigned FirstIntegralType,
7679 LastIntegralType;
7680 unsigned FirstPromotedIntegralType,
7681 LastPromotedIntegralType;
7682 unsigned FirstPromotedArithmeticType,
7683 LastPromotedArithmeticType;
7684 unsigned NumArithmeticTypes;
John McCall52872982010-11-13 05:51:15 +00007685
Hans Wennborg82371412017-11-15 17:11:53 +00007686 void InitArithmeticTypes() {
7687 // Start of promoted types.
7688 FirstPromotedArithmeticType = 0;
7689 ArithmeticTypes.push_back(S.Context.FloatTy);
7690 ArithmeticTypes.push_back(S.Context.DoubleTy);
7691 ArithmeticTypes.push_back(S.Context.LongDoubleTy);
7692 if (S.Context.getTargetInfo().hasFloat128Type())
7693 ArithmeticTypes.push_back(S.Context.Float128Ty);
John McCall52872982010-11-13 05:51:15 +00007694
Hans Wennborg82371412017-11-15 17:11:53 +00007695 // Start of integral types.
7696 FirstIntegralType = ArithmeticTypes.size();
7697 FirstPromotedIntegralType = ArithmeticTypes.size();
7698 ArithmeticTypes.push_back(S.Context.IntTy);
7699 ArithmeticTypes.push_back(S.Context.LongTy);
7700 ArithmeticTypes.push_back(S.Context.LongLongTy);
7701 if (S.Context.getTargetInfo().hasInt128Type())
7702 ArithmeticTypes.push_back(S.Context.Int128Ty);
7703 ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
7704 ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
7705 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
7706 if (S.Context.getTargetInfo().hasInt128Type())
7707 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
7708 LastPromotedIntegralType = ArithmeticTypes.size();
7709 LastPromotedArithmeticType = ArithmeticTypes.size();
7710 // End of promoted types.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007711
Hans Wennborg82371412017-11-15 17:11:53 +00007712 ArithmeticTypes.push_back(S.Context.BoolTy);
7713 ArithmeticTypes.push_back(S.Context.CharTy);
7714 ArithmeticTypes.push_back(S.Context.WCharTy);
Richard Smith3a8244d2018-05-01 05:02:45 +00007715 if (S.Context.getLangOpts().Char8)
7716 ArithmeticTypes.push_back(S.Context.Char8Ty);
Hans Wennborg82371412017-11-15 17:11:53 +00007717 ArithmeticTypes.push_back(S.Context.Char16Ty);
7718 ArithmeticTypes.push_back(S.Context.Char32Ty);
7719 ArithmeticTypes.push_back(S.Context.SignedCharTy);
7720 ArithmeticTypes.push_back(S.Context.ShortTy);
7721 ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
7722 ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
7723 LastIntegralType = ArithmeticTypes.size();
7724 NumArithmeticTypes = ArithmeticTypes.size();
7725 // End of integral types.
7726 // FIXME: What about complex? What about half?
7727
7728 assert(ArithmeticTypes.size() <= ArithmeticTypesCap &&
7729 "Enough inline storage for all arithmetic types.");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007730 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007731
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007732 /// Helper method to factor out the common pattern of adding overloads
Chandler Carruth5659c0c2010-12-12 09:22:45 +00007733 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007734 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007735 bool HasVolatile,
7736 bool HasRestrict) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007737 QualType ParamTypes[2] = {
7738 S.Context.getLValueReferenceType(CandidateTy),
7739 S.Context.IntTy
7740 };
7741
7742 // Non-volatile version.
George Burgess IVc07c3892017-06-08 18:19:25 +00007743 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007744
7745 // Use a heuristic to reduce number of builtin candidates in the set:
7746 // add volatile version only if there are conversions to a volatile type.
7747 if (HasVolatile) {
7748 ParamTypes[0] =
7749 S.Context.getLValueReferenceType(
7750 S.Context.getVolatileType(CandidateTy));
George Burgess IVc07c3892017-06-08 18:19:25 +00007751 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007752 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00007753
Douglas Gregor5bee2582012-06-04 00:15:09 +00007754 // Add restrict version only if there are conversions to a restrict type
7755 // and our candidate type is a non-restrict-qualified pointer.
7756 if (HasRestrict && CandidateTy->isAnyPointerType() &&
7757 !CandidateTy.isRestrictQualified()) {
7758 ParamTypes[0]
7759 = S.Context.getLValueReferenceType(
7760 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
George Burgess IVc07c3892017-06-08 18:19:25 +00007761 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00007762
Douglas Gregor5bee2582012-06-04 00:15:09 +00007763 if (HasVolatile) {
7764 ParamTypes[0]
7765 = S.Context.getLValueReferenceType(
7766 S.Context.getCVRQualifiedType(CandidateTy,
7767 (Qualifiers::Volatile |
7768 Qualifiers::Restrict)));
George Burgess IVc07c3892017-06-08 18:19:25 +00007769 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007770 }
7771 }
7772
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007773 }
7774
7775public:
7776 BuiltinOperatorOverloadBuilder(
Richard Smithe54c3072013-05-05 15:51:06 +00007777 Sema &S, ArrayRef<Expr *> Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007778 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00007779 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007780 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007781 OverloadCandidateSet &CandidateSet)
Richard Smithe54c3072013-05-05 15:51:06 +00007782 : S(S), Args(Args),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007783 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00007784 HasArithmeticOrEnumeralCandidateType(
7785 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007786 CandidateTypes(CandidateTypes),
7787 CandidateSet(CandidateSet) {
Hans Wennborg82371412017-11-15 17:11:53 +00007788
7789 InitArithmeticTypes();
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007790 }
7791
Jan Korous536d2e32018-04-18 13:38:39 +00007792 // Increment is deprecated for bool since C++17.
7793 //
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007794 // C++ [over.built]p3:
7795 //
Jan Korous536d2e32018-04-18 13:38:39 +00007796 // For every pair (T, VQ), where T is an arithmetic type other
7797 // than bool, and VQ is either volatile or empty, there exist
7798 // candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007799 //
7800 // VQ T& operator++(VQ T&);
7801 // T operator++(VQ T&, int);
7802 //
7803 // C++ [over.built]p4:
7804 //
7805 // For every pair (T, VQ), where T is an arithmetic type other
7806 // than bool, and VQ is either volatile or empty, there exist
7807 // candidate operator functions of the form
7808 //
7809 // VQ T& operator--(VQ T&);
7810 // T operator--(VQ T&, int);
7811 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007812 if (!HasArithmeticOrEnumeralCandidateType)
7813 return;
7814
Jan Korousd74ebe22018-04-11 13:36:29 +00007815 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
7816 const auto TypeOfT = ArithmeticTypes[Arith];
Jan Korous536d2e32018-04-18 13:38:39 +00007817 if (TypeOfT == S.Context.BoolTy) {
7818 if (Op == OO_MinusMinus)
7819 continue;
7820 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
7821 continue;
7822 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007823 addPlusPlusMinusMinusStyleOverloads(
Jan Korousd74ebe22018-04-11 13:36:29 +00007824 TypeOfT,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007825 VisibleTypeConversionsQuals.hasVolatile(),
7826 VisibleTypeConversionsQuals.hasRestrict());
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007827 }
7828 }
7829
7830 // C++ [over.built]p5:
7831 //
7832 // For every pair (T, VQ), where T is a cv-qualified or
7833 // cv-unqualified object type, and VQ is either volatile or
7834 // empty, there exist candidate operator functions of the form
7835 //
7836 // T*VQ& operator++(T*VQ&);
7837 // T*VQ& operator--(T*VQ&);
7838 // T* operator++(T*VQ&, int);
7839 // T* operator--(T*VQ&, int);
7840 void addPlusPlusMinusMinusPointerOverloads() {
7841 for (BuiltinCandidateTypeSet::iterator
7842 Ptr = CandidateTypes[0].pointer_begin(),
7843 PtrEnd = CandidateTypes[0].pointer_end();
7844 Ptr != PtrEnd; ++Ptr) {
7845 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00007846 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007847 continue;
7848
7849 addPlusPlusMinusMinusStyleOverloads(*Ptr,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007850 (!(*Ptr).isVolatileQualified() &&
7851 VisibleTypeConversionsQuals.hasVolatile()),
7852 (!(*Ptr).isRestrictQualified() &&
7853 VisibleTypeConversionsQuals.hasRestrict()));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007854 }
7855 }
7856
7857 // C++ [over.built]p6:
7858 // For every cv-qualified or cv-unqualified object type T, there
7859 // exist candidate operator functions of the form
7860 //
7861 // T& operator*(T*);
7862 //
7863 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007864 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00007865 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007866 // T& operator*(T*);
7867 void addUnaryStarPointerOverloads() {
7868 for (BuiltinCandidateTypeSet::iterator
7869 Ptr = CandidateTypes[0].pointer_begin(),
7870 PtrEnd = CandidateTypes[0].pointer_end();
7871 Ptr != PtrEnd; ++Ptr) {
7872 QualType ParamTy = *Ptr;
7873 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007874 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7875 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007876
Douglas Gregor02824322011-01-26 19:30:28 +00007877 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7878 if (Proto->getTypeQuals() || Proto->getRefQualifier())
7879 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007880
George Burgess IVc07c3892017-06-08 18:19:25 +00007881 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007882 }
7883 }
7884
7885 // C++ [over.built]p9:
7886 // For every promoted arithmetic type T, there exist candidate
7887 // operator functions of the form
7888 //
7889 // T operator+(T);
7890 // T operator-(T);
7891 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007892 if (!HasArithmeticOrEnumeralCandidateType)
7893 return;
7894
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007895 for (unsigned Arith = FirstPromotedArithmeticType;
7896 Arith < LastPromotedArithmeticType; ++Arith) {
Hans Wennborg82371412017-11-15 17:11:53 +00007897 QualType ArithTy = ArithmeticTypes[Arith];
George Burgess IVc07c3892017-06-08 18:19:25 +00007898 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007899 }
7900
7901 // Extension: We also add these operators for vector types.
7902 for (BuiltinCandidateTypeSet::iterator
7903 Vec = CandidateTypes[0].vector_begin(),
7904 VecEnd = CandidateTypes[0].vector_end();
7905 Vec != VecEnd; ++Vec) {
7906 QualType VecTy = *Vec;
George Burgess IVc07c3892017-06-08 18:19:25 +00007907 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007908 }
7909 }
7910
7911 // C++ [over.built]p8:
7912 // For every type T, there exist candidate operator functions of
7913 // the form
7914 //
7915 // T* operator+(T*);
7916 void addUnaryPlusPointerOverloads() {
7917 for (BuiltinCandidateTypeSet::iterator
7918 Ptr = CandidateTypes[0].pointer_begin(),
7919 PtrEnd = CandidateTypes[0].pointer_end();
7920 Ptr != PtrEnd; ++Ptr) {
7921 QualType ParamTy = *Ptr;
George Burgess IVc07c3892017-06-08 18:19:25 +00007922 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007923 }
7924 }
7925
7926 // C++ [over.built]p10:
7927 // For every promoted integral type T, there exist candidate
7928 // operator functions of the form
7929 //
7930 // T operator~(T);
7931 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007932 if (!HasArithmeticOrEnumeralCandidateType)
7933 return;
7934
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007935 for (unsigned Int = FirstPromotedIntegralType;
7936 Int < LastPromotedIntegralType; ++Int) {
Hans Wennborg82371412017-11-15 17:11:53 +00007937 QualType IntTy = ArithmeticTypes[Int];
George Burgess IVc07c3892017-06-08 18:19:25 +00007938 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007939 }
7940
7941 // Extension: We also add this operator for vector types.
7942 for (BuiltinCandidateTypeSet::iterator
7943 Vec = CandidateTypes[0].vector_begin(),
7944 VecEnd = CandidateTypes[0].vector_end();
7945 Vec != VecEnd; ++Vec) {
7946 QualType VecTy = *Vec;
George Burgess IVc07c3892017-06-08 18:19:25 +00007947 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007948 }
7949 }
7950
7951 // C++ [over.match.oper]p16:
Richard Smith5e9746f2016-10-21 22:00:42 +00007952 // For every pointer to member type T or type std::nullptr_t, there
7953 // exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007954 //
7955 // bool operator==(T,T);
7956 // bool operator!=(T,T);
Richard Smith5e9746f2016-10-21 22:00:42 +00007957 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007958 /// Set of (canonical) types that we've already handled.
7959 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7960
Richard Smithe54c3072013-05-05 15:51:06 +00007961 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007962 for (BuiltinCandidateTypeSet::iterator
7963 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7964 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7965 MemPtr != MemPtrEnd;
7966 ++MemPtr) {
7967 // Don't add the same builtin candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007968 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007969 continue;
7970
7971 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
George Burgess IVc07c3892017-06-08 18:19:25 +00007972 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007973 }
Richard Smith5e9746f2016-10-21 22:00:42 +00007974
7975 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7976 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7977 if (AddedTypes.insert(NullPtrTy).second) {
7978 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
George Burgess IVc07c3892017-06-08 18:19:25 +00007979 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Richard Smith5e9746f2016-10-21 22:00:42 +00007980 }
7981 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007982 }
7983 }
7984
7985 // C++ [over.built]p15:
7986 //
Richard Smith5e9746f2016-10-21 22:00:42 +00007987 // For every T, where T is an enumeration type or a pointer type,
7988 // there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007989 //
7990 // bool operator<(T, T);
7991 // bool operator>(T, T);
7992 // bool operator<=(T, T);
7993 // bool operator>=(T, T);
7994 // bool operator==(T, T);
7995 // bool operator!=(T, T);
Eric Fiselier0683c0e2018-05-07 21:07:10 +00007996 // R operator<=>(T, T)
7997 void addGenericBinaryPointerOrEnumeralOverloads() {
Eli Friedman14f082b2012-09-18 21:52:24 +00007998 // C++ [over.match.oper]p3:
7999 // [...]the built-in candidates include all of the candidate operator
8000 // functions defined in 13.6 that, compared to the given operator, [...]
8001 // do not have the same parameter-type-list as any non-template non-member
8002 // candidate.
Chandler Carruthc02db8c2010-12-12 09:14:11 +00008003 //
Eli Friedman14f082b2012-09-18 21:52:24 +00008004 // Note that in practice, this only affects enumeration types because there
8005 // aren't any built-in candidates of record type, and a user-defined operator
8006 // must have an operand of record or enumeration type. Also, the only other
8007 // overloaded operator with enumeration arguments, operator=,
Chandler Carruthc02db8c2010-12-12 09:14:11 +00008008 // cannot be overloaded for enumeration types, so this is the only place
8009 // where we must suppress candidates like this.
8010 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
8011 UserDefinedBinaryOperators;
8012
Richard Smithe54c3072013-05-05 15:51:06 +00008013 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruthc02db8c2010-12-12 09:14:11 +00008014 if (CandidateTypes[ArgIdx].enumeration_begin() !=
8015 CandidateTypes[ArgIdx].enumeration_end()) {
8016 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
8017 CEnd = CandidateSet.end();
8018 C != CEnd; ++C) {
8019 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
8020 continue;
8021
Eli Friedman14f082b2012-09-18 21:52:24 +00008022 if (C->Function->isFunctionTemplateSpecialization())
8023 continue;
8024
Chandler Carruthc02db8c2010-12-12 09:14:11 +00008025 QualType FirstParamType =
8026 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
8027 QualType SecondParamType =
8028 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
8029
8030 // Skip if either parameter isn't of enumeral type.
8031 if (!FirstParamType->isEnumeralType() ||
8032 !SecondParamType->isEnumeralType())
8033 continue;
8034
8035 // Add this operator to the set of known user-defined operators.
8036 UserDefinedBinaryOperators.insert(
8037 std::make_pair(S.Context.getCanonicalType(FirstParamType),
8038 S.Context.getCanonicalType(SecondParamType)));
8039 }
8040 }
8041 }
8042
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008043 /// Set of (canonical) types that we've already handled.
8044 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8045
Richard Smithe54c3072013-05-05 15:51:06 +00008046 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008047 for (BuiltinCandidateTypeSet::iterator
8048 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8049 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8050 Ptr != PtrEnd; ++Ptr) {
8051 // Don't add the same builtin candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00008052 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008053 continue;
8054
8055 QualType ParamTypes[2] = { *Ptr, *Ptr };
George Burgess IVc07c3892017-06-08 18:19:25 +00008056 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008057 }
8058 for (BuiltinCandidateTypeSet::iterator
8059 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8060 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8061 Enum != EnumEnd; ++Enum) {
8062 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
8063
Chandler Carruthc02db8c2010-12-12 09:14:11 +00008064 // Don't add the same builtin candidate twice, or if a user defined
8065 // candidate exists.
David Blaikie82e95a32014-11-19 07:49:47 +00008066 if (!AddedTypes.insert(CanonType).second ||
Chandler Carruthc02db8c2010-12-12 09:14:11 +00008067 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
8068 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008069 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008070 QualType ParamTypes[2] = { *Enum, *Enum };
George Burgess IVc07c3892017-06-08 18:19:25 +00008071 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008072 }
8073 }
8074 }
8075
8076 // C++ [over.built]p13:
8077 //
8078 // For every cv-qualified or cv-unqualified object type T
8079 // there exist candidate operator functions of the form
8080 //
8081 // T* operator+(T*, ptrdiff_t);
8082 // T& operator[](T*, ptrdiff_t); [BELOW]
8083 // T* operator-(T*, ptrdiff_t);
8084 // T* operator+(ptrdiff_t, T*);
8085 // T& operator[](ptrdiff_t, T*); [BELOW]
8086 //
8087 // C++ [over.built]p14:
8088 //
8089 // For every T, where T is a pointer to object type, there
8090 // exist candidate operator functions of the form
8091 //
8092 // ptrdiff_t operator-(T, T);
8093 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
8094 /// Set of (canonical) types that we've already handled.
8095 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8096
8097 for (int Arg = 0; Arg < 2; ++Arg) {
Eric Christopher9207a522015-08-21 16:24:01 +00008098 QualType AsymmetricParamTypes[2] = {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008099 S.Context.getPointerDiffType(),
8100 S.Context.getPointerDiffType(),
8101 };
8102 for (BuiltinCandidateTypeSet::iterator
8103 Ptr = CandidateTypes[Arg].pointer_begin(),
8104 PtrEnd = CandidateTypes[Arg].pointer_end();
8105 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00008106 QualType PointeeTy = (*Ptr)->getPointeeType();
8107 if (!PointeeTy->isObjectType())
8108 continue;
8109
Eric Christopher9207a522015-08-21 16:24:01 +00008110 AsymmetricParamTypes[Arg] = *Ptr;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008111 if (Arg == 0 || Op == OO_Plus) {
8112 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
8113 // T* operator+(ptrdiff_t, T*);
George Burgess IVc07c3892017-06-08 18:19:25 +00008114 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008115 }
8116 if (Op == OO_Minus) {
8117 // ptrdiff_t operator-(T, T);
David Blaikie82e95a32014-11-19 07:49:47 +00008118 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008119 continue;
8120
8121 QualType ParamTypes[2] = { *Ptr, *Ptr };
George Burgess IVc07c3892017-06-08 18:19:25 +00008122 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008123 }
8124 }
8125 }
8126 }
8127
8128 // C++ [over.built]p12:
8129 //
8130 // For every pair of promoted arithmetic types L and R, there
8131 // exist candidate operator functions of the form
8132 //
8133 // LR operator*(L, R);
8134 // LR operator/(L, R);
8135 // LR operator+(L, R);
8136 // LR operator-(L, R);
8137 // bool operator<(L, R);
8138 // bool operator>(L, R);
8139 // bool operator<=(L, R);
8140 // bool operator>=(L, R);
8141 // bool operator==(L, R);
8142 // bool operator!=(L, R);
8143 //
8144 // where LR is the result of the usual arithmetic conversions
8145 // between types L and R.
8146 //
8147 // C++ [over.built]p24:
8148 //
8149 // For every pair of promoted arithmetic types L and R, there exist
8150 // candidate operator functions of the form
8151 //
8152 // LR operator?(bool, L, R);
8153 //
8154 // where LR is the result of the usual arithmetic conversions
8155 // between types L and R.
8156 // Our candidates ignore the first parameter.
George Burgess IVc07c3892017-06-08 18:19:25 +00008157 void addGenericBinaryArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00008158 if (!HasArithmeticOrEnumeralCandidateType)
8159 return;
8160
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008161 for (unsigned Left = FirstPromotedArithmeticType;
8162 Left < LastPromotedArithmeticType; ++Left) {
8163 for (unsigned Right = FirstPromotedArithmeticType;
8164 Right < LastPromotedArithmeticType; ++Right) {
Hans Wennborg82371412017-11-15 17:11:53 +00008165 QualType LandR[2] = { ArithmeticTypes[Left],
8166 ArithmeticTypes[Right] };
George Burgess IVc07c3892017-06-08 18:19:25 +00008167 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008168 }
8169 }
8170
8171 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
8172 // conditional operator for vector types.
8173 for (BuiltinCandidateTypeSet::iterator
8174 Vec1 = CandidateTypes[0].vector_begin(),
8175 Vec1End = CandidateTypes[0].vector_end();
8176 Vec1 != Vec1End; ++Vec1) {
8177 for (BuiltinCandidateTypeSet::iterator
8178 Vec2 = CandidateTypes[1].vector_begin(),
8179 Vec2End = CandidateTypes[1].vector_end();
8180 Vec2 != Vec2End; ++Vec2) {
8181 QualType LandR[2] = { *Vec1, *Vec2 };
George Burgess IVc07c3892017-06-08 18:19:25 +00008182 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008183 }
8184 }
8185 }
8186
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008187 // C++2a [over.built]p14:
8188 //
8189 // For every integral type T there exists a candidate operator function
8190 // of the form
8191 //
8192 // std::strong_ordering operator<=>(T, T)
8193 //
8194 // C++2a [over.built]p15:
8195 //
8196 // For every pair of floating-point types L and R, there exists a candidate
8197 // operator function of the form
8198 //
8199 // std::partial_ordering operator<=>(L, R);
8200 //
8201 // FIXME: The current specification for integral types doesn't play nice with
8202 // the direction of p0946r0, which allows mixed integral and unscoped-enum
8203 // comparisons. Under the current spec this can lead to ambiguity during
8204 // overload resolution. For example:
8205 //
8206 // enum A : int {a};
8207 // auto x = (a <=> (long)42);
8208 //
8209 // error: call is ambiguous for arguments 'A' and 'long'.
8210 // note: candidate operator<=>(int, int)
8211 // note: candidate operator<=>(long, long)
8212 //
8213 // To avoid this error, this function deviates from the specification and adds
8214 // the mixed overloads `operator<=>(L, R)` where L and R are promoted
8215 // arithmetic types (the same as the generic relational overloads).
8216 //
8217 // For now this function acts as a placeholder.
8218 void addThreeWayArithmeticOverloads() {
8219 addGenericBinaryArithmeticOverloads();
8220 }
8221
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008222 // C++ [over.built]p17:
8223 //
8224 // For every pair of promoted integral types L and R, there
8225 // exist candidate operator functions of the form
8226 //
8227 // LR operator%(L, R);
8228 // LR operator&(L, R);
8229 // LR operator^(L, R);
8230 // LR operator|(L, R);
8231 // L operator<<(L, R);
8232 // L operator>>(L, R);
8233 //
8234 // where LR is the result of the usual arithmetic conversions
8235 // between types L and R.
8236 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00008237 if (!HasArithmeticOrEnumeralCandidateType)
8238 return;
8239
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008240 for (unsigned Left = FirstPromotedIntegralType;
8241 Left < LastPromotedIntegralType; ++Left) {
8242 for (unsigned Right = FirstPromotedIntegralType;
8243 Right < LastPromotedIntegralType; ++Right) {
Hans Wennborg82371412017-11-15 17:11:53 +00008244 QualType LandR[2] = { ArithmeticTypes[Left],
8245 ArithmeticTypes[Right] };
George Burgess IVc07c3892017-06-08 18:19:25 +00008246 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008247 }
8248 }
8249 }
8250
8251 // C++ [over.built]p20:
8252 //
8253 // For every pair (T, VQ), where T is an enumeration or
8254 // pointer to member type and VQ is either volatile or
8255 // empty, there exist candidate operator functions of the form
8256 //
8257 // VQ T& operator=(VQ T&, T);
8258 void addAssignmentMemberPointerOrEnumeralOverloads() {
8259 /// Set of (canonical) types that we've already handled.
8260 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8261
8262 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8263 for (BuiltinCandidateTypeSet::iterator
8264 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8265 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8266 Enum != EnumEnd; ++Enum) {
David Blaikie82e95a32014-11-19 07:49:47 +00008267 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008268 continue;
8269
Richard Smithe54c3072013-05-05 15:51:06 +00008270 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008271 }
8272
8273 for (BuiltinCandidateTypeSet::iterator
8274 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8275 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8276 MemPtr != MemPtrEnd; ++MemPtr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008277 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008278 continue;
8279
Richard Smithe54c3072013-05-05 15:51:06 +00008280 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008281 }
8282 }
8283 }
8284
8285 // C++ [over.built]p19:
8286 //
8287 // For every pair (T, VQ), where T is any type and VQ is either
8288 // volatile or empty, there exist candidate operator functions
8289 // of the form
8290 //
8291 // T*VQ& operator=(T*VQ&, T*);
8292 //
8293 // C++ [over.built]p21:
8294 //
8295 // For every pair (T, VQ), where T is a cv-qualified or
8296 // cv-unqualified object type and VQ is either volatile or
8297 // empty, there exist candidate operator functions of the form
8298 //
8299 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
8300 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
8301 void addAssignmentPointerOverloads(bool isEqualOp) {
8302 /// Set of (canonical) types that we've already handled.
8303 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8304
8305 for (BuiltinCandidateTypeSet::iterator
8306 Ptr = CandidateTypes[0].pointer_begin(),
8307 PtrEnd = CandidateTypes[0].pointer_end();
8308 Ptr != PtrEnd; ++Ptr) {
8309 // If this is operator=, keep track of the builtin candidates we added.
8310 if (isEqualOp)
8311 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00008312 else if (!(*Ptr)->getPointeeType()->isObjectType())
8313 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008314
8315 // non-volatile version
8316 QualType ParamTypes[2] = {
8317 S.Context.getLValueReferenceType(*Ptr),
8318 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
8319 };
George Burgess IVc07c3892017-06-08 18:19:25 +00008320 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008321 /*IsAssigmentOperator=*/ isEqualOp);
8322
Douglas Gregor5bee2582012-06-04 00:15:09 +00008323 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8324 VisibleTypeConversionsQuals.hasVolatile();
8325 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008326 // volatile version
8327 ParamTypes[0] =
8328 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
George Burgess IVc07c3892017-06-08 18:19:25 +00008329 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008330 /*IsAssigmentOperator=*/isEqualOp);
8331 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00008332
Douglas Gregor5bee2582012-06-04 00:15:09 +00008333 if (!(*Ptr).isRestrictQualified() &&
8334 VisibleTypeConversionsQuals.hasRestrict()) {
8335 // restrict version
8336 ParamTypes[0]
8337 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
George Burgess IVc07c3892017-06-08 18:19:25 +00008338 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00008339 /*IsAssigmentOperator=*/isEqualOp);
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00008340
Douglas Gregor5bee2582012-06-04 00:15:09 +00008341 if (NeedVolatile) {
8342 // volatile restrict version
8343 ParamTypes[0]
8344 = S.Context.getLValueReferenceType(
8345 S.Context.getCVRQualifiedType(*Ptr,
8346 (Qualifiers::Volatile |
8347 Qualifiers::Restrict)));
George Burgess IVc07c3892017-06-08 18:19:25 +00008348 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00008349 /*IsAssigmentOperator=*/isEqualOp);
8350 }
8351 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008352 }
8353
8354 if (isEqualOp) {
8355 for (BuiltinCandidateTypeSet::iterator
8356 Ptr = CandidateTypes[1].pointer_begin(),
8357 PtrEnd = CandidateTypes[1].pointer_end();
8358 Ptr != PtrEnd; ++Ptr) {
8359 // Make sure we don't add the same candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00008360 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008361 continue;
8362
Chandler Carruth8e543b32010-12-12 08:17:55 +00008363 QualType ParamTypes[2] = {
8364 S.Context.getLValueReferenceType(*Ptr),
8365 *Ptr,
8366 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008367
8368 // non-volatile version
George Burgess IVc07c3892017-06-08 18:19:25 +00008369 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008370 /*IsAssigmentOperator=*/true);
8371
Douglas Gregor5bee2582012-06-04 00:15:09 +00008372 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8373 VisibleTypeConversionsQuals.hasVolatile();
8374 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008375 // volatile version
8376 ParamTypes[0] =
8377 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
George Burgess IVc07c3892017-06-08 18:19:25 +00008378 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Richard Smithe54c3072013-05-05 15:51:06 +00008379 /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008380 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00008381
Douglas Gregor5bee2582012-06-04 00:15:09 +00008382 if (!(*Ptr).isRestrictQualified() &&
8383 VisibleTypeConversionsQuals.hasRestrict()) {
8384 // restrict version
8385 ParamTypes[0]
8386 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
George Burgess IVc07c3892017-06-08 18:19:25 +00008387 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Richard Smithe54c3072013-05-05 15:51:06 +00008388 /*IsAssigmentOperator=*/true);
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00008389
Douglas Gregor5bee2582012-06-04 00:15:09 +00008390 if (NeedVolatile) {
8391 // volatile restrict version
8392 ParamTypes[0]
8393 = S.Context.getLValueReferenceType(
8394 S.Context.getCVRQualifiedType(*Ptr,
8395 (Qualifiers::Volatile |
8396 Qualifiers::Restrict)));
George Burgess IVc07c3892017-06-08 18:19:25 +00008397 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Richard Smithe54c3072013-05-05 15:51:06 +00008398 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00008399 }
8400 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008401 }
8402 }
8403 }
8404
8405 // C++ [over.built]p18:
8406 //
8407 // For every triple (L, VQ, R), where L is an arithmetic type,
8408 // VQ is either volatile or empty, and R is a promoted
8409 // arithmetic type, there exist candidate operator functions of
8410 // the form
8411 //
8412 // VQ L& operator=(VQ L&, R);
8413 // VQ L& operator*=(VQ L&, R);
8414 // VQ L& operator/=(VQ L&, R);
8415 // VQ L& operator+=(VQ L&, R);
8416 // VQ L& operator-=(VQ L&, R);
8417 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00008418 if (!HasArithmeticOrEnumeralCandidateType)
8419 return;
8420
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008421 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
8422 for (unsigned Right = FirstPromotedArithmeticType;
8423 Right < LastPromotedArithmeticType; ++Right) {
8424 QualType ParamTypes[2];
Hans Wennborg82371412017-11-15 17:11:53 +00008425 ParamTypes[1] = ArithmeticTypes[Right];
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008426
8427 // Add this built-in operator as a candidate (VQ is empty).
8428 ParamTypes[0] =
Hans Wennborg82371412017-11-15 17:11:53 +00008429 S.Context.getLValueReferenceType(ArithmeticTypes[Left]);
George Burgess IVc07c3892017-06-08 18:19:25 +00008430 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008431 /*IsAssigmentOperator=*/isEqualOp);
8432
8433 // Add this built-in operator as a candidate (VQ is 'volatile').
8434 if (VisibleTypeConversionsQuals.hasVolatile()) {
8435 ParamTypes[0] =
Hans Wennborg82371412017-11-15 17:11:53 +00008436 S.Context.getVolatileType(ArithmeticTypes[Left]);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008437 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
George Burgess IVc07c3892017-06-08 18:19:25 +00008438 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008439 /*IsAssigmentOperator=*/isEqualOp);
8440 }
8441 }
8442 }
8443
8444 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8445 for (BuiltinCandidateTypeSet::iterator
8446 Vec1 = CandidateTypes[0].vector_begin(),
8447 Vec1End = CandidateTypes[0].vector_end();
8448 Vec1 != Vec1End; ++Vec1) {
8449 for (BuiltinCandidateTypeSet::iterator
8450 Vec2 = CandidateTypes[1].vector_begin(),
8451 Vec2End = CandidateTypes[1].vector_end();
8452 Vec2 != Vec2End; ++Vec2) {
8453 QualType ParamTypes[2];
8454 ParamTypes[1] = *Vec2;
8455 // Add this built-in operator as a candidate (VQ is empty).
8456 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
George Burgess IVc07c3892017-06-08 18:19:25 +00008457 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008458 /*IsAssigmentOperator=*/isEqualOp);
8459
8460 // Add this built-in operator as a candidate (VQ is 'volatile').
8461 if (VisibleTypeConversionsQuals.hasVolatile()) {
8462 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
8463 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
George Burgess IVc07c3892017-06-08 18:19:25 +00008464 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008465 /*IsAssigmentOperator=*/isEqualOp);
8466 }
8467 }
8468 }
8469 }
8470
8471 // C++ [over.built]p22:
8472 //
8473 // For every triple (L, VQ, R), where L is an integral type, VQ
8474 // is either volatile or empty, and R is a promoted integral
8475 // type, there exist candidate operator functions of the form
8476 //
8477 // VQ L& operator%=(VQ L&, R);
8478 // VQ L& operator<<=(VQ L&, R);
8479 // VQ L& operator>>=(VQ L&, R);
8480 // VQ L& operator&=(VQ L&, R);
8481 // VQ L& operator^=(VQ L&, R);
8482 // VQ L& operator|=(VQ L&, R);
8483 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00008484 if (!HasArithmeticOrEnumeralCandidateType)
8485 return;
8486
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008487 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8488 for (unsigned Right = FirstPromotedIntegralType;
8489 Right < LastPromotedIntegralType; ++Right) {
8490 QualType ParamTypes[2];
Hans Wennborg82371412017-11-15 17:11:53 +00008491 ParamTypes[1] = ArithmeticTypes[Right];
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008492
8493 // Add this built-in operator as a candidate (VQ is empty).
8494 ParamTypes[0] =
Hans Wennborg82371412017-11-15 17:11:53 +00008495 S.Context.getLValueReferenceType(ArithmeticTypes[Left]);
George Burgess IVc07c3892017-06-08 18:19:25 +00008496 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008497 if (VisibleTypeConversionsQuals.hasVolatile()) {
8498 // Add this built-in operator as a candidate (VQ is 'volatile').
Hans Wennborg82371412017-11-15 17:11:53 +00008499 ParamTypes[0] = ArithmeticTypes[Left];
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008500 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8501 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
George Burgess IVc07c3892017-06-08 18:19:25 +00008502 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008503 }
8504 }
8505 }
8506 }
8507
8508 // C++ [over.operator]p23:
8509 //
8510 // There also exist candidate operator functions of the form
8511 //
8512 // bool operator!(bool);
8513 // bool operator&&(bool, bool);
8514 // bool operator||(bool, bool);
8515 void addExclaimOverload() {
8516 QualType ParamTy = S.Context.BoolTy;
George Burgess IVc07c3892017-06-08 18:19:25 +00008517 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008518 /*IsAssignmentOperator=*/false,
8519 /*NumContextualBoolArguments=*/1);
8520 }
8521 void addAmpAmpOrPipePipeOverload() {
8522 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
George Burgess IVc07c3892017-06-08 18:19:25 +00008523 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008524 /*IsAssignmentOperator=*/false,
8525 /*NumContextualBoolArguments=*/2);
8526 }
8527
8528 // C++ [over.built]p13:
8529 //
8530 // For every cv-qualified or cv-unqualified object type T there
8531 // exist candidate operator functions of the form
8532 //
8533 // T* operator+(T*, ptrdiff_t); [ABOVE]
8534 // T& operator[](T*, ptrdiff_t);
8535 // T* operator-(T*, ptrdiff_t); [ABOVE]
8536 // T* operator+(ptrdiff_t, T*); [ABOVE]
8537 // T& operator[](ptrdiff_t, T*);
8538 void addSubscriptOverloads() {
8539 for (BuiltinCandidateTypeSet::iterator
8540 Ptr = CandidateTypes[0].pointer_begin(),
8541 PtrEnd = CandidateTypes[0].pointer_end();
8542 Ptr != PtrEnd; ++Ptr) {
8543 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8544 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00008545 if (!PointeeType->isObjectType())
8546 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008547
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008548 // T& operator[](T*, ptrdiff_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 for (BuiltinCandidateTypeSet::iterator
8553 Ptr = CandidateTypes[1].pointer_begin(),
8554 PtrEnd = CandidateTypes[1].pointer_end();
8555 Ptr != PtrEnd; ++Ptr) {
8556 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8557 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00008558 if (!PointeeType->isObjectType())
8559 continue;
8560
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008561 // T& operator[](ptrdiff_t, T*)
George Burgess IVc07c3892017-06-08 18:19:25 +00008562 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008563 }
8564 }
8565
8566 // C++ [over.built]p11:
8567 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8568 // C1 is the same type as C2 or is a derived class of C2, T is an object
8569 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8570 // there exist candidate operator functions of the form
8571 //
8572 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8573 //
8574 // where CV12 is the union of CV1 and CV2.
8575 void addArrowStarOverloads() {
8576 for (BuiltinCandidateTypeSet::iterator
8577 Ptr = CandidateTypes[0].pointer_begin(),
8578 PtrEnd = CandidateTypes[0].pointer_end();
8579 Ptr != PtrEnd; ++Ptr) {
8580 QualType C1Ty = (*Ptr);
8581 QualType C1;
8582 QualifierCollector Q1;
8583 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8584 if (!isa<RecordType>(C1))
8585 continue;
8586 // heuristic to reduce number of builtin candidates in the set.
8587 // Add volatile/restrict version only if there are conversions to a
8588 // volatile/restrict type.
8589 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8590 continue;
8591 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8592 continue;
8593 for (BuiltinCandidateTypeSet::iterator
8594 MemPtr = CandidateTypes[1].member_pointer_begin(),
8595 MemPtrEnd = CandidateTypes[1].member_pointer_end();
8596 MemPtr != MemPtrEnd; ++MemPtr) {
8597 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8598 QualType C2 = QualType(mptr->getClass(), 0);
8599 C2 = C2.getUnqualifiedType();
Richard Smith0f59cb32015-12-18 21:45:41 +00008600 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008601 break;
8602 QualType ParamTypes[2] = { *Ptr, *MemPtr };
8603 // build CV12 T&
8604 QualType T = mptr->getPointeeType();
8605 if (!VisibleTypeConversionsQuals.hasVolatile() &&
8606 T.isVolatileQualified())
8607 continue;
8608 if (!VisibleTypeConversionsQuals.hasRestrict() &&
8609 T.isRestrictQualified())
8610 continue;
8611 T = Q1.apply(S.Context, T);
George Burgess IVc07c3892017-06-08 18:19:25 +00008612 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008613 }
8614 }
8615 }
8616
8617 // Note that we don't consider the first argument, since it has been
8618 // contextually converted to bool long ago. The candidates below are
8619 // therefore added as binary.
8620 //
8621 // C++ [over.built]p25:
8622 // For every type T, where T is a pointer, pointer-to-member, or scoped
8623 // enumeration type, there exist candidate operator functions of the form
8624 //
8625 // T operator?(bool, T, T);
8626 //
8627 void addConditionalOperatorOverloads() {
8628 /// Set of (canonical) types that we've already handled.
8629 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8630
8631 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8632 for (BuiltinCandidateTypeSet::iterator
8633 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8634 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8635 Ptr != PtrEnd; ++Ptr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008636 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008637 continue;
8638
8639 QualType ParamTypes[2] = { *Ptr, *Ptr };
George Burgess IVc07c3892017-06-08 18:19:25 +00008640 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008641 }
8642
8643 for (BuiltinCandidateTypeSet::iterator
8644 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8645 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8646 MemPtr != MemPtrEnd; ++MemPtr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008647 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008648 continue;
8649
8650 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
George Burgess IVc07c3892017-06-08 18:19:25 +00008651 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008652 }
8653
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008654 if (S.getLangOpts().CPlusPlus11) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008655 for (BuiltinCandidateTypeSet::iterator
8656 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8657 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8658 Enum != EnumEnd; ++Enum) {
8659 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8660 continue;
8661
David Blaikie82e95a32014-11-19 07:49:47 +00008662 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008663 continue;
8664
8665 QualType ParamTypes[2] = { *Enum, *Enum };
George Burgess IVc07c3892017-06-08 18:19:25 +00008666 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008667 }
8668 }
8669 }
8670 }
8671};
8672
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008673} // end anonymous namespace
8674
8675/// AddBuiltinOperatorCandidates - Add the appropriate built-in
8676/// operator overloads to the candidate set (C++ [over.built]), based
8677/// on the operator @p Op and the arguments given. For example, if the
8678/// operator is a binary '+', this routine might add "int
8679/// operator+(int, int)" to cover integer addition.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00008680void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8681 SourceLocation OpLoc,
8682 ArrayRef<Expr *> Args,
8683 OverloadCandidateSet &CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00008684 // Find all of the types that the arguments can convert to, but only
8685 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00008686 // that make use of these types. Also record whether we encounter non-record
8687 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00008688 Qualifiers VisibleTypeConversionsQuals;
8689 VisibleTypeConversionsQuals.addConst();
Richard Smithe54c3072013-05-05 15:51:06 +00008690 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00008691 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00008692
8693 bool HasNonRecordCandidateType = false;
8694 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008695 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Richard Smithe54c3072013-05-05 15:51:06 +00008696 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Benjamin Kramer57dddd482015-02-17 21:55:18 +00008697 CandidateTypes.emplace_back(*this);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00008698 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8699 OpLoc,
8700 true,
8701 (Op == OO_Exclaim ||
8702 Op == OO_AmpAmp ||
8703 Op == OO_PipePipe),
8704 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00008705 HasNonRecordCandidateType = HasNonRecordCandidateType ||
8706 CandidateTypes[ArgIdx].hasNonRecordTypes();
8707 HasArithmeticOrEnumeralCandidateType =
8708 HasArithmeticOrEnumeralCandidateType ||
8709 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00008710 }
Douglas Gregora11693b2008-11-12 17:17:38 +00008711
Chandler Carruth00a38332010-12-13 01:44:01 +00008712 // Exit early when no non-record types have been added to the candidate set
8713 // for any of the arguments to the operator.
Douglas Gregor877d4eb2011-10-10 14:05:31 +00008714 //
8715 // We can't exit early for !, ||, or &&, since there we have always have
8716 // 'bool' overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00008717 if (!HasNonRecordCandidateType &&
Douglas Gregor877d4eb2011-10-10 14:05:31 +00008718 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth00a38332010-12-13 01:44:01 +00008719 return;
8720
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008721 // Setup an object to manage the common state for building overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00008722 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008723 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00008724 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008725 CandidateTypes, CandidateSet);
8726
8727 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00008728 switch (Op) {
8729 case OO_None:
8730 case NUM_OVERLOADED_OPERATORS:
David Blaikie83d382b2011-09-23 05:06:16 +00008731 llvm_unreachable("Expected an overloaded operator");
Douglas Gregora11693b2008-11-12 17:17:38 +00008732
Chandler Carruth5184de02010-12-12 08:51:33 +00008733 case OO_New:
8734 case OO_Delete:
8735 case OO_Array_New:
8736 case OO_Array_Delete:
8737 case OO_Call:
David Blaikie83d382b2011-09-23 05:06:16 +00008738 llvm_unreachable(
8739 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruth5184de02010-12-12 08:51:33 +00008740
8741 case OO_Comma:
8742 case OO_Arrow:
Richard Smith9f690bd2015-10-27 06:02:45 +00008743 case OO_Coawait:
Chandler Carruth5184de02010-12-12 08:51:33 +00008744 // C++ [over.match.oper]p3:
Richard Smith9f690bd2015-10-27 06:02:45 +00008745 // -- For the operator ',', the unary operator '&', the
8746 // operator '->', or the operator 'co_await', the
8747 // built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00008748 break;
8749
8750 case OO_Plus: // '+' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008751 if (Args.size() == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008752 OpBuilder.addUnaryPlusPointerOverloads();
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00008753 LLVM_FALLTHROUGH;
Douglas Gregord08452f2008-11-19 15:42:04 +00008754
8755 case OO_Minus: // '-' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008756 if (Args.size() == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008757 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008758 } else {
8759 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
George Burgess IVc07c3892017-06-08 18:19:25 +00008760 OpBuilder.addGenericBinaryArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008761 }
Douglas Gregord08452f2008-11-19 15:42:04 +00008762 break;
8763
Chandler Carruth5184de02010-12-12 08:51:33 +00008764 case OO_Star: // '*' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008765 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008766 OpBuilder.addUnaryStarPointerOverloads();
8767 else
George Burgess IVc07c3892017-06-08 18:19:25 +00008768 OpBuilder.addGenericBinaryArithmeticOverloads();
Chandler Carruth5184de02010-12-12 08:51:33 +00008769 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008770
Chandler Carruth5184de02010-12-12 08:51:33 +00008771 case OO_Slash:
George Burgess IVc07c3892017-06-08 18:19:25 +00008772 OpBuilder.addGenericBinaryArithmeticOverloads();
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008773 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008774
8775 case OO_PlusPlus:
8776 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008777 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8778 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00008779 break;
8780
Douglas Gregor84605ae2009-08-24 13:43:27 +00008781 case OO_EqualEqual:
8782 case OO_ExclaimEqual:
Richard Smith5e9746f2016-10-21 22:00:42 +00008783 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00008784 LLVM_FALLTHROUGH;
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008785
Douglas Gregora11693b2008-11-12 17:17:38 +00008786 case OO_Less:
8787 case OO_Greater:
8788 case OO_LessEqual:
8789 case OO_GreaterEqual:
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008790 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
George Burgess IVc07c3892017-06-08 18:19:25 +00008791 OpBuilder.addGenericBinaryArithmeticOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00008792 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008793
Richard Smithd30b23d2017-12-01 02:13:10 +00008794 case OO_Spaceship:
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008795 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
8796 OpBuilder.addThreeWayArithmeticOverloads();
8797 break;
Richard Smithd30b23d2017-12-01 02:13:10 +00008798
Douglas Gregora11693b2008-11-12 17:17:38 +00008799 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00008800 case OO_Caret:
8801 case OO_Pipe:
8802 case OO_LessLess:
8803 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008804 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00008805 break;
8806
Chandler Carruth5184de02010-12-12 08:51:33 +00008807 case OO_Amp: // '&' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008808 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008809 // C++ [over.match.oper]p3:
8810 // -- For the operator ',', the unary operator '&', or the
8811 // operator '->', the built-in candidates set is empty.
8812 break;
8813
8814 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8815 break;
8816
8817 case OO_Tilde:
8818 OpBuilder.addUnaryTildePromotedIntegralOverloads();
8819 break;
8820
Douglas Gregora11693b2008-11-12 17:17:38 +00008821 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008822 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00008823 LLVM_FALLTHROUGH;
Douglas Gregora11693b2008-11-12 17:17:38 +00008824
8825 case OO_PlusEqual:
8826 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008827 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00008828 LLVM_FALLTHROUGH;
Douglas Gregora11693b2008-11-12 17:17:38 +00008829
8830 case OO_StarEqual:
8831 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008832 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008833 break;
8834
8835 case OO_PercentEqual:
8836 case OO_LessLessEqual:
8837 case OO_GreaterGreaterEqual:
8838 case OO_AmpEqual:
8839 case OO_CaretEqual:
8840 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008841 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008842 break;
8843
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008844 case OO_Exclaim:
8845 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00008846 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008847
Douglas Gregora11693b2008-11-12 17:17:38 +00008848 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008849 case OO_PipePipe:
8850 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00008851 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008852
8853 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008854 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008855 break;
8856
8857 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008858 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008859 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00008860
8861 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008862 OpBuilder.addConditionalOperatorOverloads();
George Burgess IVc07c3892017-06-08 18:19:25 +00008863 OpBuilder.addGenericBinaryArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008864 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008865 }
8866}
8867
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008868/// Add function candidates found via argument-dependent lookup
Douglas Gregore254f902009-02-04 00:32:51 +00008869/// to the set of overloading candidates.
8870///
8871/// This routine performs argument-dependent name lookup based on the
8872/// given function name (which may also be an operator name) and adds
8873/// all of the overload candidates found by ADL to the overload
8874/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00008875void
Douglas Gregore254f902009-02-04 00:32:51 +00008876Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smith100b24a2014-04-17 01:52:14 +00008877 SourceLocation Loc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008878 ArrayRef<Expr *> Args,
Douglas Gregor739b107a2011-03-03 02:41:12 +00008879 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008880 OverloadCandidateSet& CandidateSet,
Richard Smithb6626742012-10-18 17:56:02 +00008881 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00008882 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00008883
John McCall91f61fc2010-01-26 06:04:06 +00008884 // FIXME: This approach for uniquing ADL results (and removing
8885 // redundant candidates from the set) relies on pointer-equality,
8886 // which means we need to key off the canonical decl. However,
8887 // always going back to the canonical decl might not get us the
8888 // right set of default arguments. What default arguments are
8889 // we supposed to consider on ADL candidates, anyway?
8890
Douglas Gregorcabea402009-09-22 15:41:20 +00008891 // FIXME: Pass in the explicit template arguments?
Richard Smith100b24a2014-04-17 01:52:14 +00008892 ArgumentDependentLookup(Name, Loc, Args, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00008893
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008894 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008895 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8896 CandEnd = CandidateSet.end();
8897 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00008898 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00008899 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00008900 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00008901 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00008902 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008903
8904 // For each of the ADL candidates we found, add it to the overload
8905 // set.
John McCall8fe68082010-01-26 07:16:45 +00008906 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00008907 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00008908 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00008909 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00008910 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008911
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008912 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8913 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00008914 } else
John McCall4c4c1df2010-01-26 03:27:55 +00008915 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00008916 FoundDecl, ExplicitTemplateArgs,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00008917 Args, CandidateSet, PartialOverloading);
Douglas Gregor15448f82009-06-27 21:05:07 +00008918 }
Douglas Gregore254f902009-02-04 00:32:51 +00008919}
8920
George Burgess IV3dc166912016-05-10 01:59:34 +00008921namespace {
8922enum class Comparison { Equal, Better, Worse };
8923}
8924
8925/// Compares the enable_if attributes of two FunctionDecls, for the purposes of
8926/// overload resolution.
8927///
8928/// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
8929/// Cand1's first N enable_if attributes have precisely the same conditions as
8930/// Cand2's first N enable_if attributes (where N = the number of enable_if
8931/// attributes on Cand2), and Cand1 has more than N enable_if attributes.
8932///
8933/// Note that you can have a pair of candidates such that Cand1's enable_if
8934/// attributes are worse than Cand2's, and Cand2's enable_if attributes are
8935/// worse than Cand1's.
8936static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
8937 const FunctionDecl *Cand2) {
8938 // Common case: One (or both) decls don't have enable_if attrs.
8939 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
8940 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
8941 if (!Cand1Attr || !Cand2Attr) {
8942 if (Cand1Attr == Cand2Attr)
8943 return Comparison::Equal;
8944 return Cand1Attr ? Comparison::Better : Comparison::Worse;
8945 }
George Burgess IV2a6150d2015-10-16 01:17:38 +00008946
Michael Krusedc5ce722018-08-03 01:21:16 +00008947 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
8948 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
George Burgess IV2a6150d2015-10-16 01:17:38 +00008949
8950 auto Cand1I = Cand1Attrs.begin();
8951 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
Michael Krusedc5ce722018-08-03 01:21:16 +00008952 for (EnableIfAttr *Cand2A : Cand2Attrs) {
George Burgess IV2a6150d2015-10-16 01:17:38 +00008953 Cand1ID.clear();
8954 Cand2ID.clear();
8955
Michael Krusedc5ce722018-08-03 01:21:16 +00008956 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
8957 // has fewer enable_if attributes than Cand2.
8958 auto Cand1A = Cand1I++;
8959 if (Cand1A == Cand1Attrs.end())
8960 return Comparison::Worse;
8961
George Burgess IV2a6150d2015-10-16 01:17:38 +00008962 Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true);
8963 Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true);
8964 if (Cand1ID != Cand2ID)
George Burgess IV3dc166912016-05-10 01:59:34 +00008965 return Comparison::Worse;
George Burgess IV2a6150d2015-10-16 01:17:38 +00008966 }
8967
George Burgess IV3dc166912016-05-10 01:59:34 +00008968 return Cand1I == Cand1Attrs.end() ? Comparison::Equal : Comparison::Better;
George Burgess IV2a6150d2015-10-16 01:17:38 +00008969}
8970
Erich Keane3efe0022018-07-20 14:13:28 +00008971static bool isBetterMultiversionCandidate(const OverloadCandidate &Cand1,
8972 const OverloadCandidate &Cand2) {
8973 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
8974 !Cand2.Function->isMultiVersion())
8975 return false;
8976
8977 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
8978 // cpu_dispatch, else arbitrarily based on the identifiers.
8979 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
8980 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
8981 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
8982 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
8983
8984 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
8985 return false;
8986
8987 if (Cand1CPUDisp && !Cand2CPUDisp)
8988 return true;
8989 if (Cand2CPUDisp && !Cand1CPUDisp)
8990 return false;
8991
8992 if (Cand1CPUSpec && Cand2CPUSpec) {
8993 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
8994 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size();
8995
8996 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
8997 FirstDiff = std::mismatch(
8998 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
8999 Cand2CPUSpec->cpus_begin(),
9000 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
9001 return LHS->getName() == RHS->getName();
9002 });
9003
9004 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
9005 "Two different cpu-specific versions should not have the same "
9006 "identifier list, otherwise they'd be the same decl!");
9007 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName();
9008 }
9009 llvm_unreachable("No way to get here unless both had cpu_dispatch");
9010}
9011
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009012/// isBetterOverloadCandidate - Determines whether the first overload
9013/// candidate is a better candidate than the second (C++ 13.3.3p1).
Richard Smith67ef14f2017-09-26 18:37:55 +00009014bool clang::isBetterOverloadCandidate(
9015 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
9016 SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009017 // Define viable functions to be better candidates than non-viable
9018 // functions.
9019 if (!Cand2.Viable)
9020 return Cand1.Viable;
9021 else if (!Cand1.Viable)
9022 return false;
9023
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009024 // C++ [over.match.best]p1:
9025 //
9026 // -- if F is a static member function, ICS1(F) is defined such
9027 // that ICS1(F) is neither better nor worse than ICS1(G) for
9028 // any function G, and, symmetrically, ICS1(G) is neither
9029 // better nor worse than ICS1(F).
9030 unsigned StartArg = 0;
9031 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
9032 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009033
George Burgess IVfbad5b22016-09-07 20:03:19 +00009034 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
9035 // We don't allow incompatible pointer conversions in C++.
9036 if (!S.getLangOpts().CPlusPlus)
9037 return ICS.isStandard() &&
9038 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
9039
9040 // The only ill-formed conversion we allow in C++ is the string literal to
9041 // char* conversion, which is only considered ill-formed after C++11.
9042 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
9043 hasDeprecatedStringLiteralToCharPtrConversion(ICS);
9044 };
9045
9046 // Define functions that don't require ill-formed conversions for a given
9047 // argument to be better candidates than functions that do.
Richard Smith6eedfe72017-01-09 08:01:21 +00009048 unsigned NumArgs = Cand1.Conversions.size();
9049 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
George Burgess IVfbad5b22016-09-07 20:03:19 +00009050 bool HasBetterConversion = false;
9051 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9052 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
9053 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
9054 if (Cand1Bad != Cand2Bad) {
9055 if (Cand1Bad)
9056 return false;
9057 HasBetterConversion = true;
9058 }
9059 }
9060
9061 if (HasBetterConversion)
9062 return true;
9063
Douglas Gregord3cb3562009-07-07 23:38:56 +00009064 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00009065 // A viable function F1 is defined to be a better function than another
9066 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00009067 // conversion sequence than ICSi(F2), and then...
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009068 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Richard Smith0f59cb32015-12-18 21:45:41 +00009069 switch (CompareImplicitConversionSequences(S, Loc,
John McCall5c32be02010-08-24 20:38:10 +00009070 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009071 Cand2.Conversions[ArgIdx])) {
9072 case ImplicitConversionSequence::Better:
9073 // Cand1 has a better conversion sequence.
9074 HasBetterConversion = true;
9075 break;
9076
9077 case ImplicitConversionSequence::Worse:
9078 // Cand1 can't be better than Cand2.
9079 return false;
9080
9081 case ImplicitConversionSequence::Indistinguishable:
9082 // Do nothing.
9083 break;
9084 }
9085 }
9086
Mike Stump11289f42009-09-09 15:08:12 +00009087 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00009088 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009089 if (HasBetterConversion)
9090 return true;
9091
Douglas Gregora1f013e2008-11-07 22:36:19 +00009092 // -- the context is an initialization by user-defined conversion
9093 // (see 8.5, 13.3.1.5) and the standard conversion sequence
9094 // from the return type of F1 to the destination type (i.e.,
9095 // the type of the entity being initialized) is a better
9096 // conversion sequence than the standard conversion sequence
9097 // from the return type of F2 to the destination type.
Richard Smith67ef14f2017-09-26 18:37:55 +00009098 if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
9099 Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00009100 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00009101 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregor2837aa22012-02-22 17:32:19 +00009102 // First check whether we prefer one of the conversion functions over the
9103 // other. This only distinguishes the results in non-standard, extension
9104 // cases such as the conversion from a lambda closure type to a function
9105 // pointer or block.
Richard Smithec2748a2014-05-17 04:36:39 +00009106 ImplicitConversionSequence::CompareKind Result =
9107 compareConversionFunctions(S, Cand1.Function, Cand2.Function);
9108 if (Result == ImplicitConversionSequence::Indistinguishable)
Richard Smith0f59cb32015-12-18 21:45:41 +00009109 Result = CompareStandardConversionSequences(S, Loc,
Richard Smithec2748a2014-05-17 04:36:39 +00009110 Cand1.FinalConversion,
9111 Cand2.FinalConversion);
Richard Smith6fdeaab2014-05-17 01:58:45 +00009112
Richard Smithec2748a2014-05-17 04:36:39 +00009113 if (Result != ImplicitConversionSequence::Indistinguishable)
9114 return Result == ImplicitConversionSequence::Better;
Richard Smith6fdeaab2014-05-17 01:58:45 +00009115
9116 // FIXME: Compare kind of reference binding if conversion functions
9117 // convert to a reference type used in direct reference binding, per
9118 // C++14 [over.match.best]p1 section 2 bullet 3.
9119 }
9120
Richard Smith51731362017-11-01 01:37:11 +00009121 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
9122 // as combined with the resolution to CWG issue 243.
9123 //
9124 // When the context is initialization by constructor ([over.match.ctor] or
9125 // either phase of [over.match.list]), a constructor is preferred over
9126 // a conversion function.
9127 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
9128 Cand1.Function && Cand2.Function &&
9129 isa<CXXConstructorDecl>(Cand1.Function) !=
9130 isa<CXXConstructorDecl>(Cand2.Function))
9131 return isa<CXXConstructorDecl>(Cand1.Function);
9132
Richard Smith6fdeaab2014-05-17 01:58:45 +00009133 // -- F1 is a non-template function and F2 is a function template
9134 // specialization, or, if not that,
9135 bool Cand1IsSpecialization = Cand1.Function &&
9136 Cand1.Function->getPrimaryTemplate();
9137 bool Cand2IsSpecialization = Cand2.Function &&
9138 Cand2.Function->getPrimaryTemplate();
9139 if (Cand1IsSpecialization != Cand2IsSpecialization)
9140 return Cand2IsSpecialization;
9141
9142 // -- F1 and F2 are function template specializations, and the function
9143 // template for F1 is more specialized than the template for F2
9144 // according to the partial ordering rules described in 14.5.5.2, or,
9145 // if not that,
9146 if (Cand1IsSpecialization && Cand2IsSpecialization) {
9147 if (FunctionTemplateDecl *BetterTemplate
9148 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
9149 Cand2.Function->getPrimaryTemplate(),
9150 Loc,
9151 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
9152 : TPOC_Call,
9153 Cand1.ExplicitCallArguments,
9154 Cand2.ExplicitCallArguments))
9155 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregora1f013e2008-11-07 22:36:19 +00009156 }
9157
Richard Smith5179eb72016-06-28 19:03:57 +00009158 // FIXME: Work around a defect in the C++17 inheriting constructor wording.
9159 // A derived-class constructor beats an (inherited) base class constructor.
9160 bool Cand1IsInherited =
9161 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
9162 bool Cand2IsInherited =
9163 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
9164 if (Cand1IsInherited != Cand2IsInherited)
9165 return Cand2IsInherited;
9166 else if (Cand1IsInherited) {
9167 assert(Cand2IsInherited);
9168 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
9169 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
9170 if (Cand1Class->isDerivedFrom(Cand2Class))
9171 return true;
9172 if (Cand2Class->isDerivedFrom(Cand1Class))
9173 return false;
9174 // Inherited from sibling base classes: still ambiguous.
9175 }
9176
Faisal Vali81b756e2017-10-22 14:45:08 +00009177 // Check C++17 tie-breakers for deduction guides.
9178 {
9179 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
9180 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
9181 if (Guide1 && Guide2) {
9182 // -- F1 is generated from a deduction-guide and F2 is not
9183 if (Guide1->isImplicit() != Guide2->isImplicit())
9184 return Guide2->isImplicit();
9185
9186 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
9187 if (Guide1->isCopyDeductionCandidate())
9188 return true;
9189 }
9190 }
Richard Smith67ef14f2017-09-26 18:37:55 +00009191
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009192 // Check for enable_if value-based overload resolution.
George Burgess IV3dc166912016-05-10 01:59:34 +00009193 if (Cand1.Function && Cand2.Function) {
9194 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
9195 if (Cmp != Comparison::Equal)
9196 return Cmp == Comparison::Better;
9197 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009198
Justin Lebar25c4a812016-03-29 16:24:16 +00009199 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
Artem Belevich94a55e82015-09-22 17:22:59 +00009200 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9201 return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
9202 S.IdentifyCUDAPreference(Caller, Cand2.Function);
9203 }
9204
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009205 bool HasPS1 = Cand1.Function != nullptr &&
9206 functionHasPassObjectSizeParams(Cand1.Function);
9207 bool HasPS2 = Cand2.Function != nullptr &&
9208 functionHasPassObjectSizeParams(Cand2.Function);
Erich Keane3efe0022018-07-20 14:13:28 +00009209 if (HasPS1 != HasPS2 && HasPS1)
9210 return true;
9211
9212 return isBetterMultiversionCandidate(Cand1, Cand2);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009213}
9214
Richard Smith2dbe4042015-11-04 19:26:32 +00009215/// Determine whether two declarations are "equivalent" for the purposes of
Richard Smith26210db2015-11-13 03:52:13 +00009216/// name lookup and overload resolution. This applies when the same internal/no
9217/// linkage entity is defined by two modules (probably by textually including
Richard Smith2dbe4042015-11-04 19:26:32 +00009218/// the same header). In such a case, we don't consider the declarations to
9219/// declare the same entity, but we also don't want lookups with both
9220/// declarations visible to be ambiguous in some cases (this happens when using
9221/// a modularized libstdc++).
9222bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
9223 const NamedDecl *B) {
Richard Smith26210db2015-11-13 03:52:13 +00009224 auto *VA = dyn_cast_or_null<ValueDecl>(A);
9225 auto *VB = dyn_cast_or_null<ValueDecl>(B);
9226 if (!VA || !VB)
9227 return false;
9228
9229 // The declarations must be declaring the same name as an internal linkage
9230 // entity in different modules.
9231 if (!VA->getDeclContext()->getRedeclContext()->Equals(
9232 VB->getDeclContext()->getRedeclContext()) ||
9233 getOwningModule(const_cast<ValueDecl *>(VA)) ==
9234 getOwningModule(const_cast<ValueDecl *>(VB)) ||
9235 VA->isExternallyVisible() || VB->isExternallyVisible())
9236 return false;
9237
9238 // Check that the declarations appear to be equivalent.
9239 //
9240 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
9241 // For constants and functions, we should check the initializer or body is
9242 // the same. For non-constant variables, we shouldn't allow it at all.
9243 if (Context.hasSameType(VA->getType(), VB->getType()))
9244 return true;
9245
9246 // Enum constants within unnamed enumerations will have different types, but
9247 // may still be similar enough to be interchangeable for our purposes.
9248 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
9249 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
9250 // Only handle anonymous enums. If the enumerations were named and
9251 // equivalent, they would have been merged to the same type.
9252 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
9253 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
9254 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
9255 !Context.hasSameType(EnumA->getIntegerType(),
9256 EnumB->getIntegerType()))
9257 return false;
9258 // Allow this only if the value is the same for both enumerators.
9259 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
9260 }
9261 }
9262
9263 // Nothing else is sufficiently similar.
9264 return false;
Richard Smith2dbe4042015-11-04 19:26:32 +00009265}
9266
9267void Sema::diagnoseEquivalentInternalLinkageDeclarations(
9268 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
9269 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
9270
9271 Module *M = getOwningModule(const_cast<NamedDecl*>(D));
9272 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
9273 << !M << (M ? M->getFullModuleName() : "");
9274
9275 for (auto *E : Equiv) {
9276 Module *M = getOwningModule(const_cast<NamedDecl*>(E));
9277 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
9278 << !M << (M ? M->getFullModuleName() : "");
9279 }
Richard Smith896c66e2015-10-21 07:13:52 +00009280}
9281
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009282/// Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009283/// within an overload candidate set.
9284///
James Dennettffad8b72012-06-22 08:10:18 +00009285/// \param Loc The location of the function name (or operator symbol) for
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009286/// which overload resolution occurs.
9287///
James Dennettffad8b72012-06-22 08:10:18 +00009288/// \param Best If overload resolution was successful or found a deleted
9289/// function, \p Best points to the candidate function found.
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009290///
9291/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00009292OverloadingResult
9293OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Richard Smith67ef14f2017-09-26 18:37:55 +00009294 iterator &Best) {
Artem Belevich18609102016-02-12 18:29:18 +00009295 llvm::SmallVector<OverloadCandidate *, 16> Candidates;
9296 std::transform(begin(), end(), std::back_inserter(Candidates),
9297 [](OverloadCandidate &Cand) { return &Cand; });
9298
Justin Lebar66a2ab92016-08-10 00:40:43 +00009299 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
9300 // are accepted by both clang and NVCC. However, during a particular
Artem Belevich18609102016-02-12 18:29:18 +00009301 // compilation mode only one call variant is viable. We need to
9302 // exclude non-viable overload candidates from consideration based
9303 // only on their host/device attributes. Specifically, if one
9304 // candidate call is WrongSide and the other is SameSide, we ignore
9305 // the WrongSide candidate.
Justin Lebar25c4a812016-03-29 16:24:16 +00009306 if (S.getLangOpts().CUDA) {
Artem Belevich18609102016-02-12 18:29:18 +00009307 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9308 bool ContainsSameSideCandidate =
9309 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
9310 return Cand->Function &&
9311 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9312 Sema::CFP_SameSide;
9313 });
9314 if (ContainsSameSideCandidate) {
9315 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
9316 return Cand->Function &&
9317 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9318 Sema::CFP_WrongSide;
9319 };
George Burgess IV8684b032017-01-04 19:16:29 +00009320 llvm::erase_if(Candidates, IsWrongSideCandidate);
Artem Belevich18609102016-02-12 18:29:18 +00009321 }
9322 }
9323
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009324 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00009325 Best = end();
Artem Belevich18609102016-02-12 18:29:18 +00009326 for (auto *Cand : Candidates)
John McCall5c32be02010-08-24 20:38:10 +00009327 if (Cand->Viable)
Richard Smith67ef14f2017-09-26 18:37:55 +00009328 if (Best == end() ||
9329 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009330 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009331
9332 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00009333 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009334 return OR_No_Viable_Function;
9335
Richard Smith2dbe4042015-11-04 19:26:32 +00009336 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
Richard Smith896c66e2015-10-21 07:13:52 +00009337
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009338 // Make sure that this function is better than every other viable
9339 // function. If not, we have an ambiguity.
Artem Belevich18609102016-02-12 18:29:18 +00009340 for (auto *Cand : Candidates) {
Richard Smith67ef14f2017-09-26 18:37:55 +00009341 if (Cand->Viable && Cand != Best &&
9342 !isBetterOverloadCandidate(S, *Best, *Cand, Loc, Kind)) {
Richard Smith2dbe4042015-11-04 19:26:32 +00009343 if (S.isEquivalentInternalLinkageDeclaration(Best->Function,
9344 Cand->Function)) {
9345 EquivalentCands.push_back(Cand->Function);
Richard Smith896c66e2015-10-21 07:13:52 +00009346 continue;
9347 }
9348
John McCall5c32be02010-08-24 20:38:10 +00009349 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009350 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00009351 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009352 }
Mike Stump11289f42009-09-09 15:08:12 +00009353
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009354 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00009355 if (Best->Function &&
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00009356 (Best->Function->isDeleted() ||
George Burgess IVce6284b2017-01-28 02:19:40 +00009357 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor171c45a2009-02-18 21:56:37 +00009358 return OR_Deleted;
9359
Richard Smith2dbe4042015-11-04 19:26:32 +00009360 if (!EquivalentCands.empty())
9361 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
9362 EquivalentCands);
Richard Smith896c66e2015-10-21 07:13:52 +00009363
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009364 return OR_Success;
9365}
9366
John McCall53262c92010-01-12 02:15:36 +00009367namespace {
9368
9369enum OverloadCandidateKind {
9370 oc_function,
9371 oc_method,
9372 oc_constructor,
9373 oc_implicit_default_constructor,
9374 oc_implicit_copy_constructor,
Alexis Hunt119c10e2011-05-25 23:16:36 +00009375 oc_implicit_move_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00009376 oc_implicit_copy_assignment,
Alexis Hunt119c10e2011-05-25 23:16:36 +00009377 oc_implicit_move_assignment,
Eric Fiselier92e523b2018-05-30 01:00:41 +00009378 oc_inherited_constructor
John McCall53262c92010-01-12 02:15:36 +00009379};
9380
Eric Fiselier92e523b2018-05-30 01:00:41 +00009381enum OverloadCandidateSelect {
9382 ocs_non_template,
9383 ocs_template,
9384 ocs_described_template,
9385};
9386
9387static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
George Burgess IVd66d37c2016-10-28 21:42:06 +00009388ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
9389 std::string &Description) {
John McCalle1ac8d12010-01-13 00:25:19 +00009390
Eric Fiselier92e523b2018-05-30 01:00:41 +00009391 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
John McCalle1ac8d12010-01-13 00:25:19 +00009392 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
9393 isTemplate = true;
9394 Description = S.getTemplateArgumentBindingsText(
Eric Fiselier92e523b2018-05-30 01:00:41 +00009395 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
John McCalle1ac8d12010-01-13 00:25:19 +00009396 }
John McCallfd0b2f82010-01-06 09:43:14 +00009397
Eric Fiselier92e523b2018-05-30 01:00:41 +00009398 OverloadCandidateSelect Select = [&]() {
9399 if (!Description.empty())
9400 return ocs_described_template;
9401 return isTemplate ? ocs_template : ocs_non_template;
9402 }();
9403
9404 OverloadCandidateKind Kind = [&]() {
9405 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
9406 if (!Ctor->isImplicit()) {
9407 if (isa<ConstructorUsingShadowDecl>(Found))
9408 return oc_inherited_constructor;
9409 else
9410 return oc_constructor;
9411 }
9412
9413 if (Ctor->isDefaultConstructor())
9414 return oc_implicit_default_constructor;
9415
9416 if (Ctor->isMoveConstructor())
9417 return oc_implicit_move_constructor;
9418
9419 assert(Ctor->isCopyConstructor() &&
9420 "unexpected sort of implicit constructor");
9421 return oc_implicit_copy_constructor;
Richard Smith5179eb72016-06-28 19:03:57 +00009422 }
Sebastian Redl08905022011-02-05 19:23:19 +00009423
Eric Fiselier92e523b2018-05-30 01:00:41 +00009424 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
9425 // This actually gets spelled 'candidate function' for now, but
9426 // it doesn't hurt to split it out.
9427 if (!Meth->isImplicit())
9428 return oc_method;
Alexis Hunt119c10e2011-05-25 23:16:36 +00009429
Eric Fiselier92e523b2018-05-30 01:00:41 +00009430 if (Meth->isMoveAssignmentOperator())
9431 return oc_implicit_move_assignment;
Alexis Hunt119c10e2011-05-25 23:16:36 +00009432
Eric Fiselier92e523b2018-05-30 01:00:41 +00009433 if (Meth->isCopyAssignmentOperator())
9434 return oc_implicit_copy_assignment;
John McCallfd0b2f82010-01-06 09:43:14 +00009435
Eric Fiselier92e523b2018-05-30 01:00:41 +00009436 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
9437 return oc_method;
9438 }
John McCallfd0b2f82010-01-06 09:43:14 +00009439
Eric Fiselier92e523b2018-05-30 01:00:41 +00009440 return oc_function;
9441 }();
Alexis Hunt119c10e2011-05-25 23:16:36 +00009442
Eric Fiselier92e523b2018-05-30 01:00:41 +00009443 return std::make_pair(Kind, Select);
John McCall53262c92010-01-12 02:15:36 +00009444}
9445
Richard Smith5179eb72016-06-28 19:03:57 +00009446void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
9447 // FIXME: It'd be nice to only emit a note once per using-decl per overload
9448 // set.
9449 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
9450 S.Diag(FoundDecl->getLocation(),
9451 diag::note_ovl_candidate_inherited_constructor)
9452 << Shadow->getNominatedBaseClass();
Sebastian Redl08905022011-02-05 19:23:19 +00009453}
9454
John McCall53262c92010-01-12 02:15:36 +00009455} // end anonymous namespace
9456
George Burgess IV5f21c712015-10-12 19:57:04 +00009457static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
9458 const FunctionDecl *FD) {
9459 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
9460 bool AlwaysTrue;
9461 if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
9462 return false;
9463 if (!AlwaysTrue)
9464 return false;
9465 }
9466 return true;
9467}
9468
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009469/// Returns true if we can take the address of the function.
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009470///
9471/// \param Complain - If true, we'll emit a diagnostic
9472/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
9473/// we in overload resolution?
9474/// \param Loc - The location of the statement we're complaining about. Ignored
9475/// if we're not complaining, or if we're in overload resolution.
9476static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
9477 bool Complain,
9478 bool InOverloadResolution,
9479 SourceLocation Loc) {
9480 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
9481 if (Complain) {
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009482 if (InOverloadResolution)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009483 S.Diag(FD->getBeginLoc(),
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009484 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
9485 else
9486 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
9487 }
9488 return false;
9489 }
9490
George Burgess IV21081362016-07-24 23:12:40 +00009491 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
9492 return P->hasAttr<PassObjectSizeAttr>();
9493 });
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009494 if (I == FD->param_end())
9495 return true;
9496
9497 if (Complain) {
9498 // Add one to ParamNo because it's user-facing
9499 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
9500 if (InOverloadResolution)
9501 S.Diag(FD->getLocation(),
9502 diag::note_ovl_candidate_has_pass_object_size_params)
9503 << ParamNo;
9504 else
9505 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
9506 << FD << ParamNo;
9507 }
9508 return false;
9509}
9510
9511static bool checkAddressOfCandidateIsAvailable(Sema &S,
9512 const FunctionDecl *FD) {
9513 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
9514 /*InOverloadResolution=*/true,
9515 /*Loc=*/SourceLocation());
9516}
9517
9518bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
9519 bool Complain,
9520 SourceLocation Loc) {
9521 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
9522 /*InOverloadResolution=*/false,
9523 Loc);
9524}
9525
John McCall53262c92010-01-12 02:15:36 +00009526// Notes the location of an overload candidate.
Richard Smithc2bebe92016-05-11 20:37:46 +00009527void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
9528 QualType DestType, bool TakingAddress) {
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009529 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
9530 return;
Erich Keane3efe0022018-07-20 14:13:28 +00009531 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
9532 !Fn->getAttr<TargetAttr>()->isDefaultVersion())
Erich Keane281d20b2018-01-08 21:34:17 +00009533 return;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009534
John McCalle1ac8d12010-01-13 00:25:19 +00009535 std::string FnDesc;
Eric Fiselier92e523b2018-05-30 01:00:41 +00009536 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
9537 ClassifyOverloadCandidate(*this, Found, Fn, FnDesc);
Richard Trieucaff2472011-11-23 22:32:32 +00009538 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
Eric Fiselier92e523b2018-05-30 01:00:41 +00009539 << (unsigned)KSPair.first << (unsigned)KSPair.second
9540 << Fn << FnDesc;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009541
9542 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
Richard Trieucaff2472011-11-23 22:32:32 +00009543 Diag(Fn->getLocation(), PD);
Richard Smith5179eb72016-06-28 19:03:57 +00009544 MaybeEmitInheritedConstructorNote(*this, Found);
John McCallfd0b2f82010-01-06 09:43:14 +00009545}
9546
Nick Lewyckyed4265c2013-09-22 10:06:01 +00009547// Notes the location of all overload candidates designated through
Douglas Gregorb491ed32011-02-19 21:32:49 +00009548// OverloadedExpr
George Burgess IV5f21c712015-10-12 19:57:04 +00009549void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
9550 bool TakingAddress) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009551 assert(OverloadedExpr->getType() == Context.OverloadTy);
9552
9553 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
9554 OverloadExpr *OvlExpr = Ovl.Expression;
9555
9556 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00009557 IEnd = OvlExpr->decls_end();
Douglas Gregorb491ed32011-02-19 21:32:49 +00009558 I != IEnd; ++I) {
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00009559 if (FunctionTemplateDecl *FunTmpl =
Douglas Gregorb491ed32011-02-19 21:32:49 +00009560 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Smithc2bebe92016-05-11 20:37:46 +00009561 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType,
George Burgess IV5f21c712015-10-12 19:57:04 +00009562 TakingAddress);
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00009563 } else if (FunctionDecl *Fun
Douglas Gregorb491ed32011-02-19 21:32:49 +00009564 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Smithc2bebe92016-05-11 20:37:46 +00009565 NoteOverloadCandidate(*I, Fun, DestType, TakingAddress);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009566 }
9567 }
9568}
9569
John McCall0d1da222010-01-12 00:44:57 +00009570/// Diagnoses an ambiguous conversion. The partial diagnostic is the
9571/// "lead" diagnostic; it will be given two arguments, the source and
9572/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00009573void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
9574 Sema &S,
9575 SourceLocation CaretLoc,
9576 const PartialDiagnostic &PDiag) const {
9577 S.Diag(CaretLoc, PDiag)
9578 << Ambiguous.getFromType() << Ambiguous.getToType();
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00009579 // FIXME: The note limiting machinery is borrowed from
9580 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
9581 // refactoring here.
9582 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9583 unsigned CandsShown = 0;
9584 AmbiguousConversionSequence::const_iterator I, E;
9585 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
9586 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9587 break;
9588 ++CandsShown;
Richard Smithc2bebe92016-05-11 20:37:46 +00009589 S.NoteOverloadCandidate(I->first, I->second);
John McCall0d1da222010-01-12 00:44:57 +00009590 }
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00009591 if (I != E)
9592 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
John McCall12f97bc2010-01-08 04:41:39 +00009593}
9594
Richard Smith17c00b42014-11-12 01:24:00 +00009595static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009596 unsigned I, bool TakingCandidateAddress) {
John McCall6a61b522010-01-13 09:16:55 +00009597 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
9598 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00009599 assert(Cand->Function && "for now, candidate must be a function");
9600 FunctionDecl *Fn = Cand->Function;
9601
9602 // There's a conversion slot for the object argument if this is a
9603 // non-constructor method. Note that 'I' corresponds the
9604 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00009605 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00009606 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00009607 if (I == 0)
9608 isObjectArgument = true;
9609 else
9610 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00009611 }
9612
John McCalle1ac8d12010-01-13 00:25:19 +00009613 std::string FnDesc;
Eric Fiselier92e523b2018-05-30 01:00:41 +00009614 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
Richard Smithc2bebe92016-05-11 20:37:46 +00009615 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
John McCalle1ac8d12010-01-13 00:25:19 +00009616
John McCall6a61b522010-01-13 09:16:55 +00009617 Expr *FromExpr = Conv.Bad.FromExpr;
9618 QualType FromTy = Conv.Bad.getFromType();
9619 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00009620
John McCallfb7ad0f2010-02-02 02:42:52 +00009621 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00009622 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00009623 Expr *E = FromExpr->IgnoreParens();
9624 if (isa<UnaryOperator>(E))
9625 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00009626 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00009627
9628 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
Eric Fiselier92e523b2018-05-30 01:00:41 +00009629 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9630 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy
9631 << Name << I + 1;
Richard Smith5179eb72016-06-28 19:03:57 +00009632 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCallfb7ad0f2010-02-02 02:42:52 +00009633 return;
9634 }
9635
John McCall6d174642010-01-23 08:10:49 +00009636 // Do some hand-waving analysis to see if the non-viability is due
9637 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00009638 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
9639 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
9640 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
9641 CToTy = RT->getPointeeType();
9642 else {
9643 // TODO: detect and diagnose the full richness of const mismatches.
9644 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
Richard Trieucc3949d2016-02-18 22:34:54 +00009645 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
9646 CFromTy = FromPT->getPointeeType();
9647 CToTy = ToPT->getPointeeType();
9648 }
John McCall47000992010-01-14 03:28:57 +00009649 }
9650
9651 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
9652 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall47000992010-01-14 03:28:57 +00009653 Qualifiers FromQs = CFromTy.getQualifiers();
9654 Qualifiers ToQs = CToTy.getQualifiers();
9655
9656 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
9657 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
Eric Fiselier92e523b2018-05-30 01:00:41 +00009658 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9659 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
Anastasia Stulovabf549bf2018-06-22 15:45:08 +00009660 << ToTy << (unsigned)isObjectArgument << I + 1;
Richard Smith5179eb72016-06-28 19:03:57 +00009661 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall47000992010-01-14 03:28:57 +00009662 return;
9663 }
9664
John McCall31168b02011-06-15 23:02:42 +00009665 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00009666 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
Eric Fiselier92e523b2018-05-30 01:00:41 +00009667 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9668 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9669 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
9670 << (unsigned)isObjectArgument << I + 1;
Richard Smith5179eb72016-06-28 19:03:57 +00009671 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall31168b02011-06-15 23:02:42 +00009672 return;
9673 }
9674
Douglas Gregoraec25842011-04-26 23:16:46 +00009675 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
9676 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
Eric Fiselier92e523b2018-05-30 01:00:41 +00009677 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9678 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9679 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
9680 << (unsigned)isObjectArgument << I + 1;
Richard Smith5179eb72016-06-28 19:03:57 +00009681 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Douglas Gregoraec25842011-04-26 23:16:46 +00009682 return;
9683 }
9684
Andrey Bokhanko45d41322016-05-11 18:38:21 +00009685 if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
9686 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
Eric Fiselier92e523b2018-05-30 01:00:41 +00009687 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9688 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9689 << FromQs.hasUnaligned() << I + 1;
Richard Smith5179eb72016-06-28 19:03:57 +00009690 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Andrey Bokhanko45d41322016-05-11 18:38:21 +00009691 return;
9692 }
9693
John McCall47000992010-01-14 03:28:57 +00009694 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
9695 assert(CVR && "unexpected qualifiers mismatch");
9696
9697 if (isObjectArgument) {
9698 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
Eric Fiselier92e523b2018-05-30 01:00:41 +00009699 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9700 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9701 << (CVR - 1);
John McCall47000992010-01-14 03:28:57 +00009702 } else {
9703 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
Eric Fiselier92e523b2018-05-30 01:00:41 +00009704 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9705 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9706 << (CVR - 1) << I + 1;
John McCall47000992010-01-14 03:28:57 +00009707 }
Richard Smith5179eb72016-06-28 19:03:57 +00009708 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall47000992010-01-14 03:28:57 +00009709 return;
9710 }
9711
Sebastian Redla72462c2011-09-24 17:48:32 +00009712 // Special diagnostic for failure to convert an initializer list, since
9713 // telling the user that it has type void is not useful.
9714 if (FromExpr && isa<InitListExpr>(FromExpr)) {
9715 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
Eric Fiselier92e523b2018-05-30 01:00:41 +00009716 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9717 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9718 << ToTy << (unsigned)isObjectArgument << I + 1;
Richard Smith5179eb72016-06-28 19:03:57 +00009719 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Sebastian Redla72462c2011-09-24 17:48:32 +00009720 return;
9721 }
9722
John McCall6d174642010-01-23 08:10:49 +00009723 // Diagnose references or pointers to incomplete types differently,
9724 // since it's far from impossible that the incompleteness triggered
9725 // the failure.
9726 QualType TempFromTy = FromTy.getNonReferenceType();
9727 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
9728 TempFromTy = PTy->getPointeeType();
9729 if (TempFromTy->isIncompleteType()) {
David Blaikieac928932016-03-04 22:29:11 +00009730 // Emit the generic diagnostic and, optionally, add the hints to it.
John McCall6d174642010-01-23 08:10:49 +00009731 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
Eric Fiselier92e523b2018-05-30 01:00:41 +00009732 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9733 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9734 << ToTy << (unsigned)isObjectArgument << I + 1
9735 << (unsigned)(Cand->Fix.Kind);
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00009736
Richard Smith5179eb72016-06-28 19:03:57 +00009737 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall6d174642010-01-23 08:10:49 +00009738 return;
9739 }
9740
Douglas Gregor56f2e342010-06-30 23:01:39 +00009741 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009742 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00009743 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
9744 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
9745 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9746 FromPtrTy->getPointeeType()) &&
9747 !FromPtrTy->getPointeeType()->isIncompleteType() &&
9748 !ToPtrTy->getPointeeType()->isIncompleteType() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00009749 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00009750 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009751 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00009752 }
9753 } else if (const ObjCObjectPointerType *FromPtrTy
9754 = FromTy->getAs<ObjCObjectPointerType>()) {
9755 if (const ObjCObjectPointerType *ToPtrTy
9756 = ToTy->getAs<ObjCObjectPointerType>())
9757 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
9758 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
9759 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9760 FromPtrTy->getPointeeType()) &&
9761 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009762 BaseToDerivedConversion = 2;
9763 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009764 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
9765 !FromTy->isIncompleteType() &&
9766 !ToRefTy->getPointeeType()->isIncompleteType() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00009767 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009768 BaseToDerivedConversion = 3;
9769 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
9770 ToTy.getNonReferenceType().getCanonicalType() ==
9771 FromTy.getNonReferenceType().getCanonicalType()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009772 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
Eric Fiselier92e523b2018-05-30 01:00:41 +00009773 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9774 << (unsigned)isObjectArgument << I + 1
9775 << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
Richard Smith5179eb72016-06-28 19:03:57 +00009776 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009777 return;
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009778 }
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009779 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009780
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009781 if (BaseToDerivedConversion) {
Eric Fiselier92e523b2018-05-30 01:00:41 +00009782 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
9783 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9784 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9785 << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1;
Richard Smith5179eb72016-06-28 19:03:57 +00009786 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Douglas Gregor56f2e342010-06-30 23:01:39 +00009787 return;
9788 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009789
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00009790 if (isa<ObjCObjectPointerType>(CFromTy) &&
9791 isa<PointerType>(CToTy)) {
9792 Qualifiers FromQs = CFromTy.getQualifiers();
9793 Qualifiers ToQs = CToTy.getQualifiers();
9794 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9795 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
Eric Fiselier92e523b2018-05-30 01:00:41 +00009796 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
9797 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9798 << FromTy << ToTy << (unsigned)isObjectArgument << I + 1;
Richard Smith5179eb72016-06-28 19:03:57 +00009799 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00009800 return;
9801 }
9802 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009803
9804 if (TakingCandidateAddress &&
9805 !checkAddressOfCandidateIsAvailable(S, Cand->Function))
9806 return;
9807
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009808 // Emit the generic diagnostic and, optionally, add the hints to it.
9809 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
Eric Fiselier92e523b2018-05-30 01:00:41 +00009810 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9811 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9812 << ToTy << (unsigned)isObjectArgument << I + 1
9813 << (unsigned)(Cand->Fix.Kind);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009814
9815 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer490afa62012-01-14 21:05:10 +00009816 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
9817 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009818 FDiag << *HI;
9819 S.Diag(Fn->getLocation(), FDiag);
9820
Richard Smith5179eb72016-06-28 19:03:57 +00009821 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall6a61b522010-01-13 09:16:55 +00009822}
9823
Larisse Voufo98b20f12013-07-19 23:00:19 +00009824/// Additional arity mismatch diagnosis specific to a function overload
9825/// candidates. This is not covered by the more general DiagnoseArityMismatch()
9826/// over a candidate in any candidate set.
Richard Smith17c00b42014-11-12 01:24:00 +00009827static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
9828 unsigned NumArgs) {
John McCall6a61b522010-01-13 09:16:55 +00009829 FunctionDecl *Fn = Cand->Function;
John McCall6a61b522010-01-13 09:16:55 +00009830 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009831
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009832 // With invalid overloaded operators, it's possible that we think we
Larisse Voufo98b20f12013-07-19 23:00:19 +00009833 // have an arity mismatch when in fact it looks like we have the
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009834 // right number of arguments, because only overloaded operators have
9835 // the weird behavior of overloading member and non-member functions.
9836 // Just don't report anything.
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00009837 if (Fn->isInvalidDecl() &&
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009838 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009839 return true;
9840
9841 if (NumArgs < MinParams) {
9842 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
9843 (Cand->FailureKind == ovl_fail_bad_deduction &&
9844 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
9845 } else {
9846 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
9847 (Cand->FailureKind == ovl_fail_bad_deduction &&
9848 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
9849 }
9850
9851 return false;
9852}
9853
9854/// General arity mismatch diagnosis over a candidate in a candidate set.
Richard Smithc2bebe92016-05-11 20:37:46 +00009855static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
9856 unsigned NumFormalArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009857 assert(isa<FunctionDecl>(D) &&
9858 "The templated declaration should at least be a function"
9859 " when diagnosing bad template argument deduction due to too many"
9860 " or too few arguments");
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00009861
Larisse Voufo98b20f12013-07-19 23:00:19 +00009862 FunctionDecl *Fn = cast<FunctionDecl>(D);
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00009863
Larisse Voufo98b20f12013-07-19 23:00:19 +00009864 // TODO: treat calls to a missing default constructor as a special case
9865 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
9866 unsigned MinParams = Fn->getMinRequiredArguments();
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009867
John McCall6a61b522010-01-13 09:16:55 +00009868 // at least / at most / exactly
9869 unsigned mode, modeCount;
9870 if (NumFormalArgs < MinParams) {
Alp Toker9cacbab2014-01-20 20:26:09 +00009871 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
9872 FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00009873 mode = 0; // "at least"
9874 else
9875 mode = 2; // "exactly"
9876 modeCount = MinParams;
9877 } else {
Alp Toker9cacbab2014-01-20 20:26:09 +00009878 if (MinParams != FnTy->getNumParams())
John McCall6a61b522010-01-13 09:16:55 +00009879 mode = 1; // "at most"
9880 else
9881 mode = 2; // "exactly"
Alp Toker9cacbab2014-01-20 20:26:09 +00009882 modeCount = FnTy->getNumParams();
John McCall6a61b522010-01-13 09:16:55 +00009883 }
9884
9885 std::string Description;
Eric Fiselier92e523b2018-05-30 01:00:41 +00009886 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
Richard Smithc2bebe92016-05-11 20:37:46 +00009887 ClassifyOverloadCandidate(S, Found, Fn, Description);
John McCall6a61b522010-01-13 09:16:55 +00009888
Richard Smith10ff50d2012-05-11 05:16:41 +00009889 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
9890 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
Eric Fiselier92e523b2018-05-30 01:00:41 +00009891 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
9892 << Description << mode << Fn->getParamDecl(0) << NumFormalArgs;
Richard Smith10ff50d2012-05-11 05:16:41 +00009893 else
9894 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Eric Fiselier92e523b2018-05-30 01:00:41 +00009895 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
9896 << Description << mode << modeCount << NumFormalArgs;
9897
Richard Smith5179eb72016-06-28 19:03:57 +00009898 MaybeEmitInheritedConstructorNote(S, Found);
John McCalle1ac8d12010-01-13 00:25:19 +00009899}
9900
Larisse Voufo98b20f12013-07-19 23:00:19 +00009901/// Arity mismatch diagnosis specific to a function overload candidate.
Richard Smith17c00b42014-11-12 01:24:00 +00009902static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
9903 unsigned NumFormalArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009904 if (!CheckArityMismatch(S, Cand, NumFormalArgs))
Richard Smithc2bebe92016-05-11 20:37:46 +00009905 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
Larisse Voufo98b20f12013-07-19 23:00:19 +00009906}
Larisse Voufo47c08452013-07-19 22:53:23 +00009907
Richard Smith17c00b42014-11-12 01:24:00 +00009908static TemplateDecl *getDescribedTemplate(Decl *Templated) {
Serge Pavlov7dcc97e2016-04-19 06:19:52 +00009909 if (TemplateDecl *TD = Templated->getDescribedTemplate())
9910 return TD;
Larisse Voufo98b20f12013-07-19 23:00:19 +00009911 llvm_unreachable("Unsupported: Getting the described template declaration"
9912 " for bad deduction diagnosis");
9913}
9914
9915/// Diagnose a failed template-argument deduction.
Richard Smithc2bebe92016-05-11 20:37:46 +00009916static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
Richard Smith17c00b42014-11-12 01:24:00 +00009917 DeductionFailureInfo &DeductionFailure,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009918 unsigned NumArgs,
9919 bool TakingCandidateAddress) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009920 TemplateParameter Param = DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009921 NamedDecl *ParamD;
9922 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
9923 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
9924 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
Larisse Voufo98b20f12013-07-19 23:00:19 +00009925 switch (DeductionFailure.Result) {
John McCall8b9ed552010-02-01 18:53:26 +00009926 case Sema::TDK_Success:
9927 llvm_unreachable("TDK_success while diagnosing bad deduction");
9928
9929 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00009930 assert(ParamD && "no parameter found for incomplete deduction result");
Larisse Voufo98b20f12013-07-19 23:00:19 +00009931 S.Diag(Templated->getLocation(),
9932 diag::note_ovl_candidate_incomplete_deduction)
9933 << ParamD->getDeclName();
Richard Smith5179eb72016-06-28 19:03:57 +00009934 MaybeEmitInheritedConstructorNote(S, Found);
John McCall8b9ed552010-02-01 18:53:26 +00009935 return;
9936 }
9937
Richard Smith4a8f3512018-07-19 19:00:37 +00009938 case Sema::TDK_IncompletePack: {
9939 assert(ParamD && "no parameter found for incomplete deduction result");
9940 S.Diag(Templated->getLocation(),
9941 diag::note_ovl_candidate_incomplete_deduction_pack)
9942 << ParamD->getDeclName()
9943 << (DeductionFailure.getFirstArg()->pack_size() + 1)
9944 << *DeductionFailure.getFirstArg();
9945 MaybeEmitInheritedConstructorNote(S, Found);
9946 return;
9947 }
9948
John McCall42d7d192010-08-05 09:05:08 +00009949 case Sema::TDK_Underqualified: {
9950 assert(ParamD && "no parameter found for bad qualifiers deduction result");
9951 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
9952
Larisse Voufo98b20f12013-07-19 23:00:19 +00009953 QualType Param = DeductionFailure.getFirstArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00009954
9955 // Param will have been canonicalized, but it should just be a
9956 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00009957 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00009958 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00009959 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00009960 assert(S.Context.hasSameType(Param, NonCanonParam));
9961
9962 // Arg has also been canonicalized, but there's nothing we can do
9963 // about that. It also doesn't matter as much, because it won't
9964 // have any template parameters in it (because deduction isn't
9965 // done on dependent types).
Larisse Voufo98b20f12013-07-19 23:00:19 +00009966 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00009967
Larisse Voufo98b20f12013-07-19 23:00:19 +00009968 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
9969 << ParamD->getDeclName() << Arg << NonCanonParam;
Richard Smith5179eb72016-06-28 19:03:57 +00009970 MaybeEmitInheritedConstructorNote(S, Found);
John McCall42d7d192010-08-05 09:05:08 +00009971 return;
9972 }
9973
9974 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00009975 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009976 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009977 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009978 which = 0;
Richard Smith593d6a12016-12-23 01:30:39 +00009979 else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
9980 // Deduction might have failed because we deduced arguments of two
9981 // different types for a non-type template parameter.
9982 // FIXME: Use a different TDK value for this.
9983 QualType T1 =
9984 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
9985 QualType T2 =
9986 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
Richard Smithe54d9522018-10-09 18:49:22 +00009987 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
Richard Smith593d6a12016-12-23 01:30:39 +00009988 S.Diag(Templated->getLocation(),
9989 diag::note_ovl_candidate_inconsistent_deduction_types)
9990 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
9991 << *DeductionFailure.getSecondArg() << T2;
9992 MaybeEmitInheritedConstructorNote(S, Found);
9993 return;
9994 }
9995
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009996 which = 1;
Richard Smith593d6a12016-12-23 01:30:39 +00009997 } else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009998 which = 2;
9999 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010000
Larisse Voufo98b20f12013-07-19 23:00:19 +000010001 S.Diag(Templated->getLocation(),
10002 diag::note_ovl_candidate_inconsistent_deduction)
10003 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
10004 << *DeductionFailure.getSecondArg();
Richard Smith5179eb72016-06-28 19:03:57 +000010005 MaybeEmitInheritedConstructorNote(S, Found);
Douglas Gregor3626a5c2010-05-08 17:41:32 +000010006 return;
10007 }
Douglas Gregor02eb4832010-05-08 18:13:28 +000010008
Douglas Gregor1d72edd2010-05-08 19:15:54 +000010009 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010010 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +000010011 if (ParamD->getDeclName())
Larisse Voufo98b20f12013-07-19 23:00:19 +000010012 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +000010013 diag::note_ovl_candidate_explicit_arg_mismatch_named)
Larisse Voufo98b20f12013-07-19 23:00:19 +000010014 << ParamD->getDeclName();
Douglas Gregor1d72edd2010-05-08 19:15:54 +000010015 else {
10016 int index = 0;
10017 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
10018 index = TTP->getIndex();
10019 else if (NonTypeTemplateParmDecl *NTTP
10020 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
10021 index = NTTP->getIndex();
10022 else
10023 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
Larisse Voufo98b20f12013-07-19 23:00:19 +000010024 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +000010025 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
Larisse Voufo98b20f12013-07-19 23:00:19 +000010026 << (index + 1);
Douglas Gregor1d72edd2010-05-08 19:15:54 +000010027 }
Richard Smith5179eb72016-06-28 19:03:57 +000010028 MaybeEmitInheritedConstructorNote(S, Found);
Douglas Gregor1d72edd2010-05-08 19:15:54 +000010029 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010030
Douglas Gregor02eb4832010-05-08 18:13:28 +000010031 case Sema::TDK_TooManyArguments:
10032 case Sema::TDK_TooFewArguments:
Richard Smithc2bebe92016-05-11 20:37:46 +000010033 DiagnoseArityMismatch(S, Found, Templated, NumArgs);
Douglas Gregor02eb4832010-05-08 18:13:28 +000010034 return;
Douglas Gregord09efd42010-05-08 20:07:26 +000010035
10036 case Sema::TDK_InstantiationDepth:
Larisse Voufo98b20f12013-07-19 23:00:19 +000010037 S.Diag(Templated->getLocation(),
10038 diag::note_ovl_candidate_instantiation_depth);
Richard Smith5179eb72016-06-28 19:03:57 +000010039 MaybeEmitInheritedConstructorNote(S, Found);
Douglas Gregord09efd42010-05-08 20:07:26 +000010040 return;
10041
10042 case Sema::TDK_SubstitutionFailure: {
Richard Smith9ca64612012-05-07 09:03:25 +000010043 // Format the template argument list into the argument string.
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010044 SmallString<128> TemplateArgString;
Richard Smith9ca64612012-05-07 09:03:25 +000010045 if (TemplateArgumentList *Args =
Larisse Voufo98b20f12013-07-19 23:00:19 +000010046 DeductionFailure.getTemplateArgumentList()) {
Richard Smith9ca64612012-05-07 09:03:25 +000010047 TemplateArgString = " ";
10048 TemplateArgString += S.getTemplateArgumentBindingsText(
Larisse Voufo98b20f12013-07-19 23:00:19 +000010049 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
Richard Smith9ca64612012-05-07 09:03:25 +000010050 }
10051
Richard Smith6f8d2c62012-05-09 05:17:00 +000010052 // If this candidate was disabled by enable_if, say so.
Larisse Voufo98b20f12013-07-19 23:00:19 +000010053 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
Richard Smith6f8d2c62012-05-09 05:17:00 +000010054 if (PDiag && PDiag->second.getDiagID() ==
10055 diag::err_typename_nested_not_found_enable_if) {
10056 // FIXME: Use the source range of the condition, and the fully-qualified
10057 // name of the enable_if template. These are both present in PDiag.
10058 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
10059 << "'enable_if'" << TemplateArgString;
10060 return;
10061 }
10062
Douglas Gregor00fa10b2017-07-05 20:20:14 +000010063 // We found a specific requirement that disabled the enable_if.
10064 if (PDiag && PDiag->second.getDiagID() ==
10065 diag::err_typename_nested_not_found_requirement) {
10066 S.Diag(Templated->getLocation(),
10067 diag::note_ovl_candidate_disabled_by_requirement)
10068 << PDiag->second.getStringArg(0) << TemplateArgString;
10069 return;
10070 }
10071
Richard Smith9ca64612012-05-07 09:03:25 +000010072 // Format the SFINAE diagnostic into the argument string.
10073 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
10074 // formatted message in another diagnostic.
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010075 SmallString<128> SFINAEArgString;
Richard Smith9ca64612012-05-07 09:03:25 +000010076 SourceRange R;
Richard Smith6f8d2c62012-05-09 05:17:00 +000010077 if (PDiag) {
Richard Smith9ca64612012-05-07 09:03:25 +000010078 SFINAEArgString = ": ";
10079 R = SourceRange(PDiag->first, PDiag->first);
10080 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
10081 }
10082
Larisse Voufo98b20f12013-07-19 23:00:19 +000010083 S.Diag(Templated->getLocation(),
10084 diag::note_ovl_candidate_substitution_failure)
10085 << TemplateArgString << SFINAEArgString << R;
Richard Smith5179eb72016-06-28 19:03:57 +000010086 MaybeEmitInheritedConstructorNote(S, Found);
Douglas Gregord09efd42010-05-08 20:07:26 +000010087 return;
10088 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010089
Richard Smithc92d2062017-01-05 23:02:44 +000010090 case Sema::TDK_DeducedMismatch:
10091 case Sema::TDK_DeducedMismatchNested: {
Richard Smith9b534542015-12-31 02:02:54 +000010092 // Format the template argument list into the argument string.
10093 SmallString<128> TemplateArgString;
10094 if (TemplateArgumentList *Args =
10095 DeductionFailure.getTemplateArgumentList()) {
10096 TemplateArgString = " ";
10097 TemplateArgString += S.getTemplateArgumentBindingsText(
10098 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10099 }
10100
10101 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
10102 << (*DeductionFailure.getCallArgIndex() + 1)
10103 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
Richard Smithc92d2062017-01-05 23:02:44 +000010104 << TemplateArgString
10105 << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
Richard Smith9b534542015-12-31 02:02:54 +000010106 break;
10107 }
10108
Richard Trieue3732352013-04-08 21:11:40 +000010109 case Sema::TDK_NonDeducedMismatch: {
Richard Smith44ecdbd2013-01-31 05:19:49 +000010110 // FIXME: Provide a source location to indicate what we couldn't match.
Larisse Voufo98b20f12013-07-19 23:00:19 +000010111 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
10112 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
Richard Trieue3732352013-04-08 21:11:40 +000010113 if (FirstTA.getKind() == TemplateArgument::Template &&
10114 SecondTA.getKind() == TemplateArgument::Template) {
10115 TemplateName FirstTN = FirstTA.getAsTemplate();
10116 TemplateName SecondTN = SecondTA.getAsTemplate();
10117 if (FirstTN.getKind() == TemplateName::Template &&
10118 SecondTN.getKind() == TemplateName::Template) {
10119 if (FirstTN.getAsTemplateDecl()->getName() ==
10120 SecondTN.getAsTemplateDecl()->getName()) {
10121 // FIXME: This fixes a bad diagnostic where both templates are named
10122 // the same. This particular case is a bit difficult since:
10123 // 1) It is passed as a string to the diagnostic printer.
10124 // 2) The diagnostic printer only attempts to find a better
10125 // name for types, not decls.
10126 // Ideally, this should folded into the diagnostic printer.
Larisse Voufo98b20f12013-07-19 23:00:19 +000010127 S.Diag(Templated->getLocation(),
Richard Trieue3732352013-04-08 21:11:40 +000010128 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
10129 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
10130 return;
10131 }
10132 }
10133 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010134
10135 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
10136 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
10137 return;
10138
Faisal Vali2b391ab2013-09-26 19:54:12 +000010139 // FIXME: For generic lambda parameters, check if the function is a lambda
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010140 // call operator, and if so, emit a prettier and more informative
10141 // diagnostic that mentions 'auto' and lambda in addition to
Faisal Vali2b391ab2013-09-26 19:54:12 +000010142 // (or instead of?) the canonical template type parameters.
Larisse Voufo98b20f12013-07-19 23:00:19 +000010143 S.Diag(Templated->getLocation(),
10144 diag::note_ovl_candidate_non_deduced_mismatch)
10145 << FirstTA << SecondTA;
Richard Smith44ecdbd2013-01-31 05:19:49 +000010146 return;
Richard Trieue3732352013-04-08 21:11:40 +000010147 }
John McCall8b9ed552010-02-01 18:53:26 +000010148 // TODO: diagnose these individually, then kill off
10149 // note_ovl_candidate_bad_deduction, which is uselessly vague.
Richard Smith44ecdbd2013-01-31 05:19:49 +000010150 case Sema::TDK_MiscellaneousDeductionFailure:
Larisse Voufo98b20f12013-07-19 23:00:19 +000010151 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
Richard Smith5179eb72016-06-28 19:03:57 +000010152 MaybeEmitInheritedConstructorNote(S, Found);
John McCall8b9ed552010-02-01 18:53:26 +000010153 return;
Artem Belevich13e9b4d2016-12-07 19:27:16 +000010154 case Sema::TDK_CUDATargetMismatch:
10155 S.Diag(Templated->getLocation(),
10156 diag::note_cuda_ovl_candidate_target_mismatch);
10157 return;
John McCall8b9ed552010-02-01 18:53:26 +000010158 }
10159}
10160
Larisse Voufo98b20f12013-07-19 23:00:19 +000010161/// Diagnose a failed template-argument deduction, for function calls.
Richard Smith17c00b42014-11-12 01:24:00 +000010162static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010163 unsigned NumArgs,
10164 bool TakingCandidateAddress) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010165 unsigned TDK = Cand->DeductionFailure.Result;
10166 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
10167 if (CheckArityMismatch(S, Cand, NumArgs))
10168 return;
10169 }
Richard Smithc2bebe92016-05-11 20:37:46 +000010170 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010171 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010172}
10173
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010174/// CUDA: diagnose an invalid call across targets.
Richard Smith17c00b42014-11-12 01:24:00 +000010175static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010176 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
10177 FunctionDecl *Callee = Cand->Function;
10178
10179 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
10180 CalleeTarget = S.IdentifyCUDATarget(Callee);
10181
10182 std::string FnDesc;
Eric Fiselier92e523b2018-05-30 01:00:41 +000010183 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
Richard Smithc2bebe92016-05-11 20:37:46 +000010184 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc);
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010185
10186 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
Eric Fiselier92e523b2018-05-30 01:00:41 +000010187 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
10188 << FnDesc /* Ignored */
10189 << CalleeTarget << CallerTarget;
Eli Bendersky9a220fc2014-09-29 20:38:29 +000010190
10191 // This could be an implicit constructor for which we could not infer the
10192 // target due to a collsion. Diagnose that case.
10193 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
10194 if (Meth != nullptr && Meth->isImplicit()) {
10195 CXXRecordDecl *ParentClass = Meth->getParent();
10196 Sema::CXXSpecialMember CSM;
10197
Eric Fiselier92e523b2018-05-30 01:00:41 +000010198 switch (FnKindPair.first) {
Eli Bendersky9a220fc2014-09-29 20:38:29 +000010199 default:
10200 return;
10201 case oc_implicit_default_constructor:
10202 CSM = Sema::CXXDefaultConstructor;
10203 break;
10204 case oc_implicit_copy_constructor:
10205 CSM = Sema::CXXCopyConstructor;
10206 break;
10207 case oc_implicit_move_constructor:
10208 CSM = Sema::CXXMoveConstructor;
10209 break;
10210 case oc_implicit_copy_assignment:
10211 CSM = Sema::CXXCopyAssignment;
10212 break;
10213 case oc_implicit_move_assignment:
10214 CSM = Sema::CXXMoveAssignment;
10215 break;
10216 };
10217
10218 bool ConstRHS = false;
10219 if (Meth->getNumParams()) {
10220 if (const ReferenceType *RT =
10221 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
10222 ConstRHS = RT->getPointeeType().isConstQualified();
10223 }
10224 }
10225
10226 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
10227 /* ConstRHS */ ConstRHS,
10228 /* Diagnose */ true);
10229 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010230}
10231
Richard Smith17c00b42014-11-12 01:24:00 +000010232static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010233 FunctionDecl *Callee = Cand->Function;
10234 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
10235
10236 S.Diag(Callee->getLocation(),
George Burgess IV177399e2017-01-09 04:12:14 +000010237 diag::note_ovl_candidate_disabled_by_function_cond_attr)
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010238 << Attr->getCond()->getSourceRange() << Attr->getMessage();
10239}
10240
Yaxun Liu5b746652016-12-18 05:18:55 +000010241static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) {
10242 FunctionDecl *Callee = Cand->Function;
10243
10244 S.Diag(Callee->getLocation(),
Andrew Savonichev16f16992018-10-11 13:35:34 +000010245 diag::note_ovl_candidate_disabled_by_extension)
10246 << S.getOpenCLExtensionsFromDeclExtMap(Callee);
Yaxun Liu5b746652016-12-18 05:18:55 +000010247}
10248
John McCall8b9ed552010-02-01 18:53:26 +000010249/// Generates a 'note' diagnostic for an overload candidate. We've
10250/// already generated a primary error at the call site.
10251///
10252/// It really does need to be a single diagnostic with its caret
10253/// pointed at the candidate declaration. Yes, this creates some
10254/// major challenges of technical writing. Yes, this makes pointing
10255/// out problems with specific arguments quite awkward. It's still
10256/// better than generating twenty screens of text for every failed
10257/// overload.
10258///
10259/// It would be great to be able to express per-candidate problems
10260/// more richly for those diagnostic clients that cared, but we'd
10261/// still have to be just as careful with the default diagnostics.
Richard Smith17c00b42014-11-12 01:24:00 +000010262static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010263 unsigned NumArgs,
10264 bool TakingCandidateAddress) {
John McCall53262c92010-01-12 02:15:36 +000010265 FunctionDecl *Fn = Cand->Function;
10266
John McCall12f97bc2010-01-08 04:41:39 +000010267 // Note deleted candidates, but only if they're viable.
George Burgess IV177399e2017-01-09 04:12:14 +000010268 if (Cand->Viable) {
10269 if (Fn->isDeleted() || S.isFunctionConsideredUnavailable(Fn)) {
10270 std::string FnDesc;
Eric Fiselier92e523b2018-05-30 01:00:41 +000010271 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10272 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +000010273
George Burgess IV177399e2017-01-09 04:12:14 +000010274 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
Eric Fiselier92e523b2018-05-30 01:00:41 +000010275 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10276 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
George Burgess IV177399e2017-01-09 04:12:14 +000010277 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10278 return;
10279 }
John McCall12f97bc2010-01-08 04:41:39 +000010280
George Burgess IV177399e2017-01-09 04:12:14 +000010281 // We don't really have anything else to say about viable candidates.
Richard Smithc2bebe92016-05-11 20:37:46 +000010282 S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +000010283 return;
10284 }
John McCall0d1da222010-01-12 00:44:57 +000010285
John McCall6a61b522010-01-13 09:16:55 +000010286 switch (Cand->FailureKind) {
10287 case ovl_fail_too_many_arguments:
10288 case ovl_fail_too_few_arguments:
10289 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +000010290
John McCall6a61b522010-01-13 09:16:55 +000010291 case ovl_fail_bad_deduction:
Richard Smithc2bebe92016-05-11 20:37:46 +000010292 return DiagnoseBadDeduction(S, Cand, NumArgs,
10293 TakingCandidateAddress);
John McCall8b9ed552010-02-01 18:53:26 +000010294
John McCall578a1f82014-12-14 01:46:53 +000010295 case ovl_fail_illegal_constructor: {
10296 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
10297 << (Fn->getPrimaryTemplate() ? 1 : 0);
Richard Smith5179eb72016-06-28 19:03:57 +000010298 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall578a1f82014-12-14 01:46:53 +000010299 return;
10300 }
10301
John McCallfe796dd2010-01-23 05:17:32 +000010302 case ovl_fail_trivial_conversion:
10303 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +000010304 case ovl_fail_final_conversion_not_exact:
Richard Smithc2bebe92016-05-11 20:37:46 +000010305 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +000010306
John McCall65eb8792010-02-25 01:37:24 +000010307 case ovl_fail_bad_conversion: {
10308 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Richard Smith6eedfe72017-01-09 08:01:21 +000010309 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +000010310 if (Cand->Conversions[I].isBad())
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010311 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010312
John McCall6a61b522010-01-13 09:16:55 +000010313 // FIXME: this currently happens when we're called from SemaInit
10314 // when user-conversion overload fails. Figure out how to handle
10315 // those conditions and diagnose them well.
Richard Smithc2bebe92016-05-11 20:37:46 +000010316 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +000010317 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010318
10319 case ovl_fail_bad_target:
10320 return DiagnoseBadTarget(S, Cand);
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010321
10322 case ovl_fail_enable_if:
10323 return DiagnoseFailedEnableIfAttr(S, Cand);
George Burgess IV7204ed92016-01-07 02:26:57 +000010324
Yaxun Liu5b746652016-12-18 05:18:55 +000010325 case ovl_fail_ext_disabled:
10326 return DiagnoseOpenCLExtensionDisabled(S, Cand);
10327
Richard Smithf9c59b72017-01-08 21:45:44 +000010328 case ovl_fail_inhctor_slice:
Richard Smith836a3b42017-01-13 20:46:54 +000010329 // It's generally not interesting to note copy/move constructors here.
10330 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
10331 return;
Richard Smithf9c59b72017-01-08 21:45:44 +000010332 S.Diag(Fn->getLocation(),
Richard Smith836a3b42017-01-13 20:46:54 +000010333 diag::note_ovl_candidate_inherited_constructor_slice)
10334 << (Fn->getPrimaryTemplate() ? 1 : 0)
10335 << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
Richard Smithf9c59b72017-01-08 21:45:44 +000010336 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10337 return;
10338
George Burgess IV7204ed92016-01-07 02:26:57 +000010339 case ovl_fail_addr_not_available: {
10340 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
10341 (void)Available;
10342 assert(!Available);
10343 break;
10344 }
Erich Keane281d20b2018-01-08 21:34:17 +000010345 case ovl_non_default_multiversion_function:
10346 // Do nothing, these should simply be ignored.
10347 break;
John McCall65eb8792010-02-25 01:37:24 +000010348 }
John McCalld3224162010-01-08 00:58:21 +000010349}
10350
Richard Smith17c00b42014-11-12 01:24:00 +000010351static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
John McCalld3224162010-01-08 00:58:21 +000010352 // Desugar the type of the surrogate down to a function type,
10353 // retaining as many typedefs as possible while still showing
10354 // the function type (and, therefore, its parameter types).
10355 QualType FnType = Cand->Surrogate->getConversionType();
10356 bool isLValueReference = false;
10357 bool isRValueReference = false;
10358 bool isPointer = false;
10359 if (const LValueReferenceType *FnTypeRef =
10360 FnType->getAs<LValueReferenceType>()) {
10361 FnType = FnTypeRef->getPointeeType();
10362 isLValueReference = true;
10363 } else if (const RValueReferenceType *FnTypeRef =
10364 FnType->getAs<RValueReferenceType>()) {
10365 FnType = FnTypeRef->getPointeeType();
10366 isRValueReference = true;
10367 }
10368 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
10369 FnType = FnTypePtr->getPointeeType();
10370 isPointer = true;
10371 }
10372 // Desugar down to a function type.
10373 FnType = QualType(FnType->getAs<FunctionType>(), 0);
10374 // Reconstruct the pointer/reference as appropriate.
10375 if (isPointer) FnType = S.Context.getPointerType(FnType);
10376 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
10377 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
10378
10379 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
10380 << FnType;
10381}
10382
Richard Smith17c00b42014-11-12 01:24:00 +000010383static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
10384 SourceLocation OpLoc,
10385 OverloadCandidate *Cand) {
Richard Smith6eedfe72017-01-09 08:01:21 +000010386 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
John McCalld3224162010-01-08 00:58:21 +000010387 std::string TypeStr("operator");
10388 TypeStr += Opc;
10389 TypeStr += "(";
George Burgess IV5f6ab9a2017-06-08 20:55:21 +000010390 TypeStr += Cand->BuiltinParamTypes[0].getAsString();
Richard Smith6eedfe72017-01-09 08:01:21 +000010391 if (Cand->Conversions.size() == 1) {
John McCalld3224162010-01-08 00:58:21 +000010392 TypeStr += ")";
10393 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
10394 } else {
10395 TypeStr += ", ";
George Burgess IV5f6ab9a2017-06-08 20:55:21 +000010396 TypeStr += Cand->BuiltinParamTypes[1].getAsString();
John McCalld3224162010-01-08 00:58:21 +000010397 TypeStr += ")";
10398 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
10399 }
10400}
10401
Richard Smith17c00b42014-11-12 01:24:00 +000010402static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
10403 OverloadCandidate *Cand) {
Richard Smith6eedfe72017-01-09 08:01:21 +000010404 for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
John McCall0d1da222010-01-12 00:44:57 +000010405 if (ICS.isBad()) break; // all meaningless after first invalid
10406 if (!ICS.isAmbiguous()) continue;
10407
Richard Smithc2bebe92016-05-11 20:37:46 +000010408 ICS.DiagnoseAmbiguousConversion(
10409 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +000010410 }
10411}
10412
Larisse Voufo98b20f12013-07-19 23:00:19 +000010413static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
John McCall3712d9e2010-01-15 23:32:50 +000010414 if (Cand->Function)
10415 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +000010416 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +000010417 return Cand->Surrogate->getLocation();
10418 return SourceLocation();
10419}
10420
Larisse Voufo98b20f12013-07-19 23:00:19 +000010421static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
Chandler Carruth73fddfe2011-09-10 00:51:24 +000010422 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010423 case Sema::TDK_Success:
Richard Smith6eedfe72017-01-09 08:01:21 +000010424 case Sema::TDK_NonDependentConversionFailure:
10425 llvm_unreachable("non-deduction failure while diagnosing bad deduction");
Benjamin Kramer8a8051f2011-09-10 21:52:04 +000010426
Douglas Gregorc5c01a62012-09-13 21:01:57 +000010427 case Sema::TDK_Invalid:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010428 case Sema::TDK_Incomplete:
Richard Smith4a8f3512018-07-19 19:00:37 +000010429 case Sema::TDK_IncompletePack:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010430 return 1;
10431
10432 case Sema::TDK_Underqualified:
10433 case Sema::TDK_Inconsistent:
10434 return 2;
10435
10436 case Sema::TDK_SubstitutionFailure:
Richard Smith9b534542015-12-31 02:02:54 +000010437 case Sema::TDK_DeducedMismatch:
Richard Smithc92d2062017-01-05 23:02:44 +000010438 case Sema::TDK_DeducedMismatchNested:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010439 case Sema::TDK_NonDeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +000010440 case Sema::TDK_MiscellaneousDeductionFailure:
Artem Belevich13e9b4d2016-12-07 19:27:16 +000010441 case Sema::TDK_CUDATargetMismatch:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010442 return 3;
10443
10444 case Sema::TDK_InstantiationDepth:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010445 return 4;
10446
10447 case Sema::TDK_InvalidExplicitArguments:
10448 return 5;
10449
10450 case Sema::TDK_TooManyArguments:
10451 case Sema::TDK_TooFewArguments:
10452 return 6;
10453 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +000010454 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010455}
10456
Richard Smith17c00b42014-11-12 01:24:00 +000010457namespace {
John McCallad2587a2010-01-12 00:48:53 +000010458struct CompareOverloadCandidatesForDisplay {
10459 Sema &S;
Richard Smith0f59cb32015-12-18 21:45:41 +000010460 SourceLocation Loc;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +000010461 size_t NumArgs;
Richard Smith67ef14f2017-09-26 18:37:55 +000010462 OverloadCandidateSet::CandidateSetKind CSK;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +000010463
Richard Smith67ef14f2017-09-26 18:37:55 +000010464 CompareOverloadCandidatesForDisplay(
10465 Sema &S, SourceLocation Loc, size_t NArgs,
10466 OverloadCandidateSet::CandidateSetKind CSK)
Richard Smithfd544352017-09-26 21:33:43 +000010467 : S(S), NumArgs(NArgs), CSK(CSK) {}
John McCall12f97bc2010-01-08 04:41:39 +000010468
10469 bool operator()(const OverloadCandidate *L,
10470 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +000010471 // Fast-path this check.
10472 if (L == R) return false;
10473
John McCall12f97bc2010-01-08 04:41:39 +000010474 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +000010475 if (L->Viable) {
10476 if (!R->Viable) return true;
10477
10478 // TODO: introduce a tri-valued comparison for overload
10479 // candidates. Would be more worthwhile if we had a sort
10480 // that could exploit it.
Richard Smith67ef14f2017-09-26 18:37:55 +000010481 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK))
10482 return true;
10483 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK))
10484 return false;
John McCallad2587a2010-01-12 00:48:53 +000010485 } else if (R->Viable)
10486 return false;
John McCall12f97bc2010-01-08 04:41:39 +000010487
John McCall3712d9e2010-01-15 23:32:50 +000010488 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +000010489
John McCall3712d9e2010-01-15 23:32:50 +000010490 // Criteria by which we can sort non-viable candidates:
10491 if (!L->Viable) {
10492 // 1. Arity mismatches come after other candidates.
10493 if (L->FailureKind == ovl_fail_too_many_arguments ||
Kaelyn Takatab96b3be2014-05-01 21:15:24 +000010494 L->FailureKind == ovl_fail_too_few_arguments) {
10495 if (R->FailureKind == ovl_fail_too_many_arguments ||
10496 R->FailureKind == ovl_fail_too_few_arguments) {
Kaelyn Takata50c4ffc2014-05-07 00:43:38 +000010497 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
10498 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
10499 if (LDist == RDist) {
10500 if (L->FailureKind == R->FailureKind)
10501 // Sort non-surrogates before surrogates.
10502 return !L->IsSurrogate && R->IsSurrogate;
10503 // Sort candidates requiring fewer parameters than there were
10504 // arguments given after candidates requiring more parameters
10505 // than there were arguments given.
10506 return L->FailureKind == ovl_fail_too_many_arguments;
10507 }
Kaelyn Takatab96b3be2014-05-01 21:15:24 +000010508 return LDist < RDist;
10509 }
John McCall3712d9e2010-01-15 23:32:50 +000010510 return false;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +000010511 }
John McCall3712d9e2010-01-15 23:32:50 +000010512 if (R->FailureKind == ovl_fail_too_many_arguments ||
10513 R->FailureKind == ovl_fail_too_few_arguments)
10514 return true;
John McCall12f97bc2010-01-08 04:41:39 +000010515
John McCallfe796dd2010-01-23 05:17:32 +000010516 // 2. Bad conversions come first and are ordered by the number
10517 // of bad conversions and quality of good conversions.
10518 if (L->FailureKind == ovl_fail_bad_conversion) {
10519 if (R->FailureKind != ovl_fail_bad_conversion)
10520 return true;
10521
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010522 // The conversion that can be fixed with a smaller number of changes,
10523 // comes first.
10524 unsigned numLFixes = L->Fix.NumConversionsFixed;
10525 unsigned numRFixes = R->Fix.NumConversionsFixed;
10526 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
10527 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +000010528 if (numLFixes != numRFixes) {
David Blaikie7a3cbb22015-03-09 02:02:07 +000010529 return numLFixes < numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +000010530 }
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010531
John McCallfe796dd2010-01-23 05:17:32 +000010532 // If there's any ordering between the defined conversions...
10533 // FIXME: this might not be transitive.
Richard Smith6eedfe72017-01-09 08:01:21 +000010534 assert(L->Conversions.size() == R->Conversions.size());
John McCallfe796dd2010-01-23 05:17:32 +000010535
10536 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +000010537 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Richard Smith6eedfe72017-01-09 08:01:21 +000010538 for (unsigned E = L->Conversions.size(); I != E; ++I) {
Richard Smith0f59cb32015-12-18 21:45:41 +000010539 switch (CompareImplicitConversionSequences(S, Loc,
John McCall5c32be02010-08-24 20:38:10 +000010540 L->Conversions[I],
10541 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +000010542 case ImplicitConversionSequence::Better:
10543 leftBetter++;
10544 break;
10545
10546 case ImplicitConversionSequence::Worse:
10547 leftBetter--;
10548 break;
10549
10550 case ImplicitConversionSequence::Indistinguishable:
10551 break;
10552 }
10553 }
10554 if (leftBetter > 0) return true;
10555 if (leftBetter < 0) return false;
10556
10557 } else if (R->FailureKind == ovl_fail_bad_conversion)
10558 return false;
10559
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010560 if (L->FailureKind == ovl_fail_bad_deduction) {
10561 if (R->FailureKind != ovl_fail_bad_deduction)
10562 return true;
10563
10564 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10565 return RankDeductionFailure(L->DeductionFailure)
Eli Friedman1e7a0c62011-10-14 23:10:30 +000010566 < RankDeductionFailure(R->DeductionFailure);
Eli Friedmane2c600c2011-10-14 21:52:24 +000010567 } else if (R->FailureKind == ovl_fail_bad_deduction)
10568 return false;
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010569
John McCall3712d9e2010-01-15 23:32:50 +000010570 // TODO: others?
10571 }
10572
10573 // Sort everything else by location.
10574 SourceLocation LLoc = GetLocationForCandidate(L);
10575 SourceLocation RLoc = GetLocationForCandidate(R);
10576
10577 // Put candidates without locations (e.g. builtins) at the end.
10578 if (LLoc.isInvalid()) return false;
10579 if (RLoc.isInvalid()) return true;
10580
10581 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +000010582 }
10583};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010584}
John McCall12f97bc2010-01-08 04:41:39 +000010585
John McCallfe796dd2010-01-23 05:17:32 +000010586/// CompleteNonViableCandidate - Normally, overload resolution only
Richard Smith6eedfe72017-01-09 08:01:21 +000010587/// computes up to the first bad conversion. Produces the FixIt set if
10588/// possible.
Richard Smith17c00b42014-11-12 01:24:00 +000010589static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
10590 ArrayRef<Expr *> Args) {
John McCallfe796dd2010-01-23 05:17:32 +000010591 assert(!Cand->Viable);
10592
10593 // Don't do anything on failures other than bad conversion.
10594 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
10595
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010596 // We only want the FixIts if all the arguments can be corrected.
10597 bool Unfixable = false;
Anna Zaks1b068122011-07-28 19:46:48 +000010598 // Use a implicit copy initialization to check conversion fixes.
10599 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010600
Richard Smith6eedfe72017-01-09 08:01:21 +000010601 // Attempt to fix the bad conversion.
10602 unsigned ConvCount = Cand->Conversions.size();
10603 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
10604 ++ConvIdx) {
John McCallfe796dd2010-01-23 05:17:32 +000010605 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
Richard Smith6eedfe72017-01-09 08:01:21 +000010606 if (Cand->Conversions[ConvIdx].isInitialized() &&
10607 Cand->Conversions[ConvIdx].isBad()) {
10608 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
John McCallfe796dd2010-01-23 05:17:32 +000010609 break;
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010610 }
John McCallfe796dd2010-01-23 05:17:32 +000010611 }
10612
Douglas Gregoradc7a702010-04-16 17:45:54 +000010613 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +000010614 // operation somehow.
10615 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +000010616
Richard Smith14ead302017-01-10 20:19:21 +000010617 unsigned ConvIdx = 0;
10618 ArrayRef<QualType> ParamTypes;
John McCallfe796dd2010-01-23 05:17:32 +000010619
10620 if (Cand->IsSurrogate) {
10621 QualType ConvType
10622 = Cand->Surrogate->getConversionType().getNonReferenceType();
10623 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10624 ConvType = ConvPtrType->getPointeeType();
Richard Smith14ead302017-01-10 20:19:21 +000010625 ParamTypes = ConvType->getAs<FunctionProtoType>()->getParamTypes();
10626 // Conversion 0 is 'this', which doesn't have a corresponding argument.
10627 ConvIdx = 1;
John McCallfe796dd2010-01-23 05:17:32 +000010628 } else if (Cand->Function) {
Richard Smith14ead302017-01-10 20:19:21 +000010629 ParamTypes =
10630 Cand->Function->getType()->getAs<FunctionProtoType>()->getParamTypes();
John McCallfe796dd2010-01-23 05:17:32 +000010631 if (isa<CXXMethodDecl>(Cand->Function) &&
Richard Smith14ead302017-01-10 20:19:21 +000010632 !isa<CXXConstructorDecl>(Cand->Function)) {
10633 // Conversion 0 is 'this', which doesn't have a corresponding argument.
10634 ConvIdx = 1;
Richard Smith6eedfe72017-01-09 08:01:21 +000010635 }
Richard Smith14ead302017-01-10 20:19:21 +000010636 } else {
10637 // Builtin operator.
10638 assert(ConvCount <= 3);
George Burgess IV5f6ab9a2017-06-08 20:55:21 +000010639 ParamTypes = Cand->BuiltinParamTypes;
John McCallfe796dd2010-01-23 05:17:32 +000010640 }
10641
10642 // Fill in the rest of the conversions.
Richard Smith14ead302017-01-10 20:19:21 +000010643 for (unsigned ArgIdx = 0; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Richard Smith6eedfe72017-01-09 08:01:21 +000010644 if (Cand->Conversions[ConvIdx].isInitialized()) {
Richard Smith14ead302017-01-10 20:19:21 +000010645 // We've already checked this conversion.
10646 } else if (ArgIdx < ParamTypes.size()) {
10647 if (ParamTypes[ArgIdx]->isDependentType())
Richard Smith6eedfe72017-01-09 08:01:21 +000010648 Cand->Conversions[ConvIdx].setAsIdentityConversion(
10649 Args[ArgIdx]->getType());
10650 else {
10651 Cand->Conversions[ConvIdx] =
Richard Smith14ead302017-01-10 20:19:21 +000010652 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ArgIdx],
Richard Smith6eedfe72017-01-09 08:01:21 +000010653 SuppressUserConversions,
10654 /*InOverloadResolution=*/true,
10655 /*AllowObjCWritebackConversion=*/
10656 S.getLangOpts().ObjCAutoRefCount);
10657 // Store the FixIt in the candidate if it exists.
10658 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
10659 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10660 }
10661 } else
John McCallfe796dd2010-01-23 05:17:32 +000010662 Cand->Conversions[ConvIdx].setEllipsis();
10663 }
10664}
10665
Erich Keanec18cce42018-01-29 19:33:20 +000010666/// When overload resolution fails, prints diagnostic messages containing the
10667/// candidates in the candidate set.
Richard Smithb2f0f052016-10-10 18:54:32 +000010668void OverloadCandidateSet::NoteCandidates(
10669 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
10670 StringRef Opc, SourceLocation OpLoc,
10671 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
John McCall12f97bc2010-01-08 04:41:39 +000010672 // Sort the candidates by viability and position. Sorting directly would
10673 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010674 SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +000010675 if (OCD == OCD_AllCandidates) Cands.reserve(size());
10676 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
Richard Smithb2f0f052016-10-10 18:54:32 +000010677 if (!Filter(*Cand))
10678 continue;
John McCallfe796dd2010-01-23 05:17:32 +000010679 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +000010680 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +000010681 else if (OCD == OCD_AllCandidates) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010682 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010683 if (Cand->Function || Cand->IsSurrogate)
10684 Cands.push_back(Cand);
10685 // Otherwise, this a non-viable builtin candidate. We do not, in general,
10686 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +000010687 }
10688 }
10689
Mandeep Singh Grange66d2322017-11-14 00:22:24 +000010690 std::stable_sort(Cands.begin(), Cands.end(),
Richard Smith67ef14f2017-09-26 18:37:55 +000010691 CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010692
John McCall0d1da222010-01-12 00:44:57 +000010693 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +000010694
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010695 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Douglas Gregor79591782012-10-23 23:11:23 +000010696 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010697 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +000010698 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10699 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +000010700
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010701 // Set an arbitrary limit on the number of candidate functions we'll spam
10702 // the user with. FIXME: This limit should depend on details of the
10703 // candidate list.
Douglas Gregor79591782012-10-23 23:11:23 +000010704 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010705 break;
10706 }
10707 ++CandsShown;
10708
John McCalld3224162010-01-08 00:58:21 +000010709 if (Cand->Function)
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010710 NoteFunctionCandidate(S, Cand, Args.size(),
10711 /*TakingCandidateAddress=*/false);
John McCalld3224162010-01-08 00:58:21 +000010712 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +000010713 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010714 else {
10715 assert(Cand->Viable &&
10716 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +000010717 // Generally we only see ambiguities including viable builtin
10718 // operators if overload resolution got screwed up by an
10719 // ambiguous user-defined conversion.
10720 //
10721 // FIXME: It's quite possible for different conversions to see
10722 // different ambiguities, though.
10723 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +000010724 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +000010725 ReportedAmbiguousConversions = true;
10726 }
John McCalld3224162010-01-08 00:58:21 +000010727
John McCall0d1da222010-01-12 00:44:57 +000010728 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +000010729 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +000010730 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +000010731 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010732
10733 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +000010734 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +000010735}
10736
Larisse Voufo98b20f12013-07-19 23:00:19 +000010737static SourceLocation
10738GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
10739 return Cand->Specialization ? Cand->Specialization->getLocation()
10740 : SourceLocation();
10741}
10742
Richard Smith17c00b42014-11-12 01:24:00 +000010743namespace {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010744struct CompareTemplateSpecCandidatesForDisplay {
10745 Sema &S;
10746 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
10747
10748 bool operator()(const TemplateSpecCandidate *L,
10749 const TemplateSpecCandidate *R) {
10750 // Fast-path this check.
10751 if (L == R)
10752 return false;
10753
10754 // Assuming that both candidates are not matches...
10755
10756 // Sort by the ranking of deduction failures.
10757 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10758 return RankDeductionFailure(L->DeductionFailure) <
10759 RankDeductionFailure(R->DeductionFailure);
10760
10761 // Sort everything else by location.
10762 SourceLocation LLoc = GetLocationForCandidate(L);
10763 SourceLocation RLoc = GetLocationForCandidate(R);
10764
10765 // Put candidates without locations (e.g. builtins) at the end.
10766 if (LLoc.isInvalid())
10767 return false;
10768 if (RLoc.isInvalid())
10769 return true;
10770
10771 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10772 }
10773};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010774}
Larisse Voufo98b20f12013-07-19 23:00:19 +000010775
10776/// Diagnose a template argument deduction failure.
10777/// We are treating these failures as overload failures due to bad
10778/// deductions.
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010779void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
10780 bool ForTakingAddress) {
Richard Smithc2bebe92016-05-11 20:37:46 +000010781 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010782 DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010783}
10784
10785void TemplateSpecCandidateSet::destroyCandidates() {
10786 for (iterator i = begin(), e = end(); i != e; ++i) {
10787 i->DeductionFailure.Destroy();
10788 }
10789}
10790
10791void TemplateSpecCandidateSet::clear() {
10792 destroyCandidates();
10793 Candidates.clear();
10794}
10795
10796/// NoteCandidates - When no template specialization match is found, prints
10797/// diagnostic messages containing the non-matching specializations that form
10798/// the candidate set.
10799/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
10800/// OCD == OCD_AllCandidates and Cand->Viable == false.
10801void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
10802 // Sort the candidates by position (assuming no candidate is a match).
10803 // Sorting directly would be prohibitive, so we make a set of pointers
10804 // and sort those.
10805 SmallVector<TemplateSpecCandidate *, 32> Cands;
10806 Cands.reserve(size());
10807 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10808 if (Cand->Specialization)
10809 Cands.push_back(Cand);
Alp Tokerd4733632013-12-05 04:47:09 +000010810 // Otherwise, this is a non-matching builtin candidate. We do not,
Larisse Voufo98b20f12013-07-19 23:00:19 +000010811 // in general, want to list every possible builtin candidate.
10812 }
10813
Fangrui Song55fab262018-09-26 22:16:28 +000010814 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
Larisse Voufo98b20f12013-07-19 23:00:19 +000010815
10816 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
10817 // for generalization purposes (?).
10818 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10819
10820 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
10821 unsigned CandsShown = 0;
10822 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10823 TemplateSpecCandidate *Cand = *I;
10824
10825 // Set an arbitrary limit on the number of candidates we'll spam
10826 // the user with. FIXME: This limit should depend on details of the
10827 // candidate list.
10828 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10829 break;
10830 ++CandsShown;
10831
10832 assert(Cand->Specialization &&
10833 "Non-matching built-in candidates are not added to Cands.");
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010834 Cand->NoteDeductionFailure(S, ForTakingAddress);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010835 }
10836
10837 if (I != E)
10838 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
10839}
10840
Douglas Gregorb491ed32011-02-19 21:32:49 +000010841// [PossiblyAFunctionType] --> [Return]
10842// NonFunctionType --> NonFunctionType
10843// R (A) --> R(A)
10844// R (*)(A) --> R (A)
10845// R (&)(A) --> R (A)
10846// R (S::*)(A) --> R (A)
10847QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
10848 QualType Ret = PossiblyAFunctionType;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010849 if (const PointerType *ToTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +000010850 PossiblyAFunctionType->getAs<PointerType>())
10851 Ret = ToTypePtr->getPointeeType();
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010852 else if (const ReferenceType *ToTypeRef =
Douglas Gregorb491ed32011-02-19 21:32:49 +000010853 PossiblyAFunctionType->getAs<ReferenceType>())
10854 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +000010855 else if (const MemberPointerType *MemTypePtr =
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010856 PossiblyAFunctionType->getAs<MemberPointerType>())
10857 Ret = MemTypePtr->getPointeeType();
10858 Ret =
Douglas Gregorb491ed32011-02-19 21:32:49 +000010859 Context.getCanonicalType(Ret).getUnqualifiedType();
10860 return Ret;
10861}
Douglas Gregorcd695e52008-11-10 20:40:00 +000010862
Richard Smith9095e5b2016-11-01 01:31:23 +000010863static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
10864 bool Complain = true) {
10865 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
10866 S.DeduceReturnType(FD, Loc, Complain))
10867 return true;
10868
10869 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
Aaron Ballmanc351fba2017-12-04 20:27:34 +000010870 if (S.getLangOpts().CPlusPlus17 &&
Richard Smith9095e5b2016-11-01 01:31:23 +000010871 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
10872 !S.ResolveExceptionSpec(Loc, FPT))
10873 return true;
10874
10875 return false;
10876}
10877
Richard Smith17c00b42014-11-12 01:24:00 +000010878namespace {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010879// A helper class to help with address of function resolution
10880// - allows us to avoid passing around all those ugly parameters
Richard Smith17c00b42014-11-12 01:24:00 +000010881class AddressOfFunctionResolver {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010882 Sema& S;
10883 Expr* SourceExpr;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010884 const QualType& TargetType;
10885 QualType TargetFunctionType; // Extracted function type from target type
10886
Douglas Gregorb491ed32011-02-19 21:32:49 +000010887 bool Complain;
10888 //DeclAccessPair& ResultFunctionAccessPair;
10889 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010890
Douglas Gregorb491ed32011-02-19 21:32:49 +000010891 bool TargetTypeIsNonStaticMemberFunction;
10892 bool FoundNonTemplateFunction;
David Majnemera4f7c7a2013-08-01 06:13:59 +000010893 bool StaticMemberFunctionFromBoundPointer;
George Burgess IV5f2ef452015-10-12 18:40:58 +000010894 bool HasComplained;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010895
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010896 OverloadExpr::FindResult OvlExprInfo;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010897 OverloadExpr *OvlExpr;
10898 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010899 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Larisse Voufo98b20f12013-07-19 23:00:19 +000010900 TemplateSpecCandidateSet FailedCandidates;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010901
Douglas Gregorb491ed32011-02-19 21:32:49 +000010902public:
Larisse Voufo98b20f12013-07-19 23:00:19 +000010903 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
10904 const QualType &TargetType, bool Complain)
10905 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
10906 Complain(Complain), Context(S.getASTContext()),
10907 TargetTypeIsNonStaticMemberFunction(
10908 !!TargetType->getAs<MemberPointerType>()),
10909 FoundNonTemplateFunction(false),
David Majnemera4f7c7a2013-08-01 06:13:59 +000010910 StaticMemberFunctionFromBoundPointer(false),
George Burgess IV5f2ef452015-10-12 18:40:58 +000010911 HasComplained(false),
Larisse Voufo98b20f12013-07-19 23:00:19 +000010912 OvlExprInfo(OverloadExpr::find(SourceExpr)),
10913 OvlExpr(OvlExprInfo.Expression),
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010914 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010915 ExtractUnqualifiedFunctionTypeFromTargetType();
Chandler Carruthffce2452011-03-29 08:08:18 +000010916
David Majnemera4f7c7a2013-08-01 06:13:59 +000010917 if (TargetFunctionType->isFunctionType()) {
10918 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
10919 if (!UME->isImplicitAccess() &&
10920 !S.ResolveSingleFunctionTemplateSpecialization(UME))
10921 StaticMemberFunctionFromBoundPointer = true;
10922 } else if (OvlExpr->hasExplicitTemplateArgs()) {
10923 DeclAccessPair dap;
10924 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
10925 OvlExpr, false, &dap)) {
10926 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
10927 if (!Method->isStatic()) {
10928 // If the target type is a non-function type and the function found
10929 // is a non-static member function, pretend as if that was the
10930 // target, it's the only possible type to end up with.
10931 TargetTypeIsNonStaticMemberFunction = true;
Chandler Carruthffce2452011-03-29 08:08:18 +000010932
David Majnemera4f7c7a2013-08-01 06:13:59 +000010933 // And skip adding the function if its not in the proper form.
10934 // We'll diagnose this due to an empty set of functions.
10935 if (!OvlExprInfo.HasFormOfMemberPointer)
10936 return;
Chandler Carruthffce2452011-03-29 08:08:18 +000010937 }
10938
David Majnemera4f7c7a2013-08-01 06:13:59 +000010939 Matches.push_back(std::make_pair(dap, Fn));
Douglas Gregor9b146582009-07-08 20:55:45 +000010940 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010941 return;
Douglas Gregor9b146582009-07-08 20:55:45 +000010942 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010943
Douglas Gregorb491ed32011-02-19 21:32:49 +000010944 if (OvlExpr->hasExplicitTemplateArgs())
James Y Knight04ec5bf2015-12-24 02:59:37 +000010945 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +000010946
Douglas Gregorb491ed32011-02-19 21:32:49 +000010947 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
10948 // C++ [over.over]p4:
10949 // If more than one function is selected, [...]
George Burgess IV2a6150d2015-10-16 01:17:38 +000010950 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010951 if (FoundNonTemplateFunction)
10952 EliminateAllTemplateMatches();
10953 else
10954 EliminateAllExceptMostSpecializedTemplate();
10955 }
10956 }
Artem Belevich94a55e82015-09-22 17:22:59 +000010957
Justin Lebar25c4a812016-03-29 16:24:16 +000010958 if (S.getLangOpts().CUDA && Matches.size() > 1)
Artem Belevich94a55e82015-09-22 17:22:59 +000010959 EliminateSuboptimalCudaMatches();
Douglas Gregorb491ed32011-02-19 21:32:49 +000010960 }
George Burgess IV5f2ef452015-10-12 18:40:58 +000010961
10962 bool hasComplained() const { return HasComplained; }
10963
Douglas Gregorb491ed32011-02-19 21:32:49 +000010964private:
George Burgess IV6da4c202016-03-23 02:33:58 +000010965 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
10966 QualType Discard;
10967 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
Richard Smith3c4f8d22016-10-16 17:54:23 +000010968 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
George Burgess IV2a6150d2015-10-16 01:17:38 +000010969 }
10970
George Burgess IV6da4c202016-03-23 02:33:58 +000010971 /// \return true if A is considered a better overload candidate for the
10972 /// desired type than B.
10973 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
10974 // If A doesn't have exactly the correct type, we don't want to classify it
10975 // as "better" than anything else. This way, the user is required to
10976 // disambiguate for us if there are multiple candidates and no exact match.
10977 return candidateHasExactlyCorrectType(A) &&
10978 (!candidateHasExactlyCorrectType(B) ||
George Burgess IV3dc166912016-05-10 01:59:34 +000010979 compareEnableIfAttrs(S, A, B) == Comparison::Better);
George Burgess IV6da4c202016-03-23 02:33:58 +000010980 }
10981
10982 /// \return true if we were able to eliminate all but one overload candidate,
10983 /// false otherwise.
George Burgess IV2a6150d2015-10-16 01:17:38 +000010984 bool eliminiateSuboptimalOverloadCandidates() {
10985 // Same algorithm as overload resolution -- one pass to pick the "best",
10986 // another pass to be sure that nothing is better than the best.
10987 auto Best = Matches.begin();
10988 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
10989 if (isBetterCandidate(I->second, Best->second))
10990 Best = I;
10991
10992 const FunctionDecl *BestFn = Best->second;
10993 auto IsBestOrInferiorToBest = [this, BestFn](
10994 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
10995 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
10996 };
10997
10998 // Note: We explicitly leave Matches unmodified if there isn't a clear best
10999 // option, so we can potentially give the user a better error
11000 if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest))
11001 return false;
11002 Matches[0] = *Best;
11003 Matches.resize(1);
11004 return true;
11005 }
11006
Douglas Gregorb491ed32011-02-19 21:32:49 +000011007 bool isTargetTypeAFunction() const {
11008 return TargetFunctionType->isFunctionType();
11009 }
11010
11011 // [ToType] [Return]
11012
11013 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
11014 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
11015 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
11016 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
11017 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
11018 }
11019
11020 // return true if any matching specializations were found
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011021 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
Douglas Gregorb491ed32011-02-19 21:32:49 +000011022 const DeclAccessPair& CurAccessFunPair) {
11023 if (CXXMethodDecl *Method
11024 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
11025 // Skip non-static function templates when converting to pointer, and
11026 // static when converting to member pointer.
11027 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
11028 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011029 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000011030 else if (TargetTypeIsNonStaticMemberFunction)
11031 return false;
11032
11033 // C++ [over.over]p2:
11034 // If the name is a function template, template argument deduction is
11035 // done (14.8.2.2), and if the argument deduction succeeds, the
11036 // resulting template argument list is used to generate a single
11037 // function template specialization, which is added to the set of
11038 // overloaded functions considered.
Craig Topperc3ec1492014-05-26 06:22:03 +000011039 FunctionDecl *Specialization = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +000011040 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregorb491ed32011-02-19 21:32:49 +000011041 if (Sema::TemplateDeductionResult Result
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011042 = S.DeduceTemplateArguments(FunctionTemplate,
Douglas Gregorb491ed32011-02-19 21:32:49 +000011043 &OvlExplicitTemplateArgs,
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011044 TargetFunctionType, Specialization,
Richard Smithbaa47832016-12-01 02:11:49 +000011045 Info, /*IsAddressOfFunction*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000011046 // Make a note of the failed deduction for diagnostics.
11047 FailedCandidates.addCandidate()
Richard Smithc2bebe92016-05-11 20:37:46 +000011048 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
Larisse Voufo98b20f12013-07-19 23:00:19 +000011049 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregorb491ed32011-02-19 21:32:49 +000011050 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011051 }
11052
Douglas Gregor19a41f12013-04-17 08:45:07 +000011053 // Template argument deduction ensures that we have an exact match or
11054 // compatible pointer-to-function arguments that would be adjusted by ICS.
Douglas Gregorb491ed32011-02-19 21:32:49 +000011055 // This function template specicalization works.
Douglas Gregor19a41f12013-04-17 08:45:07 +000011056 assert(S.isSameOrCompatibleFunctionType(
11057 Context.getCanonicalType(Specialization->getType()),
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011058 Context.getCanonicalType(TargetFunctionType)));
George Burgess IV5f21c712015-10-12 19:57:04 +000011059
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011060 if (!S.checkAddressOfFunctionIsAvailable(Specialization))
George Burgess IV5f21c712015-10-12 19:57:04 +000011061 return false;
11062
Douglas Gregorb491ed32011-02-19 21:32:49 +000011063 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
11064 return true;
11065 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011066
11067 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
Douglas Gregorb491ed32011-02-19 21:32:49 +000011068 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +000011069 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +000011070 // Skip non-static functions when converting to pointer, and static
11071 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +000011072 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
11073 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011074 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000011075 else if (TargetTypeIsNonStaticMemberFunction)
11076 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +000011077
Chandler Carruthc25c6ee2009-12-29 06:17:27 +000011078 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000011079 if (S.getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +000011080 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
Justin Lebarb0080032016-08-10 01:09:11 +000011081 if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
Peter Collingbourne7277fe82011-10-02 23:49:40 +000011082 return false;
Erich Keane281d20b2018-01-08 21:34:17 +000011083 if (FunDecl->isMultiVersion()) {
11084 const auto *TA = FunDecl->getAttr<TargetAttr>();
Erich Keane3efe0022018-07-20 14:13:28 +000011085 if (TA && !TA->isDefaultVersion())
Erich Keane281d20b2018-01-08 21:34:17 +000011086 return false;
11087 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +000011088
Richard Smith2a7d4812013-05-04 07:00:32 +000011089 // If any candidate has a placeholder return type, trigger its deduction
11090 // now.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011091 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
Richard Smith9095e5b2016-11-01 01:31:23 +000011092 Complain)) {
George Burgess IV5f2ef452015-10-12 18:40:58 +000011093 HasComplained |= Complain;
Richard Smith2a7d4812013-05-04 07:00:32 +000011094 return false;
George Burgess IV5f2ef452015-10-12 18:40:58 +000011095 }
Richard Smith2a7d4812013-05-04 07:00:32 +000011096
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011097 if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
George Burgess IV5f21c712015-10-12 19:57:04 +000011098 return false;
11099
George Burgess IV6da4c202016-03-23 02:33:58 +000011100 // If we're in C, we need to support types that aren't exactly identical.
11101 if (!S.getLangOpts().CPlusPlus ||
11102 candidateHasExactlyCorrectType(FunDecl)) {
George Burgess IV5f21c712015-10-12 19:57:04 +000011103 Matches.push_back(std::make_pair(
11104 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +000011105 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +000011106 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +000011107 }
Mike Stump11289f42009-09-09 15:08:12 +000011108 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011109
Douglas Gregorb491ed32011-02-19 21:32:49 +000011110 return false;
11111 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011112
Douglas Gregorb491ed32011-02-19 21:32:49 +000011113 bool FindAllFunctionsThatMatchTargetTypeExactly() {
11114 bool Ret = false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011115
Douglas Gregorb491ed32011-02-19 21:32:49 +000011116 // If the overload expression doesn't have the form of a pointer to
11117 // member, don't try to convert it to a pointer-to-member type.
11118 if (IsInvalidFormOfPointerToMemberFunction())
11119 return false;
11120
11121 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011122 E = OvlExpr->decls_end();
Douglas Gregorb491ed32011-02-19 21:32:49 +000011123 I != E; ++I) {
11124 // Look through any using declarations to find the underlying function.
11125 NamedDecl *Fn = (*I)->getUnderlyingDecl();
11126
11127 // C++ [over.over]p3:
11128 // Non-member functions and static member functions match
11129 // targets of type "pointer-to-function" or "reference-to-function."
11130 // Nonstatic member functions match targets of
11131 // type "pointer-to-member-function."
11132 // Note that according to DR 247, the containing class does not matter.
11133 if (FunctionTemplateDecl *FunctionTemplate
11134 = dyn_cast<FunctionTemplateDecl>(Fn)) {
11135 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
11136 Ret = true;
11137 }
11138 // If we have explicit template arguments supplied, skip non-templates.
11139 else if (!OvlExpr->hasExplicitTemplateArgs() &&
11140 AddMatchingNonTemplateFunction(Fn, I.getPair()))
11141 Ret = true;
11142 }
11143 assert(Ret || Matches.empty());
11144 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +000011145 }
11146
Douglas Gregorb491ed32011-02-19 21:32:49 +000011147 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +000011148 // [...] and any given function template specialization F1 is
11149 // eliminated if the set contains a second function template
11150 // specialization whose function template is more specialized
11151 // than the function template of F1 according to the partial
11152 // ordering rules of 14.5.5.2.
11153
11154 // The algorithm specified above is quadratic. We instead use a
11155 // two-pass algorithm (similar to the one used to identify the
11156 // best viable function in an overload set) that identifies the
11157 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +000011158
11159 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
11160 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
11161 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011162
Larisse Voufo98b20f12013-07-19 23:00:19 +000011163 // TODO: It looks like FailedCandidates does not serve much purpose
11164 // here, since the no_viable diagnostic has index 0.
11165 UnresolvedSetIterator Result = S.getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +000011166 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011167 SourceExpr->getBeginLoc(), S.PDiag(),
Richard Smith5179eb72016-06-28 19:03:57 +000011168 S.PDiag(diag::err_addr_ovl_ambiguous)
Eric Fiselier92e523b2018-05-30 01:00:41 +000011169 << Matches[0].second->getDeclName(),
Richard Smith5179eb72016-06-28 19:03:57 +000011170 S.PDiag(diag::note_ovl_candidate)
Eric Fiselier92e523b2018-05-30 01:00:41 +000011171 << (unsigned)oc_function << (unsigned)ocs_described_template,
Larisse Voufo98b20f12013-07-19 23:00:19 +000011172 Complain, TargetFunctionType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011173
Douglas Gregorb491ed32011-02-19 21:32:49 +000011174 if (Result != MatchesCopy.end()) {
11175 // Make it the first and only element
11176 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
11177 Matches[0].second = cast<FunctionDecl>(*Result);
11178 Matches.resize(1);
George Burgess IV5f2ef452015-10-12 18:40:58 +000011179 } else
11180 HasComplained |= Complain;
John McCall58cc69d2010-01-27 01:50:18 +000011181 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011182
Douglas Gregorb491ed32011-02-19 21:32:49 +000011183 void EliminateAllTemplateMatches() {
11184 // [...] any function template specializations in the set are
11185 // eliminated if the set also contains a non-template function, [...]
11186 for (unsigned I = 0, N = Matches.size(); I != N; ) {
Craig Topperc3ec1492014-05-26 06:22:03 +000011187 if (Matches[I].second->getPrimaryTemplate() == nullptr)
Douglas Gregorb491ed32011-02-19 21:32:49 +000011188 ++I;
11189 else {
11190 Matches[I] = Matches[--N];
Artem Belevich94a55e82015-09-22 17:22:59 +000011191 Matches.resize(N);
Douglas Gregorb491ed32011-02-19 21:32:49 +000011192 }
11193 }
11194 }
11195
Artem Belevich94a55e82015-09-22 17:22:59 +000011196 void EliminateSuboptimalCudaMatches() {
11197 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
11198 }
11199
Douglas Gregorb491ed32011-02-19 21:32:49 +000011200public:
11201 void ComplainNoMatchesFound() const {
11202 assert(Matches.empty());
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011203 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
Douglas Gregorb491ed32011-02-19 21:32:49 +000011204 << OvlExpr->getName() << TargetFunctionType
11205 << OvlExpr->getSourceRange();
Richard Smith0d905472013-08-14 00:00:44 +000011206 if (FailedCandidates.empty())
George Burgess IV5f21c712015-10-12 19:57:04 +000011207 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11208 /*TakingAddress=*/true);
Richard Smith0d905472013-08-14 00:00:44 +000011209 else {
11210 // We have some deduction failure messages. Use them to diagnose
11211 // the function templates, and diagnose the non-template candidates
11212 // normally.
11213 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11214 IEnd = OvlExpr->decls_end();
11215 I != IEnd; ++I)
11216 if (FunctionDecl *Fun =
11217 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011218 if (!functionHasPassObjectSizeParams(Fun))
Richard Smithc2bebe92016-05-11 20:37:46 +000011219 S.NoteOverloadCandidate(*I, Fun, TargetFunctionType,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011220 /*TakingAddress=*/true);
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011221 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
Richard Smith0d905472013-08-14 00:00:44 +000011222 }
11223 }
11224
Douglas Gregorb491ed32011-02-19 21:32:49 +000011225 bool IsInvalidFormOfPointerToMemberFunction() const {
11226 return TargetTypeIsNonStaticMemberFunction &&
11227 !OvlExprInfo.HasFormOfMemberPointer;
11228 }
David Majnemera4f7c7a2013-08-01 06:13:59 +000011229
Douglas Gregorb491ed32011-02-19 21:32:49 +000011230 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
11231 // TODO: Should we condition this on whether any functions might
11232 // have matched, or is it more appropriate to do that in callers?
11233 // TODO: a fixit wouldn't hurt.
11234 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
11235 << TargetType << OvlExpr->getSourceRange();
11236 }
David Majnemera4f7c7a2013-08-01 06:13:59 +000011237
11238 bool IsStaticMemberFunctionFromBoundPointer() const {
11239 return StaticMemberFunctionFromBoundPointer;
11240 }
11241
11242 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011243 S.Diag(OvlExpr->getBeginLoc(),
David Majnemera4f7c7a2013-08-01 06:13:59 +000011244 diag::err_invalid_form_pointer_member_function)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011245 << OvlExpr->getSourceRange();
David Majnemera4f7c7a2013-08-01 06:13:59 +000011246 }
11247
Douglas Gregorb491ed32011-02-19 21:32:49 +000011248 void ComplainOfInvalidConversion() const {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011249 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
11250 << OvlExpr->getName() << TargetType;
Douglas Gregorb491ed32011-02-19 21:32:49 +000011251 }
11252
11253 void ComplainMultipleMatchesFound() const {
11254 assert(Matches.size() > 1);
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011255 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
11256 << OvlExpr->getName() << OvlExpr->getSourceRange();
George Burgess IV5f21c712015-10-12 19:57:04 +000011257 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11258 /*TakingAddress=*/true);
Douglas Gregorb491ed32011-02-19 21:32:49 +000011259 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +000011260
11261 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
11262
Douglas Gregorb491ed32011-02-19 21:32:49 +000011263 int getNumMatches() const { return Matches.size(); }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011264
Douglas Gregorb491ed32011-02-19 21:32:49 +000011265 FunctionDecl* getMatchingFunctionDecl() const {
Craig Topperc3ec1492014-05-26 06:22:03 +000011266 if (Matches.size() != 1) return nullptr;
Douglas Gregorb491ed32011-02-19 21:32:49 +000011267 return Matches[0].second;
11268 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011269
Douglas Gregorb491ed32011-02-19 21:32:49 +000011270 const DeclAccessPair* getMatchingFunctionAccessPair() const {
Craig Topperc3ec1492014-05-26 06:22:03 +000011271 if (Matches.size() != 1) return nullptr;
Douglas Gregorb491ed32011-02-19 21:32:49 +000011272 return &Matches[0].first;
11273 }
11274};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000011275}
Richard Smith17c00b42014-11-12 01:24:00 +000011276
Douglas Gregorb491ed32011-02-19 21:32:49 +000011277/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
11278/// an overloaded function (C++ [over.over]), where @p From is an
11279/// expression with overloaded function type and @p ToType is the type
11280/// we're trying to resolve to. For example:
11281///
11282/// @code
11283/// int f(double);
11284/// int f(int);
11285///
11286/// int (*pfd)(double) = f; // selects f(double)
11287/// @endcode
11288///
11289/// This routine returns the resulting FunctionDecl if it could be
11290/// resolved, and NULL otherwise. When @p Complain is true, this
11291/// routine will emit diagnostics if there is an error.
11292FunctionDecl *
Abramo Bagnara5001caa2011-11-19 11:44:21 +000011293Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
11294 QualType TargetType,
11295 bool Complain,
11296 DeclAccessPair &FoundResult,
11297 bool *pHadMultipleCandidates) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000011298 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara5001caa2011-11-19 11:44:21 +000011299
11300 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
11301 Complain);
Douglas Gregorb491ed32011-02-19 21:32:49 +000011302 int NumMatches = Resolver.getNumMatches();
Craig Topperc3ec1492014-05-26 06:22:03 +000011303 FunctionDecl *Fn = nullptr;
George Burgess IV5f2ef452015-10-12 18:40:58 +000011304 bool ShouldComplain = Complain && !Resolver.hasComplained();
11305 if (NumMatches == 0 && ShouldComplain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000011306 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
11307 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
11308 else
11309 Resolver.ComplainNoMatchesFound();
11310 }
George Burgess IV5f2ef452015-10-12 18:40:58 +000011311 else if (NumMatches > 1 && ShouldComplain)
Douglas Gregorb491ed32011-02-19 21:32:49 +000011312 Resolver.ComplainMultipleMatchesFound();
11313 else if (NumMatches == 1) {
11314 Fn = Resolver.getMatchingFunctionDecl();
11315 assert(Fn);
Richard Smith9095e5b2016-11-01 01:31:23 +000011316 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
11317 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
Douglas Gregorb491ed32011-02-19 21:32:49 +000011318 FoundResult = *Resolver.getMatchingFunctionAccessPair();
David Majnemera4f7c7a2013-08-01 06:13:59 +000011319 if (Complain) {
11320 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
11321 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
11322 else
11323 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
11324 }
Sebastian Redldf4b80e2009-10-17 21:12:09 +000011325 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +000011326
11327 if (pHadMultipleCandidates)
11328 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregorb491ed32011-02-19 21:32:49 +000011329 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +000011330}
11331
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011332/// Given an expression that refers to an overloaded function, try to
George Burgess IV3cde9bf2016-03-19 21:36:10 +000011333/// resolve that function to a single function that can have its address taken.
11334/// This will modify `Pair` iff it returns non-null.
11335///
11336/// This routine can only realistically succeed if all but one candidates in the
11337/// overload set for SrcExpr cannot have their addresses taken.
11338FunctionDecl *
11339Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
11340 DeclAccessPair &Pair) {
11341 OverloadExpr::FindResult R = OverloadExpr::find(E);
11342 OverloadExpr *Ovl = R.Expression;
11343 FunctionDecl *Result = nullptr;
11344 DeclAccessPair DAP;
11345 // Don't use the AddressOfResolver because we're specifically looking for
11346 // cases where we have one overload candidate that lacks
11347 // enable_if/pass_object_size/...
11348 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
11349 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
11350 if (!FD)
11351 return nullptr;
11352
11353 if (!checkAddressOfFunctionIsAvailable(FD))
11354 continue;
11355
11356 // We have more than one result; quit.
11357 if (Result)
11358 return nullptr;
11359 DAP = I.getPair();
11360 Result = FD;
11361 }
11362
11363 if (Result)
11364 Pair = DAP;
11365 return Result;
11366}
11367
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011368/// Given an overloaded function, tries to turn it into a non-overloaded
George Burgess IVbeca4a32016-06-08 00:34:22 +000011369/// function reference using resolveAddressOfOnlyViableOverloadCandidate. This
11370/// will perform access checks, diagnose the use of the resultant decl, and, if
George Burgess IV1dbfa852017-05-09 04:06:24 +000011371/// requested, potentially perform a function-to-pointer decay.
George Burgess IVbeca4a32016-06-08 00:34:22 +000011372///
11373/// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails.
11374/// Otherwise, returns true. This may emit diagnostics and return true.
11375bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate(
George Burgess IV1dbfa852017-05-09 04:06:24 +000011376 ExprResult &SrcExpr, bool DoFunctionPointerConverion) {
George Burgess IVbeca4a32016-06-08 00:34:22 +000011377 Expr *E = SrcExpr.get();
11378 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
11379
11380 DeclAccessPair DAP;
11381 FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP);
Erich Keane3efe0022018-07-20 14:13:28 +000011382 if (!Found || Found->isCPUDispatchMultiVersion() ||
11383 Found->isCPUSpecificMultiVersion())
George Burgess IVbeca4a32016-06-08 00:34:22 +000011384 return false;
11385
11386 // Emitting multiple diagnostics for a function that is both inaccessible and
11387 // unavailable is consistent with our behavior elsewhere. So, always check
11388 // for both.
11389 DiagnoseUseOfDecl(Found, E->getExprLoc());
11390 CheckAddressOfMemberAccess(E, DAP);
11391 Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
George Burgess IV1dbfa852017-05-09 04:06:24 +000011392 if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType())
George Burgess IVbeca4a32016-06-08 00:34:22 +000011393 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
11394 else
11395 SrcExpr = Fixed;
11396 return true;
11397}
11398
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011399/// Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011400/// resolve that overloaded function expression down to a single function.
11401///
11402/// This routine can only resolve template-ids that refer to a single function
11403/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011404/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011405/// as described in C++0x [temp.arg.explicit]p3.
Alp Toker67b47ac2013-10-20 18:48:56 +000011406///
11407/// If no template-ids are found, no diagnostics are emitted and NULL is
11408/// returned.
John McCall0009fcc2011-04-26 20:42:42 +000011409FunctionDecl *
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011410Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
John McCall0009fcc2011-04-26 20:42:42 +000011411 bool Complain,
11412 DeclAccessPair *FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011413 // C++ [over.over]p1:
11414 // [...] [Note: any redundant set of parentheses surrounding the
11415 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011416 // C++ [over.over]p1:
11417 // [...] The overloaded function name can be preceded by the &
11418 // operator.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011419
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011420 // If we didn't actually find any template-ids, we're done.
John McCall0009fcc2011-04-26 20:42:42 +000011421 if (!ovl->hasExplicitTemplateArgs())
Craig Topperc3ec1492014-05-26 06:22:03 +000011422 return nullptr;
John McCall1acbbb52010-02-02 06:20:04 +000011423
11424 TemplateArgumentListInfo ExplicitTemplateArgs;
James Y Knight04ec5bf2015-12-24 02:59:37 +000011425 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
Larisse Voufo98b20f12013-07-19 23:00:19 +000011426 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011427
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011428 // Look through all of the overloaded functions, searching for one
11429 // whose type matches exactly.
Craig Topperc3ec1492014-05-26 06:22:03 +000011430 FunctionDecl *Matched = nullptr;
John McCall0009fcc2011-04-26 20:42:42 +000011431 for (UnresolvedSetIterator I = ovl->decls_begin(),
11432 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011433 // C++0x [temp.arg.explicit]p3:
11434 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011435 // where deduction is not done, if a template argument list is
11436 // specified and it, along with any default template arguments,
11437 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011438 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +000011439 FunctionTemplateDecl *FunctionTemplate
11440 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011441
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011442 // C++ [over.over]p2:
11443 // If the name is a function template, template argument deduction is
11444 // done (14.8.2.2), and if the argument deduction succeeds, the
11445 // resulting template argument list is used to generate a single
11446 // function template specialization, which is added to the set of
11447 // overloaded functions considered.
Craig Topperc3ec1492014-05-26 06:22:03 +000011448 FunctionDecl *Specialization = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +000011449 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011450 if (TemplateDeductionResult Result
11451 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
Douglas Gregor19a41f12013-04-17 08:45:07 +000011452 Specialization, Info,
Richard Smithbaa47832016-12-01 02:11:49 +000011453 /*IsAddressOfFunction*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000011454 // Make a note of the failed deduction for diagnostics.
11455 // TODO: Actually use the failed-deduction info?
11456 FailedCandidates.addCandidate()
Richard Smithc2bebe92016-05-11 20:37:46 +000011457 .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
Larisse Voufo98b20f12013-07-19 23:00:19 +000011458 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011459 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011460 }
11461
John McCall0009fcc2011-04-26 20:42:42 +000011462 assert(Specialization && "no specialization and no error?");
11463
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011464 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +000011465 if (Matched) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000011466 if (Complain) {
John McCall0009fcc2011-04-26 20:42:42 +000011467 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
11468 << ovl->getName();
11469 NoteAllOverloadCandidates(ovl);
Douglas Gregorb491ed32011-02-19 21:32:49 +000011470 }
Craig Topperc3ec1492014-05-26 06:22:03 +000011471 return nullptr;
John McCall0009fcc2011-04-26 20:42:42 +000011472 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011473
John McCall0009fcc2011-04-26 20:42:42 +000011474 Matched = Specialization;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011475 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011476 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011477
Richard Smith9095e5b2016-11-01 01:31:23 +000011478 if (Matched &&
11479 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
Craig Topperc3ec1492014-05-26 06:22:03 +000011480 return nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +000011481
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011482 return Matched;
11483}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011484
John McCall50a2c2c2011-10-11 23:14:30 +000011485// Resolve and fix an overloaded expression that can be resolved
11486// because it identifies a single function template specialization.
11487//
Douglas Gregor1beec452011-03-12 01:48:56 +000011488// Last three arguments should only be supplied if Complain = true
John McCall50a2c2c2011-10-11 23:14:30 +000011489//
11490// Return true if it was logically possible to so resolve the
11491// expression, regardless of whether or not it succeeded. Always
11492// returns true if 'complain' is set.
11493bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
11494 ExprResult &SrcExpr, bool doFunctionPointerConverion,
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011495 bool complain, SourceRange OpRangeForComplaining,
11496 QualType DestTypeForComplaining,
John McCall0009fcc2011-04-26 20:42:42 +000011497 unsigned DiagIDForComplaining) {
John McCall50a2c2c2011-10-11 23:14:30 +000011498 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregor1beec452011-03-12 01:48:56 +000011499
John McCall50a2c2c2011-10-11 23:14:30 +000011500 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregor1beec452011-03-12 01:48:56 +000011501
John McCall0009fcc2011-04-26 20:42:42 +000011502 DeclAccessPair found;
11503 ExprResult SingleFunctionExpression;
11504 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
11505 ovl.Expression, /*complain*/ false, &found)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011506 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
John McCall50a2c2c2011-10-11 23:14:30 +000011507 SrcExpr = ExprError();
11508 return true;
11509 }
John McCall0009fcc2011-04-26 20:42:42 +000011510
11511 // It is only correct to resolve to an instance method if we're
11512 // resolving a form that's permitted to be a pointer to member.
11513 // Otherwise we'll end up making a bound member expression, which
11514 // is illegal in all the contexts we resolve like this.
11515 if (!ovl.HasFormOfMemberPointer &&
11516 isa<CXXMethodDecl>(fn) &&
11517 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall50a2c2c2011-10-11 23:14:30 +000011518 if (!complain) return false;
11519
11520 Diag(ovl.Expression->getExprLoc(),
11521 diag::err_bound_member_function)
11522 << 0 << ovl.Expression->getSourceRange();
11523
11524 // TODO: I believe we only end up here if there's a mix of
11525 // static and non-static candidates (otherwise the expression
11526 // would have 'bound member' type, not 'overload' type).
11527 // Ideally we would note which candidate was chosen and why
11528 // the static candidates were rejected.
11529 SrcExpr = ExprError();
11530 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000011531 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +000011532
Sylvestre Ledrua5202662012-07-31 06:56:50 +000011533 // Fix the expression to refer to 'fn'.
John McCall0009fcc2011-04-26 20:42:42 +000011534 SingleFunctionExpression =
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011535 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
John McCall0009fcc2011-04-26 20:42:42 +000011536
11537 // If desired, do function-to-pointer decay.
John McCall50a2c2c2011-10-11 23:14:30 +000011538 if (doFunctionPointerConverion) {
John McCall0009fcc2011-04-26 20:42:42 +000011539 SingleFunctionExpression =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011540 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
John McCall50a2c2c2011-10-11 23:14:30 +000011541 if (SingleFunctionExpression.isInvalid()) {
11542 SrcExpr = ExprError();
11543 return true;
11544 }
11545 }
John McCall0009fcc2011-04-26 20:42:42 +000011546 }
11547
11548 if (!SingleFunctionExpression.isUsable()) {
11549 if (complain) {
11550 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
11551 << ovl.Expression->getName()
11552 << DestTypeForComplaining
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011553 << OpRangeForComplaining
John McCall0009fcc2011-04-26 20:42:42 +000011554 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall50a2c2c2011-10-11 23:14:30 +000011555 NoteAllOverloadCandidates(SrcExpr.get());
11556
11557 SrcExpr = ExprError();
11558 return true;
11559 }
11560
11561 return false;
John McCall0009fcc2011-04-26 20:42:42 +000011562 }
11563
John McCall50a2c2c2011-10-11 23:14:30 +000011564 SrcExpr = SingleFunctionExpression;
11565 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000011566}
11567
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011568/// Add a single candidate to the overload set.
Douglas Gregorcabea402009-09-22 15:41:20 +000011569static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +000011570 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +000011571 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011572 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000011573 OverloadCandidateSet &CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +000011574 bool PartialOverloading,
11575 bool KnownValid) {
John McCalla0296f72010-03-19 07:35:19 +000011576 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +000011577 if (isa<UsingShadowDecl>(Callee))
11578 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
11579
Douglas Gregorcabea402009-09-22 15:41:20 +000011580 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith95ce4f62011-06-26 22:19:54 +000011581 if (ExplicitTemplateArgs) {
11582 assert(!KnownValid && "Explicit template arguments?");
11583 return;
11584 }
Bruno Cardoso Lopes37029632017-04-26 20:13:45 +000011585 // Prevent ill-formed function decls to be added as overload candidates.
11586 if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
11587 return;
11588
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011589 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
11590 /*SuppressUsedConversions=*/false,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011591 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000011592 return;
John McCalld14a8642009-11-21 08:51:07 +000011593 }
11594
11595 if (FunctionTemplateDecl *FuncTemplate
11596 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +000011597 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011598 ExplicitTemplateArgs, Args, CandidateSet,
11599 /*SuppressUsedConversions=*/false,
11600 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +000011601 return;
11602 }
11603
Richard Smith95ce4f62011-06-26 22:19:54 +000011604 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregorcabea402009-09-22 15:41:20 +000011605}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011606
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011607/// Add the overload candidates named by callee and/or found by argument
Douglas Gregorcabea402009-09-22 15:41:20 +000011608/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +000011609void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011610 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000011611 OverloadCandidateSet &CandidateSet,
11612 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +000011613
11614#ifndef NDEBUG
11615 // Verify that ArgumentDependentLookup is consistent with the rules
11616 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +000011617 //
Douglas Gregorcabea402009-09-22 15:41:20 +000011618 // Let X be the lookup set produced by unqualified lookup (3.4.1)
11619 // and let Y be the lookup set produced by argument dependent
11620 // lookup (defined as follows). If X contains
11621 //
11622 // -- a declaration of a class member, or
11623 //
11624 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +000011625 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +000011626 //
11627 // -- a declaration that is neither a function or a function
11628 // template
11629 //
11630 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +000011631
John McCall57500772009-12-16 12:17:52 +000011632 if (ULE->requiresADL()) {
11633 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11634 E = ULE->decls_end(); I != E; ++I) {
11635 assert(!(*I)->getDeclContext()->isRecord());
11636 assert(isa<UsingShadowDecl>(*I) ||
11637 !(*I)->getDeclContext()->isFunctionOrMethod());
11638 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +000011639 }
11640 }
11641#endif
11642
John McCall57500772009-12-16 12:17:52 +000011643 // It would be nice to avoid this copy.
11644 TemplateArgumentListInfo TABuffer;
Craig Topperc3ec1492014-05-26 06:22:03 +000011645 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
John McCall57500772009-12-16 12:17:52 +000011646 if (ULE->hasExplicitTemplateArgs()) {
11647 ULE->copyTemplateArgumentsInto(TABuffer);
11648 ExplicitTemplateArgs = &TABuffer;
11649 }
11650
11651 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11652 E = ULE->decls_end(); I != E; ++I)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011653 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
11654 CandidateSet, PartialOverloading,
11655 /*KnownValid*/ true);
John McCalld14a8642009-11-21 08:51:07 +000011656
John McCall57500772009-12-16 12:17:52 +000011657 if (ULE->requiresADL())
Richard Smith100b24a2014-04-17 01:52:14 +000011658 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011659 Args, ExplicitTemplateArgs,
Richard Smithb6626742012-10-18 17:56:02 +000011660 CandidateSet, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000011661}
John McCalld681c392009-12-16 08:11:27 +000011662
Richard Smith0603bbb2013-06-12 22:56:54 +000011663/// Determine whether a declaration with the specified name could be moved into
11664/// a different namespace.
11665static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
11666 switch (Name.getCXXOverloadedOperator()) {
11667 case OO_New: case OO_Array_New:
11668 case OO_Delete: case OO_Array_Delete:
11669 return false;
11670
11671 default:
11672 return true;
11673 }
11674}
11675
Richard Smith998a5912011-06-05 22:42:48 +000011676/// Attempt to recover from an ill-formed use of a non-dependent name in a
11677/// template, where the non-dependent name was declared after the template
11678/// was defined. This is common in code written for a compilers which do not
11679/// correctly implement two-stage name lookup.
11680///
11681/// Returns true if a viable candidate was found and a diagnostic was issued.
11682static bool
11683DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
11684 const CXXScopeSpec &SS, LookupResult &R,
Richard Smith100b24a2014-04-17 01:52:14 +000011685 OverloadCandidateSet::CandidateSetKind CSK,
Richard Smith998a5912011-06-05 22:42:48 +000011686 TemplateArgumentListInfo *ExplicitTemplateArgs,
Hans Wennborg64937c62015-06-11 21:21:57 +000011687 ArrayRef<Expr *> Args,
11688 bool *DoDiagnoseEmptyLookup = nullptr) {
Richard Smith51ec0cf2017-02-21 01:17:38 +000011689 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
Richard Smith998a5912011-06-05 22:42:48 +000011690 return false;
11691
11692 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewyckyfcd5e7a2012-03-14 20:41:00 +000011693 if (DC->isTransparentContext())
11694 continue;
11695
Richard Smith998a5912011-06-05 22:42:48 +000011696 SemaRef.LookupQualifiedName(R, DC);
11697
11698 if (!R.empty()) {
11699 R.suppressDiagnostics();
11700
11701 if (isa<CXXRecordDecl>(DC)) {
11702 // Don't diagnose names we find in classes; we get much better
11703 // diagnostics for these from DiagnoseEmptyLookup.
11704 R.clear();
Hans Wennborg64937c62015-06-11 21:21:57 +000011705 if (DoDiagnoseEmptyLookup)
11706 *DoDiagnoseEmptyLookup = true;
Richard Smith998a5912011-06-05 22:42:48 +000011707 return false;
11708 }
11709
Richard Smith100b24a2014-04-17 01:52:14 +000011710 OverloadCandidateSet Candidates(FnLoc, CSK);
Richard Smith998a5912011-06-05 22:42:48 +000011711 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
11712 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011713 ExplicitTemplateArgs, Args,
Richard Smith95ce4f62011-06-26 22:19:54 +000011714 Candidates, false, /*KnownValid*/ false);
Richard Smith998a5912011-06-05 22:42:48 +000011715
11716 OverloadCandidateSet::iterator Best;
Richard Smith95ce4f62011-06-26 22:19:54 +000011717 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smith998a5912011-06-05 22:42:48 +000011718 // No viable functions. Don't bother the user with notes for functions
11719 // which don't work and shouldn't be found anyway.
Richard Smith95ce4f62011-06-26 22:19:54 +000011720 R.clear();
Richard Smith998a5912011-06-05 22:42:48 +000011721 return false;
Richard Smith95ce4f62011-06-26 22:19:54 +000011722 }
Richard Smith998a5912011-06-05 22:42:48 +000011723
11724 // Find the namespaces where ADL would have looked, and suggest
11725 // declaring the function there instead.
11726 Sema::AssociatedNamespaceSet AssociatedNamespaces;
11727 Sema::AssociatedClassSet AssociatedClasses;
John McCall7d8b0412012-08-24 20:38:34 +000011728 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
Richard Smith998a5912011-06-05 22:42:48 +000011729 AssociatedNamespaces,
11730 AssociatedClasses);
Chandler Carruthd50f1692011-06-05 23:36:55 +000011731 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smith0603bbb2013-06-12 22:56:54 +000011732 if (canBeDeclaredInNamespace(R.getLookupName())) {
11733 DeclContext *Std = SemaRef.getStdNamespace();
11734 for (Sema::AssociatedNamespaceSet::iterator
11735 it = AssociatedNamespaces.begin(),
11736 end = AssociatedNamespaces.end(); it != end; ++it) {
11737 // Never suggest declaring a function within namespace 'std'.
11738 if (Std && Std->Encloses(*it))
11739 continue;
Richard Smith21bae432012-12-22 02:46:14 +000011740
Richard Smith0603bbb2013-06-12 22:56:54 +000011741 // Never suggest declaring a function within a namespace with a
11742 // reserved name, like __gnu_cxx.
11743 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
11744 if (NS &&
11745 NS->getQualifiedNameAsString().find("__") != std::string::npos)
11746 continue;
11747
11748 SuggestedNamespaces.insert(*it);
11749 }
Richard Smith998a5912011-06-05 22:42:48 +000011750 }
11751
11752 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
11753 << R.getLookupName();
Chandler Carruthd50f1692011-06-05 23:36:55 +000011754 if (SuggestedNamespaces.empty()) {
Richard Smith998a5912011-06-05 22:42:48 +000011755 SemaRef.Diag(Best->Function->getLocation(),
11756 diag::note_not_found_by_two_phase_lookup)
11757 << R.getLookupName() << 0;
Chandler Carruthd50f1692011-06-05 23:36:55 +000011758 } else if (SuggestedNamespaces.size() == 1) {
Richard Smith998a5912011-06-05 22:42:48 +000011759 SemaRef.Diag(Best->Function->getLocation(),
11760 diag::note_not_found_by_two_phase_lookup)
Chandler Carruthd50f1692011-06-05 23:36:55 +000011761 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smith998a5912011-06-05 22:42:48 +000011762 } else {
11763 // FIXME: It would be useful to list the associated namespaces here,
11764 // but the diagnostics infrastructure doesn't provide a way to produce
11765 // a localized representation of a list of items.
11766 SemaRef.Diag(Best->Function->getLocation(),
11767 diag::note_not_found_by_two_phase_lookup)
11768 << R.getLookupName() << 2;
11769 }
11770
11771 // Try to recover by calling this function.
11772 return true;
11773 }
11774
11775 R.clear();
11776 }
11777
11778 return false;
11779}
11780
11781/// Attempt to recover from ill-formed use of a non-dependent operator in a
11782/// template, where the non-dependent operator was declared after the template
11783/// was defined.
11784///
11785/// Returns true if a viable candidate was found and a diagnostic was issued.
11786static bool
11787DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
11788 SourceLocation OpLoc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011789 ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +000011790 DeclarationName OpName =
11791 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
11792 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
11793 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Richard Smith100b24a2014-04-17 01:52:14 +000011794 OverloadCandidateSet::CSK_Operator,
Craig Topperc3ec1492014-05-26 06:22:03 +000011795 /*ExplicitTemplateArgs=*/nullptr, Args);
Richard Smith998a5912011-06-05 22:42:48 +000011796}
11797
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000011798namespace {
Richard Smith88d67f32012-09-25 04:46:05 +000011799class BuildRecoveryCallExprRAII {
11800 Sema &SemaRef;
11801public:
11802 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
11803 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
11804 SemaRef.IsBuildingRecoveryCallExpr = true;
11805 }
11806
11807 ~BuildRecoveryCallExprRAII() {
11808 SemaRef.IsBuildingRecoveryCallExpr = false;
11809 }
11810};
11811
Alexander Kornienkoab9db512015-06-22 23:07:51 +000011812}
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000011813
Kaelyn Takata89c881b2014-10-27 18:07:29 +000011814static std::unique_ptr<CorrectionCandidateCallback>
11815MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
11816 bool HasTemplateArgs, bool AllowTypoCorrection) {
11817 if (!AllowTypoCorrection)
11818 return llvm::make_unique<NoTypoCorrectionCCC>();
11819 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
11820 HasTemplateArgs, ME);
11821}
11822
John McCalld681c392009-12-16 08:11:27 +000011823/// Attempts to recover from a call where no functions were found.
11824///
11825/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +000011826static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +000011827BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +000011828 UnresolvedLookupExpr *ULE,
11829 SourceLocation LParenLoc,
Craig Toppere3d2ecbe2014-06-28 23:22:33 +000011830 MutableArrayRef<Expr *> Args,
Richard Smith998a5912011-06-05 22:42:48 +000011831 SourceLocation RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000011832 bool EmptyLookup, bool AllowTypoCorrection) {
Richard Smith88d67f32012-09-25 04:46:05 +000011833 // Do not try to recover if it is already building a recovery call.
11834 // This stops infinite loops for template instantiations like
11835 //
11836 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
11837 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
11838 //
11839 if (SemaRef.IsBuildingRecoveryCallExpr)
11840 return ExprError();
11841 BuildRecoveryCallExprRAII RCE(SemaRef);
John McCalld681c392009-12-16 08:11:27 +000011842
11843 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +000011844 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +000011845 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCalld681c392009-12-16 08:11:27 +000011846
John McCall57500772009-12-16 12:17:52 +000011847 TemplateArgumentListInfo TABuffer;
Craig Topperc3ec1492014-05-26 06:22:03 +000011848 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
John McCall57500772009-12-16 12:17:52 +000011849 if (ULE->hasExplicitTemplateArgs()) {
11850 ULE->copyTemplateArgumentsInto(TABuffer);
11851 ExplicitTemplateArgs = &TABuffer;
11852 }
11853
John McCalld681c392009-12-16 08:11:27 +000011854 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
11855 Sema::LookupOrdinaryName);
Hans Wennborg64937c62015-06-11 21:21:57 +000011856 bool DoDiagnoseEmptyLookup = EmptyLookup;
Richard Smith998a5912011-06-05 22:42:48 +000011857 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Richard Smith100b24a2014-04-17 01:52:14 +000011858 OverloadCandidateSet::CSK_Normal,
Hans Wennborg64937c62015-06-11 21:21:57 +000011859 ExplicitTemplateArgs, Args,
11860 &DoDiagnoseEmptyLookup) &&
11861 (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup(
11862 S, SS, R,
11863 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
11864 ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
11865 ExplicitTemplateArgs, Args)))
John McCallfaf5fb42010-08-26 23:41:50 +000011866 return ExprError();
John McCalld681c392009-12-16 08:11:27 +000011867
John McCall57500772009-12-16 12:17:52 +000011868 assert(!R.empty() && "lookup results empty despite recovery");
11869
Richard Smith151c4562016-12-20 21:35:28 +000011870 // If recovery created an ambiguity, just bail out.
11871 if (R.isAmbiguous()) {
11872 R.suppressDiagnostics();
11873 return ExprError();
11874 }
11875
John McCall57500772009-12-16 12:17:52 +000011876 // Build an implicit member call if appropriate. Just drop the
11877 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +000011878 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +000011879 if ((*R.begin())->isCXXClassMember())
Aaron Ballman6924dcd2015-09-01 14:49:24 +000011880 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
11881 ExplicitTemplateArgs, S);
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000011882 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnara7945c982012-01-27 09:46:47 +000011883 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000011884 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +000011885 else
11886 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
11887
11888 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +000011889 return ExprError();
John McCall57500772009-12-16 12:17:52 +000011890
11891 // This shouldn't cause an infinite loop because we're giving it
Richard Smith998a5912011-06-05 22:42:48 +000011892 // an expression with viable lookup results, which should never
John McCall57500772009-12-16 12:17:52 +000011893 // end up here.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011894 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011895 MultiExprArg(Args.data(), Args.size()),
11896 RParenLoc);
John McCalld681c392009-12-16 08:11:27 +000011897}
Douglas Gregor4038cf42010-06-08 17:35:15 +000011898
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011899/// Constructs and populates an OverloadedCandidateSet from
Sam Panzer0f384432012-08-21 00:52:01 +000011900/// the given function.
11901/// \returns true when an the ExprResult output parameter has been set.
11902bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
11903 UnresolvedLookupExpr *ULE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011904 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011905 SourceLocation RParenLoc,
11906 OverloadCandidateSet *CandidateSet,
11907 ExprResult *Result) {
John McCall57500772009-12-16 12:17:52 +000011908#ifndef NDEBUG
11909 if (ULE->requiresADL()) {
11910 // To do ADL, we must have found an unqualified name.
11911 assert(!ULE->getQualifier() && "qualified name with ADL");
11912
11913 // We don't perform ADL for implicit declarations of builtins.
11914 // Verify that this was correctly set up.
11915 FunctionDecl *F;
11916 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
11917 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
11918 F->getBuiltinID() && F->isImplicit())
David Blaikie83d382b2011-09-23 05:06:16 +000011919 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011920
John McCall57500772009-12-16 12:17:52 +000011921 // We don't perform ADL in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011922 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smithb6626742012-10-18 17:56:02 +000011923 }
John McCall57500772009-12-16 12:17:52 +000011924#endif
11925
John McCall4124c492011-10-17 18:40:02 +000011926 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011927 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
Sam Panzer0f384432012-08-21 00:52:01 +000011928 *Result = ExprError();
11929 return true;
11930 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +000011931
John McCall57500772009-12-16 12:17:52 +000011932 // Add the functions denoted by the callee to the set of candidate
11933 // functions, including those from argument-dependent lookup.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011934 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
John McCalld681c392009-12-16 08:11:27 +000011935
Hans Wennborgb2747382015-06-12 21:23:23 +000011936 if (getLangOpts().MSVCCompat &&
11937 CurContext->isDependentContext() && !isSFINAEContext() &&
Hans Wennborg64937c62015-06-11 21:21:57 +000011938 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
11939
11940 OverloadCandidateSet::iterator Best;
11941 if (CandidateSet->empty() ||
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011942 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
Hans Wennborg64937c62015-06-11 21:21:57 +000011943 OR_No_Viable_Function) {
11944 // In Microsoft mode, if we are inside a template class member function then
11945 // create a type dependent CallExpr. The goal is to postpone name lookup
11946 // to instantiation time to be able to search into type dependent base
11947 // classes.
11948 CallExpr *CE = new (Context) CallExpr(
11949 Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc);
Sebastian Redlb49c46c2011-09-24 17:48:00 +000011950 CE->setTypeDependent(true);
Richard Smithed9b8f02015-09-23 21:30:47 +000011951 CE->setValueDependent(true);
11952 CE->setInstantiationDependent(true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011953 *Result = CE;
Sam Panzer0f384432012-08-21 00:52:01 +000011954 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +000011955 }
Francois Pichetbcf64712011-09-07 00:14:57 +000011956 }
John McCalld681c392009-12-16 08:11:27 +000011957
Hans Wennborg64937c62015-06-11 21:21:57 +000011958 if (CandidateSet->empty())
11959 return false;
11960
John McCall4124c492011-10-17 18:40:02 +000011961 UnbridgedCasts.restore();
Sam Panzer0f384432012-08-21 00:52:01 +000011962 return false;
11963}
John McCall4124c492011-10-17 18:40:02 +000011964
Sam Panzer0f384432012-08-21 00:52:01 +000011965/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
11966/// the completed call expression. If overload resolution fails, emits
11967/// diagnostics and returns ExprError()
11968static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11969 UnresolvedLookupExpr *ULE,
11970 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011971 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011972 SourceLocation RParenLoc,
11973 Expr *ExecConfig,
11974 OverloadCandidateSet *CandidateSet,
11975 OverloadCandidateSet::iterator *Best,
11976 OverloadingResult OverloadResult,
11977 bool AllowTypoCorrection) {
11978 if (CandidateSet->empty())
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011979 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011980 RParenLoc, /*EmptyLookup=*/true,
11981 AllowTypoCorrection);
11982
11983 switch (OverloadResult) {
John McCall57500772009-12-16 12:17:52 +000011984 case OR_Success: {
Sam Panzer0f384432012-08-21 00:52:01 +000011985 FunctionDecl *FDecl = (*Best)->Function;
Sam Panzer0f384432012-08-21 00:52:01 +000011986 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000011987 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
11988 return ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000011989 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011990 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11991 ExecConfig);
John McCall57500772009-12-16 12:17:52 +000011992 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011993
Richard Smith998a5912011-06-05 22:42:48 +000011994 case OR_No_Viable_Function: {
11995 // Try to recover by looking for viable functions which the user might
11996 // have meant to call.
Sam Panzer0f384432012-08-21 00:52:01 +000011997 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011998 Args, RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000011999 /*EmptyLookup=*/false,
12000 AllowTypoCorrection);
Richard Smith998a5912011-06-05 22:42:48 +000012001 if (!Recovery.isInvalid())
12002 return Recovery;
12003
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000012004 // If the user passes in a function that we can't take the address of, we
12005 // generally end up emitting really bad error messages. Here, we attempt to
12006 // emit better ones.
12007 for (const Expr *Arg : Args) {
12008 if (!Arg->getType()->isFunctionType())
12009 continue;
12010 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
12011 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
12012 if (FD &&
12013 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
12014 Arg->getExprLoc()))
12015 return ExprError();
12016 }
12017 }
12018
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012019 SemaRef.Diag(Fn->getBeginLoc(), diag::err_ovl_no_viable_function_in_call)
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000012020 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012021 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000012022 break;
Richard Smith998a5912011-06-05 22:42:48 +000012023 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000012024
12025 case OR_Ambiguous:
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012026 SemaRef.Diag(Fn->getBeginLoc(), diag::err_ovl_ambiguous_call)
12027 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012028 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000012029 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000012030
Sam Panzer0f384432012-08-21 00:52:01 +000012031 case OR_Deleted: {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012032 SemaRef.Diag(Fn->getBeginLoc(), diag::err_ovl_deleted_call)
12033 << (*Best)->Function->isDeleted() << ULE->getName()
12034 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
12035 << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012036 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Argyrios Kyrtzidis3eaa22a2011-11-04 15:58:13 +000012037
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +000012038 // We emitted an error for the unavailable/deleted function call but keep
Sam Panzer0f384432012-08-21 00:52:01 +000012039 // the call in the AST.
12040 FunctionDecl *FDecl = (*Best)->Function;
12041 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012042 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
12043 ExecConfig);
Sam Panzer0f384432012-08-21 00:52:01 +000012044 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000012045 }
12046
Douglas Gregorb412e172010-07-25 18:17:45 +000012047 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +000012048 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +000012049}
12050
George Burgess IV7204ed92016-01-07 02:26:57 +000012051static void markUnaddressableCandidatesUnviable(Sema &S,
12052 OverloadCandidateSet &CS) {
12053 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
12054 if (I->Viable &&
12055 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
12056 I->Viable = false;
12057 I->FailureKind = ovl_fail_addr_not_available;
12058 }
12059 }
12060}
12061
Sam Panzer0f384432012-08-21 00:52:01 +000012062/// BuildOverloadedCallExpr - Given the call expression that calls Fn
12063/// (which eventually refers to the declaration Func) and the call
12064/// arguments Args/NumArgs, attempt to resolve the function call down
12065/// to a specific function. If overload resolution succeeds, returns
12066/// the call expression produced by overload resolution.
12067/// Otherwise, emits diagnostics and returns ExprError.
12068ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
12069 UnresolvedLookupExpr *ULE,
12070 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012071 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000012072 SourceLocation RParenLoc,
12073 Expr *ExecConfig,
George Burgess IV7204ed92016-01-07 02:26:57 +000012074 bool AllowTypoCorrection,
12075 bool CalleesAddressIsTaken) {
Richard Smith100b24a2014-04-17 01:52:14 +000012076 OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
12077 OverloadCandidateSet::CSK_Normal);
Sam Panzer0f384432012-08-21 00:52:01 +000012078 ExprResult result;
12079
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012080 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
12081 &result))
Sam Panzer0f384432012-08-21 00:52:01 +000012082 return result;
12083
George Burgess IV7204ed92016-01-07 02:26:57 +000012084 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
12085 // functions that aren't addressible are considered unviable.
12086 if (CalleesAddressIsTaken)
12087 markUnaddressableCandidatesUnviable(*this, CandidateSet);
12088
Sam Panzer0f384432012-08-21 00:52:01 +000012089 OverloadCandidateSet::iterator Best;
12090 OverloadingResult OverloadResult =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012091 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
Sam Panzer0f384432012-08-21 00:52:01 +000012092
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012093 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000012094 RParenLoc, ExecConfig, &CandidateSet,
12095 &Best, OverloadResult,
12096 AllowTypoCorrection);
12097}
12098
John McCall4c4c1df2010-01-26 03:27:55 +000012099static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +000012100 return Functions.size() > 1 ||
12101 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
12102}
12103
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012104/// Create a unary operation that may resolve to an overloaded
Douglas Gregor084d8552009-03-13 23:49:33 +000012105/// operator.
12106///
12107/// \param OpLoc The location of the operator itself (e.g., '*').
12108///
Craig Toppera92ffb02015-12-10 08:51:49 +000012109/// \param Opc The UnaryOperatorKind that describes this operator.
Douglas Gregor084d8552009-03-13 23:49:33 +000012110///
James Dennett18348b62012-06-22 08:52:37 +000012111/// \param Fns The set of non-member functions that will be
Douglas Gregor084d8552009-03-13 23:49:33 +000012112/// considered by overload resolution. The caller needs to build this
12113/// set based on the context using, e.g.,
12114/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12115/// set should not contain any member functions; those will be added
12116/// by CreateOverloadedUnaryOp().
12117///
James Dennett91738ff2012-06-22 10:32:46 +000012118/// \param Input The input argument.
John McCalldadc5752010-08-24 06:29:42 +000012119ExprResult
Craig Toppera92ffb02015-12-10 08:51:49 +000012120Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
John McCall4c4c1df2010-01-26 03:27:55 +000012121 const UnresolvedSetImpl &Fns,
Richard Smith91fc7d82017-10-05 19:35:51 +000012122 Expr *Input, bool PerformADL) {
Douglas Gregor084d8552009-03-13 23:49:33 +000012123 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
12124 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
12125 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000012126 // TODO: provide better source location info.
12127 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +000012128
John McCall4124c492011-10-17 18:40:02 +000012129 if (checkPlaceholderForOverload(*this, Input))
12130 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012131
Craig Topperc3ec1492014-05-26 06:22:03 +000012132 Expr *Args[2] = { Input, nullptr };
Douglas Gregor084d8552009-03-13 23:49:33 +000012133 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +000012134
Douglas Gregor084d8552009-03-13 23:49:33 +000012135 // For post-increment and post-decrement, add the implicit '0' as
12136 // the second argument, so that we know this is a post-increment or
12137 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +000012138 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +000012139 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +000012140 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
12141 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +000012142 NumArgs = 2;
12143 }
12144
Richard Smithe54c3072013-05-05 15:51:06 +000012145 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
12146
Douglas Gregor084d8552009-03-13 23:49:33 +000012147 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +000012148 if (Fns.empty())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012149 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
Aaron Ballmana5038552018-01-09 13:07:03 +000012150 VK_RValue, OK_Ordinary, OpLoc, false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012151
Craig Topperc3ec1492014-05-26 06:22:03 +000012152 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +000012153 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000012154 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000012155 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000012156 /*ADL*/ true, IsOverloaded(Fns),
12157 Fns.begin(), Fns.end());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012158 return new (Context)
12159 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
Adam Nemet484aa452017-03-27 19:17:25 +000012160 VK_RValue, OpLoc, FPOptions());
Douglas Gregor084d8552009-03-13 23:49:33 +000012161 }
12162
12163 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000012164 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
Douglas Gregor084d8552009-03-13 23:49:33 +000012165
12166 // Add the candidates from the given function set.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000012167 AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000012168
12169 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000012170 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000012171
John McCall4c4c1df2010-01-26 03:27:55 +000012172 // Add candidates from ADL.
Richard Smith91fc7d82017-10-05 19:35:51 +000012173 if (PerformADL) {
12174 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
12175 /*ExplicitTemplateArgs*/nullptr,
12176 CandidateSet);
12177 }
John McCall4c4c1df2010-01-26 03:27:55 +000012178
Douglas Gregor084d8552009-03-13 23:49:33 +000012179 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000012180 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000012181
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012182 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12183
Douglas Gregor084d8552009-03-13 23:49:33 +000012184 // Perform overload resolution.
12185 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012186 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +000012187 case OR_Success: {
12188 // We found a built-in operator or an overloaded operator.
12189 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +000012190
Douglas Gregor084d8552009-03-13 23:49:33 +000012191 if (FnDecl) {
Akira Hatanaka22461672017-07-13 06:08:27 +000012192 Expr *Base = nullptr;
Douglas Gregor084d8552009-03-13 23:49:33 +000012193 // We matched an overloaded operator. Build a call to that
12194 // operator.
Mike Stump11289f42009-09-09 15:08:12 +000012195
Douglas Gregor084d8552009-03-13 23:49:33 +000012196 // Convert the arguments.
12197 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Craig Topperc3ec1492014-05-26 06:22:03 +000012198 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000012199
John Wiegley01296292011-04-08 18:41:53 +000012200 ExprResult InputRes =
Craig Topperc3ec1492014-05-26 06:22:03 +000012201 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012202 Best->FoundDecl, Method);
12203 if (InputRes.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000012204 return ExprError();
Akira Hatanaka22461672017-07-13 06:08:27 +000012205 Base = Input = InputRes.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000012206 } else {
12207 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000012208 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +000012209 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000012210 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +000012211 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012212 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +000012213 Input);
Douglas Gregore6600372009-12-23 17:40:29 +000012214 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000012215 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012216 Input = InputInit.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000012217 }
12218
Douglas Gregor084d8552009-03-13 23:49:33 +000012219 // Build the actual expression node.
Nick Lewycky134af912013-02-07 05:08:22 +000012220 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
Akira Hatanaka22461672017-07-13 06:08:27 +000012221 Base, HadMultipleCandidates,
12222 OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000012223 if (FnExpr.isInvalid())
12224 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +000012225
Richard Smithc1564702013-11-15 02:58:23 +000012226 // Determine the result type.
Alp Toker314cc812014-01-25 16:55:45 +000012227 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000012228 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12229 ResultTy = ResultTy.getNonLValueExprType(Context);
12230
Eli Friedman030eee42009-11-18 03:58:17 +000012231 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +000012232 CallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012233 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
Adam Nemet484aa452017-03-27 19:17:25 +000012234 ResultTy, VK, OpLoc, FPOptions());
John McCall4fa0d5f2010-05-06 18:15:07 +000012235
Alp Toker314cc812014-01-25 16:55:45 +000012236 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
Anders Carlssonf64a3da2009-10-13 21:19:37 +000012237 return ExprError();
12238
George Burgess IVce6284b2017-01-28 02:19:40 +000012239 if (CheckFunctionCall(FnDecl, TheCall,
12240 FnDecl->getType()->castAs<FunctionProtoType>()))
12241 return ExprError();
12242
John McCallb268a282010-08-23 23:25:46 +000012243 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +000012244 } else {
12245 // We matched a built-in operator. Convert the arguments, then
12246 // break out so that we will build the appropriate built-in
12247 // operator node.
George Burgess IV5f6ab9a2017-06-08 20:55:21 +000012248 ExprResult InputRes = PerformImplicitConversion(
Richard Smith1ef75542018-06-27 20:30:34 +000012249 Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing,
12250 CCK_ForBuiltinOverloadedOp);
John Wiegley01296292011-04-08 18:41:53 +000012251 if (InputRes.isInvalid())
12252 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012253 Input = InputRes.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000012254 break;
Douglas Gregor084d8552009-03-13 23:49:33 +000012255 }
John Wiegley01296292011-04-08 18:41:53 +000012256 }
12257
12258 case OR_No_Viable_Function:
Richard Smith998a5912011-06-05 22:42:48 +000012259 // This is an erroneous use of an operator which can be overloaded by
12260 // a non-member function. Check for non-member operators which were
12261 // defined too late to be candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000012262 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
Richard Smith998a5912011-06-05 22:42:48 +000012263 // FIXME: Recover by calling the found function.
12264 return ExprError();
12265
John Wiegley01296292011-04-08 18:41:53 +000012266 // No viable function; fall through to handling this as a
12267 // built-in operator, which will produce an error message for us.
12268 break;
12269
12270 case OR_Ambiguous:
12271 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
12272 << UnaryOperator::getOpcodeStr(Opc)
12273 << Input->getType()
12274 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000012275 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
John Wiegley01296292011-04-08 18:41:53 +000012276 UnaryOperator::getOpcodeStr(Opc), OpLoc);
12277 return ExprError();
12278
12279 case OR_Deleted:
12280 Diag(OpLoc, diag::err_ovl_deleted_oper)
12281 << Best->Function->isDeleted()
12282 << UnaryOperator::getOpcodeStr(Opc)
12283 << getDeletedOrUnavailableSuffix(Best->Function)
12284 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000012285 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000012286 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000012287 return ExprError();
12288 }
Douglas Gregor084d8552009-03-13 23:49:33 +000012289
12290 // Either we found no viable overloaded operator or we matched a
12291 // built-in operator. In either case, fall through to trying to
12292 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +000012293 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +000012294}
12295
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012296/// Create a binary operation that may resolve to an overloaded
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012297/// operator.
12298///
12299/// \param OpLoc The location of the operator itself (e.g., '+').
12300///
Craig Toppera92ffb02015-12-10 08:51:49 +000012301/// \param Opc The BinaryOperatorKind that describes this operator.
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012302///
James Dennett18348b62012-06-22 08:52:37 +000012303/// \param Fns The set of non-member functions that will be
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012304/// considered by overload resolution. The caller needs to build this
12305/// set based on the context using, e.g.,
12306/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12307/// set should not contain any member functions; those will be added
12308/// by CreateOverloadedBinOp().
12309///
12310/// \param LHS Left-hand argument.
12311/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +000012312ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012313Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Craig Toppera92ffb02015-12-10 08:51:49 +000012314 BinaryOperatorKind Opc,
John McCall4c4c1df2010-01-26 03:27:55 +000012315 const UnresolvedSetImpl &Fns,
Richard Smith91fc7d82017-10-05 19:35:51 +000012316 Expr *LHS, Expr *RHS, bool PerformADL) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012317 Expr *Args[2] = { LHS, RHS };
Craig Topperc3ec1492014-05-26 06:22:03 +000012318 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012319
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012320 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
12321 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12322
12323 // If either side is type-dependent, create an appropriate dependent
12324 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +000012325 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +000012326 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012327 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +000012328 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +000012329 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012330 return new (Context) BinaryOperator(
12331 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
Adam Nemet484aa452017-03-27 19:17:25 +000012332 OpLoc, FPFeatures);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012333
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012334 return new (Context) CompoundAssignOperator(
12335 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
12336 Context.DependentTy, Context.DependentTy, OpLoc,
Adam Nemet484aa452017-03-27 19:17:25 +000012337 FPFeatures);
Douglas Gregor5287f092009-11-05 00:51:44 +000012338 }
John McCall4c4c1df2010-01-26 03:27:55 +000012339
12340 // FIXME: save results of ADL from here?
Craig Topperc3ec1492014-05-26 06:22:03 +000012341 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000012342 // TODO: provide better source location info in DNLoc component.
12343 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +000012344 UnresolvedLookupExpr *Fn
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000012345 = UnresolvedLookupExpr::Create(Context, NamingClass,
12346 NestedNameSpecifierLoc(), OpNameInfo,
Richard Smith91fc7d82017-10-05 19:35:51 +000012347 /*ADL*/PerformADL, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000012348 Fns.begin(), Fns.end());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012349 return new (Context)
12350 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
Adam Nemet484aa452017-03-27 19:17:25 +000012351 VK_RValue, OpLoc, FPFeatures);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012352 }
12353
John McCall4124c492011-10-17 18:40:02 +000012354 // Always do placeholder-like conversions on the RHS.
12355 if (checkPlaceholderForOverload(*this, Args[1]))
12356 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012357
John McCall526ab472011-10-25 17:37:35 +000012358 // Do placeholder-like conversion on the LHS; note that we should
12359 // not get here with a PseudoObject LHS.
12360 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall4124c492011-10-17 18:40:02 +000012361 if (checkPlaceholderForOverload(*this, Args[0]))
12362 return ExprError();
12363
Sebastian Redl6a96bf72009-11-18 23:10:33 +000012364 // If this is the assignment operator, we only perform overload resolution
12365 // if the left-hand side is a class or enumeration type. This is actually
12366 // a hack. The standard requires that we do overload resolution between the
12367 // various built-in candidates, but as DR507 points out, this can lead to
12368 // problems. So we do it this way, which pretty much follows what GCC does.
12369 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +000012370 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +000012371 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012372
John McCalle26a8722010-12-04 08:14:53 +000012373 // If this is the .* operator, which is not overloadable, just
12374 // create a built-in binary operator.
12375 if (Opc == BO_PtrMemD)
12376 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12377
Douglas Gregor084d8552009-03-13 23:49:33 +000012378 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000012379 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012380
12381 // Add the candidates from the given function set.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000012382 AddFunctionCandidates(Fns, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012383
12384 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000012385 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012386
Richard Smith0daabd72014-09-23 20:31:39 +000012387 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
12388 // performed for an assignment operator (nor for operator[] nor operator->,
12389 // which don't get here).
Richard Smith91fc7d82017-10-05 19:35:51 +000012390 if (Opc != BO_Assign && PerformADL)
Richard Smith0daabd72014-09-23 20:31:39 +000012391 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
12392 /*ExplicitTemplateArgs*/ nullptr,
12393 CandidateSet);
John McCall4c4c1df2010-01-26 03:27:55 +000012394
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012395 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000012396 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012397
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012398 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12399
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012400 // Perform overload resolution.
12401 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012402 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +000012403 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012404 // We found a built-in operator or an overloaded operator.
12405 FunctionDecl *FnDecl = Best->Function;
12406
12407 if (FnDecl) {
Akira Hatanaka22461672017-07-13 06:08:27 +000012408 Expr *Base = nullptr;
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012409 // We matched an overloaded operator. Build a call to that
12410 // operator.
12411
12412 // Convert the arguments.
12413 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +000012414 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +000012415 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000012416
Chandler Carruth8e543b32010-12-12 08:17:55 +000012417 ExprResult Arg1 =
12418 PerformCopyInitialization(
12419 InitializedEntity::InitializeParameter(Context,
12420 FnDecl->getParamDecl(0)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012421 SourceLocation(), Args[1]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000012422 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012423 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000012424
John Wiegley01296292011-04-08 18:41:53 +000012425 ExprResult Arg0 =
Craig Topperc3ec1492014-05-26 06:22:03 +000012426 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012427 Best->FoundDecl, Method);
12428 if (Arg0.isInvalid())
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000012429 return ExprError();
Akira Hatanaka22461672017-07-13 06:08:27 +000012430 Base = Args[0] = Arg0.getAs<Expr>();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012431 Args[1] = RHS = Arg1.getAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012432 } else {
12433 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +000012434 ExprResult Arg0 = PerformCopyInitialization(
12435 InitializedEntity::InitializeParameter(Context,
12436 FnDecl->getParamDecl(0)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012437 SourceLocation(), Args[0]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000012438 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012439 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000012440
Chandler Carruth8e543b32010-12-12 08:17:55 +000012441 ExprResult Arg1 =
12442 PerformCopyInitialization(
12443 InitializedEntity::InitializeParameter(Context,
12444 FnDecl->getParamDecl(1)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012445 SourceLocation(), Args[1]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000012446 if (Arg1.isInvalid())
12447 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012448 Args[0] = LHS = Arg0.getAs<Expr>();
12449 Args[1] = RHS = Arg1.getAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012450 }
12451
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012452 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012453 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Akira Hatanaka22461672017-07-13 06:08:27 +000012454 Best->FoundDecl, Base,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012455 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000012456 if (FnExpr.isInvalid())
12457 return ExprError();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012458
Richard Smithc1564702013-11-15 02:58:23 +000012459 // Determine the result type.
Alp Toker314cc812014-01-25 16:55:45 +000012460 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000012461 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12462 ResultTy = ResultTy.getNonLValueExprType(Context);
12463
John McCallb268a282010-08-23 23:25:46 +000012464 CXXOperatorCallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012465 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
Lang Hames5de91cc2012-10-02 04:45:10 +000012466 Args, ResultTy, VK, OpLoc,
Adam Nemet484aa452017-03-27 19:17:25 +000012467 FPFeatures);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012468
Alp Toker314cc812014-01-25 16:55:45 +000012469 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000012470 FnDecl))
12471 return ExprError();
12472
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000012473 ArrayRef<const Expr *> ArgsArray(Args, 2);
George Burgess IVce6284b2017-01-28 02:19:40 +000012474 const Expr *ImplicitThis = nullptr;
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000012475 // Cut off the implicit 'this'.
George Burgess IVce6284b2017-01-28 02:19:40 +000012476 if (isa<CXXMethodDecl>(FnDecl)) {
12477 ImplicitThis = ArgsArray[0];
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000012478 ArgsArray = ArgsArray.slice(1);
George Burgess IVce6284b2017-01-28 02:19:40 +000012479 }
Richard Trieu36d0b2b2015-01-13 02:32:02 +000012480
12481 // Check for a self move.
12482 if (Op == OO_Equal)
12483 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
12484
George Burgess IVce6284b2017-01-28 02:19:40 +000012485 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
12486 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
12487 VariadicDoesNotApply);
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000012488
John McCallb268a282010-08-23 23:25:46 +000012489 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012490 } else {
12491 // We matched a built-in operator. Convert the arguments, then
12492 // break out so that we will build the appropriate built-in
12493 // operator node.
Richard Smith1ef75542018-06-27 20:30:34 +000012494 ExprResult ArgsRes0 = PerformImplicitConversion(
12495 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
12496 AA_Passing, CCK_ForBuiltinOverloadedOp);
John Wiegley01296292011-04-08 18:41:53 +000012497 if (ArgsRes0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012498 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012499 Args[0] = ArgsRes0.get();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012500
Richard Smith1ef75542018-06-27 20:30:34 +000012501 ExprResult ArgsRes1 = PerformImplicitConversion(
12502 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
12503 AA_Passing, CCK_ForBuiltinOverloadedOp);
John Wiegley01296292011-04-08 18:41:53 +000012504 if (ArgsRes1.isInvalid())
12505 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012506 Args[1] = ArgsRes1.get();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012507 break;
12508 }
12509 }
12510
Douglas Gregor66950a32009-09-30 21:46:01 +000012511 case OR_No_Viable_Function: {
12512 // C++ [over.match.oper]p9:
12513 // If the operator is the operator , [...] and there are no
12514 // viable functions, then the operator is assumed to be the
12515 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +000012516 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +000012517 break;
12518
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +000012519 // For class as left operand for assignment or compound assignment
Chandler Carruth8e543b32010-12-12 08:17:55 +000012520 // operator do not fall through to handling in built-in, but report that
12521 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +000012522 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012523 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +000012524 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +000012525 Diag(OpLoc, diag::err_ovl_no_viable_oper)
12526 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +000012527 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Eli Friedmana31efa02013-08-28 20:35:35 +000012528 if (Args[0]->getType()->isIncompleteType()) {
12529 Diag(OpLoc, diag::note_assign_lhs_incomplete)
12530 << Args[0]->getType()
12531 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12532 }
Douglas Gregor66950a32009-09-30 21:46:01 +000012533 } else {
Richard Smith998a5912011-06-05 22:42:48 +000012534 // This is an erroneous use of an operator which can be overloaded by
12535 // a non-member function. Check for non-member operators which were
12536 // defined too late to be candidates.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012537 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smith998a5912011-06-05 22:42:48 +000012538 // FIXME: Recover by calling the found function.
12539 return ExprError();
12540
Douglas Gregor66950a32009-09-30 21:46:01 +000012541 // No viable function; try to create a built-in operation, which will
12542 // produce an error. Then, show the non-viable candidates.
12543 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +000012544 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012545 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +000012546 "C++ binary operator overloading is missing candidates!");
12547 if (Result.isInvalid())
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012548 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012549 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012550 return Result;
Douglas Gregor66950a32009-09-30 21:46:01 +000012551 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012552
12553 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000012554 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012555 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +000012556 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +000012557 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012558 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012559 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012560 return ExprError();
12561
12562 case OR_Deleted:
Douglas Gregor74f7d502012-02-15 19:33:52 +000012563 if (isImplicitlyDeleted(Best->Function)) {
12564 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12565 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
Richard Smithde1a4872012-12-28 12:23:24 +000012566 << Context.getRecordType(Method->getParent())
12567 << getSpecialMember(Method);
Richard Smith6f1e2c62012-04-02 20:59:25 +000012568
Richard Smithde1a4872012-12-28 12:23:24 +000012569 // The user probably meant to call this special member. Just
12570 // explain why it's deleted.
12571 NoteDeletedFunction(Method);
12572 return ExprError();
Douglas Gregor74f7d502012-02-15 19:33:52 +000012573 } else {
12574 Diag(OpLoc, diag::err_ovl_deleted_oper)
12575 << Best->Function->isDeleted()
12576 << BinaryOperator::getOpcodeStr(Opc)
12577 << getDeletedOrUnavailableSuffix(Best->Function)
12578 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12579 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012580 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000012581 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012582 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +000012583 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012584
Douglas Gregor66950a32009-09-30 21:46:01 +000012585 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +000012586 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012587}
12588
John McCalldadc5752010-08-24 06:29:42 +000012589ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +000012590Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
12591 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +000012592 Expr *Base, Expr *Idx) {
12593 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +000012594 DeclarationName OpName =
12595 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
12596
12597 // If either side is type-dependent, create an appropriate dependent
12598 // expression.
12599 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12600
Craig Topperc3ec1492014-05-26 06:22:03 +000012601 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000012602 // CHECKME: no 'operator' keyword?
12603 DeclarationNameInfo OpNameInfo(OpName, LLoc);
12604 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +000012605 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000012606 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000012607 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000012608 /*ADL*/ true, /*Overloaded*/ false,
12609 UnresolvedSetIterator(),
12610 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +000012611 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +000012612
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012613 return new (Context)
12614 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
Adam Nemet484aa452017-03-27 19:17:25 +000012615 Context.DependentTy, VK_RValue, RLoc, FPOptions());
Sebastian Redladba46e2009-10-29 20:17:01 +000012616 }
12617
John McCall4124c492011-10-17 18:40:02 +000012618 // Handle placeholders on both operands.
12619 if (checkPlaceholderForOverload(*this, Args[0]))
12620 return ExprError();
12621 if (checkPlaceholderForOverload(*this, Args[1]))
12622 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012623
Sebastian Redladba46e2009-10-29 20:17:01 +000012624 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000012625 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
Sebastian Redladba46e2009-10-29 20:17:01 +000012626
12627 // Subscript can only be overloaded as a member function.
12628
12629 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000012630 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000012631
12632 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000012633 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000012634
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012635 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12636
Sebastian Redladba46e2009-10-29 20:17:01 +000012637 // Perform overload resolution.
12638 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012639 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +000012640 case OR_Success: {
12641 // We found a built-in operator or an overloaded operator.
12642 FunctionDecl *FnDecl = Best->Function;
12643
12644 if (FnDecl) {
12645 // We matched an overloaded operator. Build a call to that
12646 // operator.
12647
John McCalla0296f72010-03-19 07:35:19 +000012648 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall58cc69d2010-01-27 01:50:18 +000012649
Sebastian Redladba46e2009-10-29 20:17:01 +000012650 // Convert the arguments.
12651 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley01296292011-04-08 18:41:53 +000012652 ExprResult Arg0 =
Craig Topperc3ec1492014-05-26 06:22:03 +000012653 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012654 Best->FoundDecl, Method);
12655 if (Arg0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000012656 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012657 Args[0] = Arg0.get();
Sebastian Redladba46e2009-10-29 20:17:01 +000012658
Anders Carlssona68e51e2010-01-29 18:37:50 +000012659 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000012660 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +000012661 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000012662 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +000012663 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012664 SourceLocation(),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012665 Args[1]);
Anders Carlssona68e51e2010-01-29 18:37:50 +000012666 if (InputInit.isInvalid())
12667 return ExprError();
12668
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012669 Args[1] = InputInit.getAs<Expr>();
Anders Carlssona68e51e2010-01-29 18:37:50 +000012670
Sebastian Redladba46e2009-10-29 20:17:01 +000012671 // Build the actual expression node.
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012672 DeclarationNameInfo OpLocInfo(OpName, LLoc);
12673 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012674 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000012675 Best->FoundDecl,
Akira Hatanaka22461672017-07-13 06:08:27 +000012676 Base,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012677 HadMultipleCandidates,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012678 OpLocInfo.getLoc(),
12679 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000012680 if (FnExpr.isInvalid())
12681 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000012682
Richard Smithc1564702013-11-15 02:58:23 +000012683 // Determine the result type
Alp Toker314cc812014-01-25 16:55:45 +000012684 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000012685 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12686 ResultTy = ResultTy.getNonLValueExprType(Context);
12687
John McCallb268a282010-08-23 23:25:46 +000012688 CXXOperatorCallExpr *TheCall =
12689 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012690 FnExpr.get(), Args,
Lang Hames5de91cc2012-10-02 04:45:10 +000012691 ResultTy, VK, RLoc,
Adam Nemet484aa452017-03-27 19:17:25 +000012692 FPOptions());
Sebastian Redladba46e2009-10-29 20:17:01 +000012693
Alp Toker314cc812014-01-25 16:55:45 +000012694 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
Sebastian Redladba46e2009-10-29 20:17:01 +000012695 return ExprError();
12696
George Burgess IVce6284b2017-01-28 02:19:40 +000012697 if (CheckFunctionCall(Method, TheCall,
12698 Method->getType()->castAs<FunctionProtoType>()))
12699 return ExprError();
12700
John McCallb268a282010-08-23 23:25:46 +000012701 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +000012702 } else {
12703 // We matched a built-in operator. Convert the arguments, then
12704 // break out so that we will build the appropriate built-in
12705 // operator node.
Richard Smith1ef75542018-06-27 20:30:34 +000012706 ExprResult ArgsRes0 = PerformImplicitConversion(
12707 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
12708 AA_Passing, CCK_ForBuiltinOverloadedOp);
John Wiegley01296292011-04-08 18:41:53 +000012709 if (ArgsRes0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000012710 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012711 Args[0] = ArgsRes0.get();
John Wiegley01296292011-04-08 18:41:53 +000012712
Richard Smith1ef75542018-06-27 20:30:34 +000012713 ExprResult ArgsRes1 = PerformImplicitConversion(
12714 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
12715 AA_Passing, CCK_ForBuiltinOverloadedOp);
John Wiegley01296292011-04-08 18:41:53 +000012716 if (ArgsRes1.isInvalid())
12717 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012718 Args[1] = ArgsRes1.get();
Sebastian Redladba46e2009-10-29 20:17:01 +000012719
12720 break;
12721 }
12722 }
12723
12724 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +000012725 if (CandidateSet.empty())
12726 Diag(LLoc, diag::err_ovl_no_oper)
12727 << Args[0]->getType() << /*subscript*/ 0
12728 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12729 else
12730 Diag(LLoc, diag::err_ovl_no_viable_subscript)
12731 << Args[0]->getType()
12732 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012733 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012734 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +000012735 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000012736 }
12737
12738 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000012739 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012740 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +000012741 << Args[0]->getType() << Args[1]->getType()
12742 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012743 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012744 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000012745 return ExprError();
12746
12747 case OR_Deleted:
12748 Diag(LLoc, diag::err_ovl_deleted_oper)
12749 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012750 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +000012751 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012752 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012753 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000012754 return ExprError();
12755 }
12756
12757 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +000012758 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000012759}
12760
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012761/// BuildCallToMemberFunction - Build a call to a member
12762/// function. MemExpr is the expression that refers to the member
12763/// function (and includes the object parameter), Args/NumArgs are the
12764/// arguments to the function call (not including the object
12765/// parameter). The caller needs to validate that the member
John McCall0009fcc2011-04-26 20:42:42 +000012766/// expression refers to a non-static member function or an overloaded
12767/// member function.
John McCalldadc5752010-08-24 06:29:42 +000012768ExprResult
Mike Stump11289f42009-09-09 15:08:12 +000012769Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012770 SourceLocation LParenLoc,
12771 MultiExprArg Args,
12772 SourceLocation RParenLoc) {
John McCall0009fcc2011-04-26 20:42:42 +000012773 assert(MemExprE->getType() == Context.BoundMemberTy ||
12774 MemExprE->getType() == Context.OverloadTy);
12775
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012776 // Dig out the member expression. This holds both the object
12777 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +000012778 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012779
John McCall0009fcc2011-04-26 20:42:42 +000012780 // Determine whether this is a call to a pointer-to-member function.
12781 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
12782 assert(op->getType() == Context.BoundMemberTy);
12783 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
12784
12785 QualType fnType =
12786 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
12787
12788 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
12789 QualType resultType = proto->getCallResultType(Context);
Alp Toker314cc812014-01-25 16:55:45 +000012790 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
John McCall0009fcc2011-04-26 20:42:42 +000012791
12792 // Check that the object type isn't more qualified than the
12793 // member function we're calling.
12794 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
12795
12796 QualType objectType = op->getLHS()->getType();
12797 if (op->getOpcode() == BO_PtrMemI)
12798 objectType = objectType->castAs<PointerType>()->getPointeeType();
12799 Qualifiers objectQuals = objectType.getQualifiers();
12800
12801 Qualifiers difference = objectQuals - funcQuals;
12802 difference.removeObjCGCAttr();
12803 difference.removeAddressSpace();
12804 if (difference) {
12805 std::string qualsString = difference.getAsString();
12806 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
12807 << fnType.getUnqualifiedType()
12808 << qualsString
12809 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
12810 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +000012811
John McCall0009fcc2011-04-26 20:42:42 +000012812 CXXMemberCallExpr *call
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012813 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall0009fcc2011-04-26 20:42:42 +000012814 resultType, valueKind, RParenLoc);
12815
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012816 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
Craig Topperc3ec1492014-05-26 06:22:03 +000012817 call, nullptr))
John McCall0009fcc2011-04-26 20:42:42 +000012818 return ExprError();
12819
Craig Topperc3ec1492014-05-26 06:22:03 +000012820 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
John McCall0009fcc2011-04-26 20:42:42 +000012821 return ExprError();
12822
Richard Trieu9be9c682013-06-22 02:30:38 +000012823 if (CheckOtherCall(call, proto))
12824 return ExprError();
12825
John McCall0009fcc2011-04-26 20:42:42 +000012826 return MaybeBindToTemporary(call);
12827 }
12828
David Majnemerced8bdf2015-02-25 17:36:15 +000012829 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
12830 return new (Context)
12831 CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc);
12832
John McCall4124c492011-10-17 18:40:02 +000012833 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012834 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000012835 return ExprError();
12836
John McCall10eae182009-11-30 22:42:35 +000012837 MemberExpr *MemExpr;
Craig Topperc3ec1492014-05-26 06:22:03 +000012838 CXXMethodDecl *Method = nullptr;
12839 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
12840 NestedNameSpecifier *Qualifier = nullptr;
John McCall10eae182009-11-30 22:42:35 +000012841 if (isa<MemberExpr>(NakedMemExpr)) {
12842 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +000012843 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +000012844 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +000012845 Qualifier = MemExpr->getQualifier();
John McCall4124c492011-10-17 18:40:02 +000012846 UnbridgedCasts.restore();
John McCall10eae182009-11-30 22:42:35 +000012847 } else {
12848 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +000012849 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012850
John McCall6e9f8f62009-12-03 04:06:58 +000012851 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +000012852 Expr::Classification ObjectClassification
12853 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
12854 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +000012855
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012856 // Add overload candidates
Richard Smith100b24a2014-04-17 01:52:14 +000012857 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
12858 OverloadCandidateSet::CSK_Normal);
Mike Stump11289f42009-09-09 15:08:12 +000012859
John McCall2d74de92009-12-01 22:10:20 +000012860 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000012861 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCall2d74de92009-12-01 22:10:20 +000012862 if (UnresExpr->hasExplicitTemplateArgs()) {
12863 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12864 TemplateArgs = &TemplateArgsBuffer;
12865 }
12866
John McCall10eae182009-11-30 22:42:35 +000012867 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
12868 E = UnresExpr->decls_end(); I != E; ++I) {
12869
John McCall6e9f8f62009-12-03 04:06:58 +000012870 NamedDecl *Func = *I;
12871 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
12872 if (isa<UsingShadowDecl>(Func))
12873 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
12874
Douglas Gregor02824322011-01-26 19:30:28 +000012875
Francois Pichet64225792011-01-18 05:04:39 +000012876 // Microsoft supports direct constructor calls.
David Blaikiebbafb8a2012-03-11 07:00:24 +000012877 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012878 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012879 Args, CandidateSet);
Francois Pichet64225792011-01-18 05:04:39 +000012880 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +000012881 // If explicit template arguments were provided, we can't call a
12882 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +000012883 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +000012884 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012885
John McCalla0296f72010-03-19 07:35:19 +000012886 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
George Burgess IVce6284b2017-01-28 02:19:40 +000012887 ObjectClassification, Args, CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +000012888 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000012889 } else {
George Burgess IV177399e2017-01-09 04:12:14 +000012890 AddMethodTemplateCandidate(
12891 cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC,
George Burgess IVce6284b2017-01-28 02:19:40 +000012892 TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet,
George Burgess IV177399e2017-01-09 04:12:14 +000012893 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000012894 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000012895 }
Mike Stump11289f42009-09-09 15:08:12 +000012896
John McCall10eae182009-11-30 22:42:35 +000012897 DeclarationName DeclName = UnresExpr->getMemberName();
12898
John McCall4124c492011-10-17 18:40:02 +000012899 UnbridgedCasts.restore();
12900
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012901 OverloadCandidateSet::iterator Best;
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012902 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
Nick Lewycky9331ed82010-11-20 01:29:55 +000012903 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012904 case OR_Success:
12905 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +000012906 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +000012907 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000012908 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
12909 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000012910 // If FoundDecl is different from Method (such as if one is a template
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000012911 // and the other a specialization), make sure DiagnoseUseOfDecl is
Faisal Valid6676412013-06-15 11:54:37 +000012912 // called on both.
12913 // FIXME: This would be more comprehensively addressed by modifying
12914 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
12915 // being used.
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000012916 if (Method != FoundDecl.getDecl() &&
Faisal Valid6676412013-06-15 11:54:37 +000012917 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
12918 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012919 break;
12920
12921 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +000012922 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012923 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000012924 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012925 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012926 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000012927 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012928
12929 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +000012930 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000012931 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012932 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012933 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000012934 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000012935
12936 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +000012937 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +000012938 << Best->Function->isDeleted()
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000012939 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012940 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012941 << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012942 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000012943 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000012944 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012945 }
12946
John McCall16df1e52010-03-30 21:47:33 +000012947 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +000012948
John McCall2d74de92009-12-01 22:10:20 +000012949 // If overload resolution picked a static member, build a
12950 // non-member call based on that function.
12951 if (Method->isStatic()) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012952 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
12953 RParenLoc);
John McCall2d74de92009-12-01 22:10:20 +000012954 }
12955
John McCall10eae182009-11-30 22:42:35 +000012956 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012957 }
12958
Alp Toker314cc812014-01-25 16:55:45 +000012959 QualType ResultType = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000012960 ExprValueKind VK = Expr::getValueKindForType(ResultType);
12961 ResultType = ResultType.getNonLValueExprType(Context);
12962
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012963 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012964 CXXMemberCallExpr *TheCall =
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012965 new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall7decc9e2010-11-18 06:31:45 +000012966 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012967
Anders Carlssonc4859ba2009-10-10 00:06:20 +000012968 // Check for a valid return type.
Alp Toker314cc812014-01-25 16:55:45 +000012969 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +000012970 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +000012971 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012972
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012973 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +000012974 // We only need to do this if there was actually an overload; otherwise
12975 // it was done at lookup.
John Wiegley01296292011-04-08 18:41:53 +000012976 if (!Method->isStatic()) {
12977 ExprResult ObjectArg =
12978 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
12979 FoundDecl, Method);
12980 if (ObjectArg.isInvalid())
12981 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012982 MemExpr->setBase(ObjectArg.get());
John Wiegley01296292011-04-08 18:41:53 +000012983 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012984
12985 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +000012986 const FunctionProtoType *Proto =
12987 Method->getType()->getAs<FunctionProtoType>();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012988 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012989 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +000012990 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012991
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012992 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000012993
Richard Smith55ce3522012-06-25 20:30:08 +000012994 if (CheckFunctionCall(Method, TheCall, Proto))
John McCall2d74de92009-12-01 22:10:20 +000012995 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +000012996
George Burgess IVaea6ade2015-09-25 17:53:16 +000012997 // In the case the method to call was not selected by the overloading
12998 // resolution process, we still need to handle the enable_if attribute. Do
George Burgess IV0d546532016-11-10 21:47:12 +000012999 // that here, so it will not hide previous -- and more relevant -- errors.
George Burgess IVadd6ab52016-11-16 21:31:25 +000013000 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
George Burgess IVaea6ade2015-09-25 17:53:16 +000013001 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
George Burgess IVadd6ab52016-11-16 21:31:25 +000013002 Diag(MemE->getMemberLoc(),
George Burgess IVaea6ade2015-09-25 17:53:16 +000013003 diag::err_ovl_no_viable_member_function_in_call)
13004 << Method << Method->getSourceRange();
13005 Diag(Method->getLocation(),
George Burgess IV177399e2017-01-09 04:12:14 +000013006 diag::note_ovl_candidate_disabled_by_function_cond_attr)
George Burgess IVaea6ade2015-09-25 17:53:16 +000013007 << Attr->getCond()->getSourceRange() << Attr->getMessage();
13008 return ExprError();
13009 }
13010 }
13011
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000013012 if ((isa<CXXConstructorDecl>(CurContext) ||
13013 isa<CXXDestructorDecl>(CurContext)) &&
Anders Carlsson47061ee2011-05-06 14:25:31 +000013014 TheCall->getMethodDecl()->isPure()) {
13015 const CXXMethodDecl *MD = TheCall->getMethodDecl();
13016
Davide Italianoccb37382015-07-14 23:36:10 +000013017 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
13018 MemExpr->performsVirtualDispatch(getLangOpts())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013019 Diag(MemExpr->getBeginLoc(),
Anders Carlsson47061ee2011-05-06 14:25:31 +000013020 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013021 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
13022 << MD->getParent()->getDeclName();
Anders Carlsson47061ee2011-05-06 14:25:31 +000013023
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013024 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
Davide Italianoccb37382015-07-14 23:36:10 +000013025 if (getLangOpts().AppleKext)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013026 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
13027 << MD->getParent()->getDeclName() << MD->getDeclName();
Chandler Carruth59259262011-06-27 08:31:58 +000013028 }
Anders Carlsson47061ee2011-05-06 14:25:31 +000013029 }
Nico Weber5a9259c2016-01-15 21:45:31 +000013030
13031 if (CXXDestructorDecl *DD =
13032 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
13033 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
Justin Lebard35f7062016-07-12 23:23:01 +000013034 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013035 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
Nico Weber5a9259c2016-01-15 21:45:31 +000013036 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
13037 MemExpr->getMemberLoc());
13038 }
13039
John McCallb268a282010-08-23 23:25:46 +000013040 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000013041}
13042
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013043/// BuildCallToObjectOfClassType - Build a call to an object of class
13044/// type (C++ [over.call.object]), which can end up invoking an
13045/// overloaded function call operator (@c operator()) or performing a
13046/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +000013047ExprResult
John Wiegley01296292011-04-08 18:41:53 +000013048Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregorb0846b02008-12-06 00:22:45 +000013049 SourceLocation LParenLoc,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000013050 MultiExprArg Args,
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013051 SourceLocation RParenLoc) {
John McCall4124c492011-10-17 18:40:02 +000013052 if (checkPlaceholderForOverload(*this, Obj))
13053 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000013054 ExprResult Object = Obj;
John McCall4124c492011-10-17 18:40:02 +000013055
13056 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000013057 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000013058 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000013059
Nico Weberb58e51c2014-11-19 05:21:39 +000013060 assert(Object.get()->getType()->isRecordType() &&
13061 "Requires object type argument");
John Wiegley01296292011-04-08 18:41:53 +000013062 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +000013063
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013064 // C++ [over.call.object]p1:
13065 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +000013066 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013067 // candidate functions includes at least the function call
13068 // operators of T. The function call operators of T are obtained by
13069 // ordinary lookup of the name operator() in the context of
13070 // (E).operator().
Richard Smith100b24a2014-04-17 01:52:14 +000013071 OverloadCandidateSet CandidateSet(LParenLoc,
13072 OverloadCandidateSet::CSK_Operator);
Douglas Gregor91f84212008-12-11 16:49:14 +000013073 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +000013074
John Wiegley01296292011-04-08 18:41:53 +000013075 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000013076 diag::err_incomplete_object_call, Object.get()))
Douglas Gregorc473cbb2009-11-15 07:48:03 +000013077 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013078
John McCall27b18f82009-11-17 02:14:36 +000013079 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
13080 LookupQualifiedName(R, Record->getDecl());
13081 R.suppressDiagnostics();
13082
Douglas Gregorc473cbb2009-11-15 07:48:03 +000013083 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +000013084 Oper != OperEnd; ++Oper) {
John Wiegley01296292011-04-08 18:41:53 +000013085 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
George Burgess IVce6284b2017-01-28 02:19:40 +000013086 Object.get()->Classify(Context), Args, CandidateSet,
13087 /*SuppressUserConversions=*/false);
Douglas Gregor358e7742009-11-07 17:23:56 +000013088 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013089
Douglas Gregorab7897a2008-11-19 22:57:39 +000013090 // C++ [over.call.object]p2:
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000013091 // In addition, for each (non-explicit in C++0x) conversion function
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000013092 // declared in T of the form
Douglas Gregorab7897a2008-11-19 22:57:39 +000013093 //
13094 // operator conversion-type-id () cv-qualifier;
13095 //
13096 // where cv-qualifier is the same cv-qualification as, or a
13097 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +000013098 // denotes the type "pointer to function of (P1,...,Pn) returning
13099 // R", or the type "reference to pointer to function of
13100 // (P1,...,Pn) returning R", or the type "reference to function
13101 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +000013102 // is also considered as a candidate function. Similarly,
13103 // surrogate call functions are added to the set of candidate
13104 // functions for each conversion function declared in an
13105 // accessible base class provided the function is not hidden
13106 // within T by another intervening declaration.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +000013107 const auto &Conversions =
13108 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
13109 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +000013110 NamedDecl *D = *I;
13111 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
13112 if (isa<UsingShadowDecl>(D))
13113 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013114
Douglas Gregor74ba25c2009-10-21 06:18:39 +000013115 // Skip over templated conversion functions; they aren't
13116 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +000013117 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +000013118 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +000013119
John McCall6e9f8f62009-12-03 04:06:58 +000013120 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000013121 if (!Conv->isExplicit()) {
13122 // Strip the reference type (if any) and then the pointer type (if
13123 // any) to get down to what might be a function type.
13124 QualType ConvType = Conv->getConversionType().getNonReferenceType();
13125 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
13126 ConvType = ConvPtrType->getPointeeType();
John McCalld14a8642009-11-21 08:51:07 +000013127
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000013128 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
13129 {
13130 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000013131 Object.get(), Args, CandidateSet);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000013132 }
13133 }
Douglas Gregorab7897a2008-11-19 22:57:39 +000013134 }
Mike Stump11289f42009-09-09 15:08:12 +000013135
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013136 bool HadMultipleCandidates = (CandidateSet.size() > 1);
13137
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013138 // Perform overload resolution.
13139 OverloadCandidateSet::iterator Best;
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013140 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
Richard Smith67ef14f2017-09-26 18:37:55 +000013141 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013142 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +000013143 // Overload resolution succeeded; we'll build the appropriate call
13144 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013145 break;
13146
13147 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +000013148 if (CandidateSet.empty())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013149 Diag(Object.get()->getBeginLoc(), diag::err_ovl_no_oper)
13150 << Object.get()->getType() << /*call*/ 1
13151 << Object.get()->getSourceRange();
John McCall02374852010-01-07 02:04:15 +000013152 else
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013153 Diag(Object.get()->getBeginLoc(), diag::err_ovl_no_viable_object_call)
13154 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000013155 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013156 break;
13157
13158 case OR_Ambiguous:
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013159 Diag(Object.get()->getBeginLoc(), diag::err_ovl_ambiguous_object_call)
13160 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000013161 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013162 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000013163
13164 case OR_Deleted:
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013165 Diag(Object.get()->getBeginLoc(), diag::err_ovl_deleted_object_call)
13166 << Best->Function->isDeleted() << Object.get()->getType()
13167 << getDeletedOrUnavailableSuffix(Best->Function)
13168 << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000013169 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000013170 break;
Mike Stump11289f42009-09-09 15:08:12 +000013171 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013172
Douglas Gregorb412e172010-07-25 18:17:45 +000013173 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013174 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013175
John McCall4124c492011-10-17 18:40:02 +000013176 UnbridgedCasts.restore();
13177
Craig Topperc3ec1492014-05-26 06:22:03 +000013178 if (Best->Function == nullptr) {
Douglas Gregorab7897a2008-11-19 22:57:39 +000013179 // Since there is no function declaration, this is one of the
13180 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +000013181 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +000013182 = cast<CXXConversionDecl>(
13183 Best->Conversions[0].UserDefined.ConversionFunction);
13184
Craig Topperc3ec1492014-05-26 06:22:03 +000013185 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
13186 Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000013187 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
13188 return ExprError();
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000013189 assert(Conv == Best->FoundDecl.getDecl() &&
Faisal Valid6676412013-06-15 11:54:37 +000013190 "Found Decl & conversion-to-functionptr should be same, right?!");
Douglas Gregorab7897a2008-11-19 22:57:39 +000013191 // We selected one of the surrogate functions that converts the
13192 // object parameter to a function pointer. Perform the conversion
13193 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013194
Fariborz Jahanian774cf792009-09-28 18:35:46 +000013195 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +000013196 // and then call it.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013197 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
13198 Conv, HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +000013199 if (Call.isInvalid())
13200 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +000013201 // Record usage of conversion in an implicit cast.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000013202 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
13203 CK_UserDefinedConversion, Call.get(),
13204 nullptr, VK_RValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013205
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000013206 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +000013207 }
13208
Craig Topperc3ec1492014-05-26 06:22:03 +000013209 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
John McCall49ec2e62010-01-28 01:54:34 +000013210
Douglas Gregorab7897a2008-11-19 22:57:39 +000013211 // We found an overloaded operator(). Build a CXXOperatorCallExpr
13212 // that calls this method, using Object for the implicit object
13213 // parameter and passing along the remaining arguments.
13214 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Nico Weber1fefe412012-11-09 06:06:14 +000013215
13216 // An error diagnostic has already been printed when parsing the declaration.
Nico Weber9512d3f2012-11-09 08:38:04 +000013217 if (Method->isInvalidDecl())
Nico Weber1fefe412012-11-09 06:06:14 +000013218 return ExprError();
13219
Chandler Carruth8e543b32010-12-12 08:17:55 +000013220 const FunctionProtoType *Proto =
13221 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013222
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000013223 unsigned NumParams = Proto->getNumParams();
Mike Stump11289f42009-09-09 15:08:12 +000013224
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000013225 DeclarationNameInfo OpLocInfo(
13226 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
13227 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Nick Lewycky134af912013-02-07 05:08:22 +000013228 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Akira Hatanaka22461672017-07-13 06:08:27 +000013229 Obj, HadMultipleCandidates,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000013230 OpLocInfo.getLoc(),
13231 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000013232 if (NewFn.isInvalid())
13233 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013234
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000013235 // Build the full argument list for the method call (the implicit object
13236 // parameter is placed at the beginning of the list).
George Burgess IV215f6e72016-12-13 19:22:56 +000013237 SmallVector<Expr *, 8> MethodArgs(Args.size() + 1);
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000013238 MethodArgs[0] = Object.get();
George Burgess IV215f6e72016-12-13 19:22:56 +000013239 std::copy(Args.begin(), Args.end(), MethodArgs.begin() + 1);
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000013240
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013241 // Once we've built TheCall, all of the expressions are properly
13242 // owned.
Alp Toker314cc812014-01-25 16:55:45 +000013243 QualType ResultTy = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000013244 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13245 ResultTy = ResultTy.getNonLValueExprType(Context);
13246
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000013247 CXXOperatorCallExpr *TheCall = new (Context)
George Burgess IV215f6e72016-12-13 19:22:56 +000013248 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(), MethodArgs, ResultTy,
Adam Nemet484aa452017-03-27 19:17:25 +000013249 VK, RParenLoc, FPOptions());
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013250
Alp Toker314cc812014-01-25 16:55:45 +000013251 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
Anders Carlsson3d5829c2009-10-13 21:49:31 +000013252 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013253
Douglas Gregor02a0acd2009-01-13 05:10:00 +000013254 // We may have default arguments. If so, we need to allocate more
13255 // slots in the call for them.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000013256 if (Args.size() < NumParams)
13257 TheCall->setNumArgs(Context, NumParams + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +000013258
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000013259 bool IsError = false;
13260
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013261 // Initialize the implicit object parameter.
John Wiegley01296292011-04-08 18:41:53 +000013262 ExprResult ObjRes =
Craig Topperc3ec1492014-05-26 06:22:03 +000013263 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000013264 Best->FoundDecl, Method);
13265 if (ObjRes.isInvalid())
13266 IsError = true;
13267 else
Benjamin Kramer62b95d82012-08-23 21:35:17 +000013268 Object = ObjRes;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013269 TheCall->setArg(0, Object.get());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000013270
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013271 // Check the argument types.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000013272 for (unsigned i = 0; i != NumParams; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013273 Expr *Arg;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000013274 if (i < Args.size()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013275 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +000013276
Douglas Gregor02a0acd2009-01-13 05:10:00 +000013277 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +000013278
John McCalldadc5752010-08-24 06:29:42 +000013279 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +000013280 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000013281 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +000013282 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +000013283 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013284
Anders Carlsson7c5fe482010-01-29 18:43:53 +000013285 IsError |= InputInit.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013286 Arg = InputInit.getAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000013287 } else {
John McCalldadc5752010-08-24 06:29:42 +000013288 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +000013289 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
13290 if (DefArg.isInvalid()) {
13291 IsError = true;
13292 break;
13293 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013294
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013295 Arg = DefArg.getAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000013296 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013297
13298 TheCall->setArg(i + 1, Arg);
13299 }
13300
13301 // If this is a variadic call, handle args passed through "...".
13302 if (Proto->isVariadic()) {
13303 // Promote the arguments (C99 6.5.2.2p7).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000013304 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
Craig Topperc3ec1492014-05-26 06:22:03 +000013305 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
13306 nullptr);
John Wiegley01296292011-04-08 18:41:53 +000013307 IsError |= Arg.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013308 TheCall->setArg(i + 1, Arg.get());
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013309 }
13310 }
13311
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000013312 if (IsError) return true;
13313
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000013314 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000013315
Richard Smith55ce3522012-06-25 20:30:08 +000013316 if (CheckFunctionCall(Method, TheCall, Proto))
Anders Carlssonbc4c1072009-08-16 01:56:34 +000013317 return true;
13318
John McCalle172be52010-08-24 06:09:16 +000013319 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013320}
13321
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013322/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +000013323/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013324/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +000013325ExprResult
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000013326Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
13327 bool *NoArrowOperatorFound) {
Chandler Carruth8e543b32010-12-12 08:17:55 +000013328 assert(Base->getType()->isRecordType() &&
13329 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +000013330
John McCall4124c492011-10-17 18:40:02 +000013331 if (checkPlaceholderForOverload(*this, Base))
13332 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000013333
John McCallbc077cf2010-02-08 23:07:23 +000013334 SourceLocation Loc = Base->getExprLoc();
13335
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013336 // C++ [over.ref]p1:
13337 //
13338 // [...] An expression x->m is interpreted as (x.operator->())->m
13339 // for a class object x of type T if T::operator->() exists and if
13340 // the operator is selected as the best match function by the
13341 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +000013342 DeclarationName OpName =
13343 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
Richard Smith100b24a2014-04-17 01:52:14 +000013344 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
Ted Kremenekc23c7e62009-07-29 21:53:49 +000013345 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +000013346
John McCallbc077cf2010-02-08 23:07:23 +000013347 if (RequireCompleteType(Loc, Base->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000013348 diag::err_typecheck_incomplete_tag, Base))
Eli Friedman132e70b2009-11-18 01:28:03 +000013349 return ExprError();
13350
John McCall27b18f82009-11-17 02:14:36 +000013351 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
13352 LookupQualifiedName(R, BaseRecord->getDecl());
13353 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +000013354
13355 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +000013356 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +000013357 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
George Burgess IVce6284b2017-01-28 02:19:40 +000013358 None, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +000013359 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013360
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013361 bool HadMultipleCandidates = (CandidateSet.size() > 1);
13362
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013363 // Perform overload resolution.
13364 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000013365 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013366 case OR_Success:
13367 // Overload resolution succeeded; we'll build the call below.
13368 break;
13369
13370 case OR_No_Viable_Function:
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000013371 if (CandidateSet.empty()) {
13372 QualType BaseType = Base->getType();
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000013373 if (NoArrowOperatorFound) {
13374 // Report this specific error to the caller instead of emitting a
13375 // diagnostic, as requested.
13376 *NoArrowOperatorFound = true;
13377 return ExprError();
13378 }
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000013379 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
13380 << BaseType << Base->getSourceRange();
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000013381 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000013382 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000013383 << FixItHint::CreateReplacement(OpLoc, ".");
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000013384 }
13385 } else
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013386 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +000013387 << "operator->" << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000013388 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000013389 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013390
13391 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000013392 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
13393 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000013394 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000013395 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000013396
13397 case OR_Deleted:
13398 Diag(OpLoc, diag::err_ovl_deleted_oper)
13399 << Best->Function->isDeleted()
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000013400 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000013401 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000013402 << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000013403 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000013404 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013405 }
13406
Craig Topperc3ec1492014-05-26 06:22:03 +000013407 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
John McCalla0296f72010-03-19 07:35:19 +000013408
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013409 // Convert the object parameter.
13410 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000013411 ExprResult BaseResult =
Craig Topperc3ec1492014-05-26 06:22:03 +000013412 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000013413 Best->FoundDecl, Method);
13414 if (BaseResult.isInvalid())
Douglas Gregord8061562009-08-06 03:17:00 +000013415 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013416 Base = BaseResult.get();
Douglas Gregor9ecea262008-11-21 03:04:22 +000013417
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013418 // Build the operator call.
Nick Lewycky134af912013-02-07 05:08:22 +000013419 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Akira Hatanaka22461672017-07-13 06:08:27 +000013420 Base, HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000013421 if (FnExpr.isInvalid())
13422 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013423
Alp Toker314cc812014-01-25 16:55:45 +000013424 QualType ResultTy = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000013425 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13426 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +000013427 CXXOperatorCallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013428 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
Adam Nemet484aa452017-03-27 19:17:25 +000013429 Base, ResultTy, VK, OpLoc, FPOptions());
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000013430
Alp Toker314cc812014-01-25 16:55:45 +000013431 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
George Burgess IVce6284b2017-01-28 02:19:40 +000013432 return ExprError();
13433
13434 if (CheckFunctionCall(Method, TheCall,
13435 Method->getType()->castAs<FunctionProtoType>()))
13436 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +000013437
13438 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013439}
13440
Richard Smithbcc22fc2012-03-09 08:00:36 +000013441/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
13442/// a literal operator described by the provided lookup results.
13443ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
13444 DeclarationNameInfo &SuffixInfo,
13445 ArrayRef<Expr*> Args,
13446 SourceLocation LitEndLoc,
13447 TemplateArgumentListInfo *TemplateArgs) {
13448 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smithc67fdd42012-03-07 08:35:16 +000013449
Richard Smith100b24a2014-04-17 01:52:14 +000013450 OverloadCandidateSet CandidateSet(UDSuffixLoc,
13451 OverloadCandidateSet::CSK_Normal);
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000013452 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
13453 /*SuppressUserConversions=*/true);
Richard Smithc67fdd42012-03-07 08:35:16 +000013454
Richard Smithbcc22fc2012-03-09 08:00:36 +000013455 bool HadMultipleCandidates = (CandidateSet.size() > 1);
13456
Richard Smithbcc22fc2012-03-09 08:00:36 +000013457 // Perform overload resolution. This will usually be trivial, but might need
13458 // to perform substitutions for a literal operator template.
13459 OverloadCandidateSet::iterator Best;
13460 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
13461 case OR_Success:
13462 case OR_Deleted:
13463 break;
13464
13465 case OR_No_Viable_Function:
13466 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
13467 << R.getLookupName();
13468 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13469 return ExprError();
13470
13471 case OR_Ambiguous:
13472 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
13473 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
13474 return ExprError();
Richard Smithc67fdd42012-03-07 08:35:16 +000013475 }
13476
Richard Smithbcc22fc2012-03-09 08:00:36 +000013477 FunctionDecl *FD = Best->Function;
Nick Lewycky134af912013-02-07 05:08:22 +000013478 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
Akira Hatanaka22461672017-07-13 06:08:27 +000013479 nullptr, HadMultipleCandidates,
Richard Smithbcc22fc2012-03-09 08:00:36 +000013480 SuffixInfo.getLoc(),
13481 SuffixInfo.getInfo());
13482 if (Fn.isInvalid())
13483 return true;
Richard Smithc67fdd42012-03-07 08:35:16 +000013484
13485 // Check the argument types. This should almost always be a no-op, except
13486 // that array-to-pointer decay is applied to string literals.
Richard Smithc67fdd42012-03-07 08:35:16 +000013487 Expr *ConvArgs[2];
Richard Smithe54c3072013-05-05 15:51:06 +000013488 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Richard Smithc67fdd42012-03-07 08:35:16 +000013489 ExprResult InputInit = PerformCopyInitialization(
13490 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
13491 SourceLocation(), Args[ArgIdx]);
13492 if (InputInit.isInvalid())
13493 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013494 ConvArgs[ArgIdx] = InputInit.get();
Richard Smithc67fdd42012-03-07 08:35:16 +000013495 }
13496
Alp Toker314cc812014-01-25 16:55:45 +000013497 QualType ResultTy = FD->getReturnType();
Richard Smithc67fdd42012-03-07 08:35:16 +000013498 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13499 ResultTy = ResultTy.getNonLValueExprType(Context);
13500
Richard Smithc67fdd42012-03-07 08:35:16 +000013501 UserDefinedLiteral *UDL =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013502 new (Context) UserDefinedLiteral(Context, Fn.get(),
Benjamin Kramerc215e762012-08-24 11:54:20 +000013503 llvm::makeArrayRef(ConvArgs, Args.size()),
Richard Smithc67fdd42012-03-07 08:35:16 +000013504 ResultTy, VK, LitEndLoc, UDSuffixLoc);
13505
Alp Toker314cc812014-01-25 16:55:45 +000013506 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
Richard Smithc67fdd42012-03-07 08:35:16 +000013507 return ExprError();
13508
Craig Topperc3ec1492014-05-26 06:22:03 +000013509 if (CheckFunctionCall(FD, UDL, nullptr))
Richard Smithc67fdd42012-03-07 08:35:16 +000013510 return ExprError();
13511
13512 return MaybeBindToTemporary(UDL);
13513}
13514
Sam Panzer0f384432012-08-21 00:52:01 +000013515/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
13516/// given LookupResult is non-empty, it is assumed to describe a member which
13517/// will be invoked. Otherwise, the function will be found via argument
13518/// dependent lookup.
13519/// CallExpr is set to a valid expression and FRS_Success returned on success,
13520/// otherwise CallExpr is set to ExprError() and some non-success value
13521/// is returned.
13522Sema::ForRangeStatus
Richard Smith9f690bd2015-10-27 06:02:45 +000013523Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
13524 SourceLocation RangeLoc,
Sam Panzer0f384432012-08-21 00:52:01 +000013525 const DeclarationNameInfo &NameInfo,
13526 LookupResult &MemberLookup,
13527 OverloadCandidateSet *CandidateSet,
13528 Expr *Range, ExprResult *CallExpr) {
Richard Smith9f690bd2015-10-27 06:02:45 +000013529 Scope *S = nullptr;
13530
Richard Smith67ef14f2017-09-26 18:37:55 +000013531 CandidateSet->clear(OverloadCandidateSet::CSK_Normal);
Sam Panzer0f384432012-08-21 00:52:01 +000013532 if (!MemberLookup.empty()) {
13533 ExprResult MemberRef =
13534 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
13535 /*IsPtr=*/false, CXXScopeSpec(),
13536 /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +000013537 /*FirstQualifierInScope=*/nullptr,
Sam Panzer0f384432012-08-21 00:52:01 +000013538 MemberLookup,
Aaron Ballman6924dcd2015-09-01 14:49:24 +000013539 /*TemplateArgs=*/nullptr, S);
Sam Panzer0f384432012-08-21 00:52:01 +000013540 if (MemberRef.isInvalid()) {
13541 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000013542 return FRS_DiagnosticIssued;
13543 }
Craig Topperc3ec1492014-05-26 06:22:03 +000013544 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
Sam Panzer0f384432012-08-21 00:52:01 +000013545 if (CallExpr->isInvalid()) {
13546 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000013547 return FRS_DiagnosticIssued;
13548 }
13549 } else {
13550 UnresolvedSet<0> FoundNames;
Sam Panzer0f384432012-08-21 00:52:01 +000013551 UnresolvedLookupExpr *Fn =
Craig Topperc3ec1492014-05-26 06:22:03 +000013552 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
Sam Panzer0f384432012-08-21 00:52:01 +000013553 NestedNameSpecifierLoc(), NameInfo,
13554 /*NeedsADL=*/true, /*Overloaded=*/false,
Richard Smithb6626742012-10-18 17:56:02 +000013555 FoundNames.begin(), FoundNames.end());
Sam Panzer0f384432012-08-21 00:52:01 +000013556
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000013557 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
Sam Panzer0f384432012-08-21 00:52:01 +000013558 CandidateSet, CallExpr);
13559 if (CandidateSet->empty() || CandidateSetError) {
13560 *CallExpr = ExprError();
13561 return FRS_NoViableFunction;
13562 }
13563 OverloadCandidateSet::iterator Best;
13564 OverloadingResult OverloadResult =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013565 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
Sam Panzer0f384432012-08-21 00:52:01 +000013566
13567 if (OverloadResult == OR_No_Viable_Function) {
13568 *CallExpr = ExprError();
13569 return FRS_NoViableFunction;
13570 }
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000013571 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
Craig Topperc3ec1492014-05-26 06:22:03 +000013572 Loc, nullptr, CandidateSet, &Best,
Sam Panzer0f384432012-08-21 00:52:01 +000013573 OverloadResult,
13574 /*AllowTypoCorrection=*/false);
13575 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
13576 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000013577 return FRS_DiagnosticIssued;
13578 }
13579 }
13580 return FRS_Success;
13581}
13582
13583
Douglas Gregorcd695e52008-11-10 20:40:00 +000013584/// FixOverloadedFunctionReference - E is an expression that refers to
13585/// a C++ overloaded function (possibly with some parentheses and
13586/// perhaps a '&' around it). We have resolved the overloaded function
13587/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +000013588/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +000013589Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +000013590 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +000013591 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000013592 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
13593 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000013594 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000013595 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013596
Douglas Gregor51c538b2009-11-20 19:42:02 +000013597 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013598 }
13599
Douglas Gregor51c538b2009-11-20 19:42:02 +000013600 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000013601 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
13602 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013603 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +000013604 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +000013605 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +000013606 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +000013607 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000013608 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013609
13610 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +000013611 ICE->getCastKind(),
Craig Topperc3ec1492014-05-26 06:22:03 +000013612 SubExpr, nullptr,
John McCall2536c6d2010-08-25 10:28:54 +000013613 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013614 }
13615
Aaron Ballmanff7bd8b2016-09-02 13:45:40 +000013616 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
13617 if (!GSE->isResultDependent()) {
13618 Expr *SubExpr =
13619 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
13620 if (SubExpr == GSE->getResultExpr())
13621 return GSE;
13622
13623 // Replace the resulting type information before rebuilding the generic
13624 // selection expression.
Aaron Ballman8b871d92016-09-02 18:31:31 +000013625 ArrayRef<Expr *> A = GSE->getAssocExprs();
13626 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
Aaron Ballmanff7bd8b2016-09-02 13:45:40 +000013627 unsigned ResultIdx = GSE->getResultIndex();
13628 AssocExprs[ResultIdx] = SubExpr;
13629
13630 return new (Context) GenericSelectionExpr(
13631 Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
13632 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
13633 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
13634 ResultIdx);
13635 }
13636 // Rather than fall through to the unreachable, return the original generic
13637 // selection expression.
13638 return GSE;
13639 }
13640
Douglas Gregor51c538b2009-11-20 19:42:02 +000013641 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +000013642 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +000013643 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +000013644 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13645 if (Method->isStatic()) {
13646 // Do nothing: static member functions aren't any different
13647 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +000013648 } else {
Alp Toker028ed912013-12-06 17:56:43 +000013649 // Fix the subexpression, which really has to be an
John McCalle66edc12009-11-24 19:00:30 +000013650 // UnresolvedLookupExpr holding an overloaded member function
13651 // or template.
John McCall16df1e52010-03-30 21:47:33 +000013652 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13653 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +000013654 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000013655 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +000013656
John McCalld14a8642009-11-21 08:51:07 +000013657 assert(isa<DeclRefExpr>(SubExpr)
13658 && "fixed to something other than a decl ref");
13659 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
13660 && "fixed to a member ref with no nested name qualifier");
13661
13662 // We have taken the address of a pointer to member
13663 // function. Perform the computation here so that we get the
13664 // appropriate pointer to member type.
13665 QualType ClassType
13666 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
13667 QualType MemPtrType
13668 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
David Majnemer02d57cc2016-06-30 03:02:03 +000013669 // Under the MS ABI, lock down the inheritance model now.
13670 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13671 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
John McCalld14a8642009-11-21 08:51:07 +000013672
John McCall7decc9e2010-11-18 06:31:45 +000013673 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
13674 VK_RValue, OK_Ordinary,
Aaron Ballmana5038552018-01-09 13:07:03 +000013675 UnOp->getOperatorLoc(), false);
Douglas Gregor6f233ef2009-02-11 01:18:59 +000013676 }
13677 }
John McCall16df1e52010-03-30 21:47:33 +000013678 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13679 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000013680 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000013681 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013682
John McCalle3027922010-08-25 11:45:40 +000013683 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +000013684 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +000013685 VK_RValue, OK_Ordinary,
Aaron Ballmana5038552018-01-09 13:07:03 +000013686 UnOp->getOperatorLoc(), false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013687 }
John McCalld14a8642009-11-21 08:51:07 +000013688
Richard Smith84a0b6d2016-10-18 23:39:12 +000013689 // C++ [except.spec]p17:
13690 // An exception-specification is considered to be needed when:
13691 // - in an expression the function is the unique lookup result or the
13692 // selected member of a set of overloaded functions
13693 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13694 ResolveExceptionSpec(E->getExprLoc(), FPT);
13695
John McCalld14a8642009-11-21 08:51:07 +000013696 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +000013697 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000013698 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCalle66edc12009-11-24 19:00:30 +000013699 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +000013700 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
13701 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +000013702 }
13703
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013704 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13705 ULE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000013706 ULE->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013707 Fn,
John McCall113bee02012-03-10 09:33:50 +000013708 /*enclosing*/ false, // FIXME?
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013709 ULE->getNameLoc(),
13710 Fn->getType(),
13711 VK_LValue,
13712 Found.getDecl(),
13713 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000013714 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013715 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
13716 return DRE;
John McCalld14a8642009-11-21 08:51:07 +000013717 }
13718
John McCall10eae182009-11-30 22:42:35 +000013719 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +000013720 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000013721 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCall2d74de92009-12-01 22:10:20 +000013722 if (MemExpr->hasExplicitTemplateArgs()) {
13723 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
13724 TemplateArgs = &TemplateArgsBuffer;
13725 }
John McCall6b51f282009-11-23 01:53:49 +000013726
John McCall2d74de92009-12-01 22:10:20 +000013727 Expr *Base;
13728
John McCall7decc9e2010-11-18 06:31:45 +000013729 // If we're filling in a static method where we used to have an
13730 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +000013731 if (MemExpr->isImplicitAccess()) {
13732 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013733 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13734 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000013735 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013736 Fn,
John McCall113bee02012-03-10 09:33:50 +000013737 /*enclosing*/ false,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013738 MemExpr->getMemberLoc(),
13739 Fn->getType(),
13740 VK_LValue,
13741 Found.getDecl(),
13742 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000013743 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013744 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
13745 return DRE;
Douglas Gregorb15af892010-01-07 23:12:05 +000013746 } else {
13747 SourceLocation Loc = MemExpr->getMemberLoc();
13748 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +000013749 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman73a04092012-01-07 04:59:52 +000013750 CheckCXXThisCapture(Loc);
Douglas Gregorb15af892010-01-07 23:12:05 +000013751 Base = new (Context) CXXThisExpr(Loc,
13752 MemExpr->getBaseType(),
13753 /*isImplicit=*/true);
13754 }
John McCall2d74de92009-12-01 22:10:20 +000013755 } else
John McCallc3007a22010-10-26 07:05:15 +000013756 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +000013757
John McCall4adb38c2011-04-27 00:36:17 +000013758 ExprValueKind valueKind;
13759 QualType type;
13760 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13761 valueKind = VK_LValue;
13762 type = Fn->getType();
13763 } else {
13764 valueKind = VK_RValue;
Yunzhong Gaoeba323a2015-05-01 02:04:32 +000013765 type = Context.BoundMemberTy;
13766 }
13767
13768 MemberExpr *ME = MemberExpr::Create(
13769 Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
13770 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
13771 MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
13772 OK_Ordinary);
13773 ME->setHadMultipleCandidates(true);
13774 MarkMemberReferenced(ME);
13775 return ME;
Douglas Gregor51c538b2009-11-20 19:42:02 +000013776 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013777
John McCallc3007a22010-10-26 07:05:15 +000013778 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregorcd695e52008-11-10 20:40:00 +000013779}
13780
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013781ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +000013782 DeclAccessPair Found,
13783 FunctionDecl *Fn) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000013784 return FixOverloadedFunctionReference(E.get(), Found, Fn);
Douglas Gregor3e1e5272009-12-09 23:02:17 +000013785}