blob: 8f28ec2fb8ab39d84f57980325bde0b43a766da7 [file] [log] [blame]
Nick Lewyckye1121512013-01-24 01:12:16 +00001//===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides Sema routines for C++ overloading.
11//
12//===----------------------------------------------------------------------===//
13
Chandler Carruth3a022472012-12-04 09:13:33 +000014#include "clang/Sema/Overload.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000015#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000016#include "clang/AST/CXXInheritance.h"
John McCallde6836a2010-08-24 07:21:54 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000018#include "clang/AST/Expr.h"
Douglas Gregor91cea0a2008-11-19 21:05:33 +000019#include "clang/AST/ExprCXX.h"
John McCalle26a8722010-12-04 08:14:53 +000020#include "clang/AST/ExprObjC.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000021#include "clang/AST/TypeOrdering.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000022#include "clang/Basic/Diagnostic.h"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000023#include "clang/Basic/DiagnosticOptions.h"
Anders Carlssond624e162009-08-26 23:45:07 +000024#include "clang/Basic/PartialDiagnostic.h"
David Majnemerc729b0b2013-09-16 22:44:20 +000025#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000026#include "clang/Sema/Initialization.h"
27#include "clang/Sema/Lookup.h"
28#include "clang/Sema/SemaInternal.h"
29#include "clang/Sema/Template.h"
30#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor2bbc0262010-09-12 04:28:07 +000031#include "llvm/ADT/DenseSet.h"
George Burgess IV177399e2017-01-09 04:12:14 +000032#include "llvm/ADT/Optional.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000033#include "llvm/ADT/STLExtras.h"
Douglas Gregor58e008d2008-11-13 20:12:29 +000034#include "llvm/ADT/SmallPtrSet.h"
Richard Smith9ca64612012-05-07 09:03:25 +000035#include "llvm/ADT/SmallString.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000036#include <algorithm>
David Blaikie8ad22e62014-05-01 23:01:41 +000037#include <cstdlib>
Douglas Gregor5251f1b2008-10-21 16:13:35 +000038
Richard Smith17c00b42014-11-12 01:24:00 +000039using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000040using namespace sema;
Douglas Gregor5251f1b2008-10-21 16:13:35 +000041
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000042static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) {
George Burgess IV21081362016-07-24 23:12:40 +000043 return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
44 return P->hasAttr<PassObjectSizeAttr>();
45 });
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000046}
47
Nick Lewycky134af912013-02-07 05:08:22 +000048/// A convenience routine for creating a decayed reference to a function.
John Wiegley01296292011-04-08 18:41:53 +000049static ExprResult
Nick Lewycky134af912013-02-07 05:08:22 +000050CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
Akira Hatanaka22461672017-07-13 06:08:27 +000051 const Expr *Base, bool HadMultipleCandidates,
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000052 SourceLocation Loc = SourceLocation(),
Douglas Gregore9d62932011-07-15 16:25:15 +000053 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
Richard Smith22262ab2013-05-04 06:44:46 +000054 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000055 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000056 // If FoundDecl is different from Fn (such as if one is a template
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000057 // and the other a specialization), make sure DiagnoseUseOfDecl is
Faisal Valid6676412013-06-15 11:54:37 +000058 // called on both.
59 // FIXME: This would be more comprehensively addressed by modifying
60 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
61 // being used.
62 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
Richard Smith22262ab2013-05-04 06:44:46 +000063 return ExprError();
Richard Smith5f4b3882016-10-19 00:14:23 +000064 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
65 S.ResolveExceptionSpec(Loc, FPT);
John McCall113bee02012-03-10 09:33:50 +000066 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000067 VK_LValue, Loc, LocInfo);
68 if (HadMultipleCandidates)
69 DRE->setHadMultipleCandidates(true);
Nick Lewycky134af912013-02-07 05:08:22 +000070
Akira Hatanaka22461672017-07-13 06:08:27 +000071 S.MarkDeclRefReferenced(DRE, Base);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000072 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
73 CK_FunctionToPointerDecay);
John McCall7decc9e2010-11-18 06:31:45 +000074}
75
John McCall5c32be02010-08-24 20:38:10 +000076static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
77 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +000078 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +000079 bool CStyle,
80 bool AllowObjCWritebackConversion);
Sam Panzer04390a62012-08-16 02:38:47 +000081
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000082static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +000083 QualType &ToType,
84 bool InOverloadResolution,
85 StandardConversionSequence &SCS,
86 bool CStyle);
John McCall5c32be02010-08-24 20:38:10 +000087static OverloadingResult
88IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
89 UserDefinedConversionSequence& User,
90 OverloadCandidateSet& Conversions,
Douglas Gregor4b60a152013-11-07 22:34:54 +000091 bool AllowExplicit,
92 bool AllowObjCConversionOnExplicit);
John McCall5c32be02010-08-24 20:38:10 +000093
94
95static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +000096CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +000097 const StandardConversionSequence& SCS1,
98 const StandardConversionSequence& SCS2);
99
100static ImplicitConversionSequence::CompareKind
101CompareQualificationConversions(Sema &S,
102 const StandardConversionSequence& SCS1,
103 const StandardConversionSequence& SCS2);
104
105static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +0000106CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +0000107 const StandardConversionSequence& SCS1,
108 const StandardConversionSequence& SCS2);
109
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000110/// GetConversionRank - Retrieve the implicit conversion rank
111/// corresponding to the given implicit conversion kind.
Richard Smith17c00b42014-11-12 01:24:00 +0000112ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000113 static const ImplicitConversionRank
114 Rank[(int)ICK_Num_Conversion_Kinds] = {
115 ICR_Exact_Match,
116 ICR_Exact_Match,
117 ICR_Exact_Match,
118 ICR_Exact_Match,
119 ICR_Exact_Match,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000120 ICR_Exact_Match,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000121 ICR_Promotion,
122 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000123 ICR_Promotion,
124 ICR_Conversion,
125 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000126 ICR_Conversion,
127 ICR_Conversion,
128 ICR_Conversion,
129 ICR_Conversion,
130 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000131 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000132 ICR_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000133 ICR_Conversion,
Egor Churaevc217f372017-03-21 12:55:55 +0000134 ICR_OCL_Scalar_Widening,
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000135 ICR_Complex_Real_Conversion,
136 ICR_Conversion,
John McCall31168b02011-06-15 23:02:42 +0000137 ICR_Conversion,
George Burgess IV45461812015-10-11 20:13:20 +0000138 ICR_Writeback_Conversion,
139 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
140 // it was omitted by the patch that added
141 // ICK_Zero_Event_Conversion
George Burgess IV2099b542016-09-02 22:59:57 +0000142 ICR_C_Conversion,
143 ICR_C_Conversion_Extension
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000144 };
145 return Rank[(int)Kind];
146}
147
148/// GetImplicitConversionName - Return the name of this kind of
149/// implicit conversion.
Richard Smith17c00b42014-11-12 01:24:00 +0000150static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopescfca1f02009-12-23 17:49:57 +0000151 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000152 "No conversion",
153 "Lvalue-to-rvalue",
154 "Array-to-pointer",
155 "Function-to-pointer",
Richard Smith3c4f8d22016-10-16 17:54:23 +0000156 "Function pointer conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000157 "Qualification",
158 "Integral promotion",
159 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000160 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000161 "Integral conversion",
162 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000163 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000164 "Floating-integral conversion",
165 "Pointer conversion",
166 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000167 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000168 "Compatible-types conversion",
Douglas Gregor46188682010-05-18 22:42:18 +0000169 "Derived-to-base conversion",
170 "Vector conversion",
171 "Vector splat",
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000172 "Complex-real conversion",
173 "Block Pointer conversion",
Sylvestre Ledru55635ce2014-11-17 19:41:49 +0000174 "Transparent Union Conversion",
George Burgess IV45461812015-10-11 20:13:20 +0000175 "Writeback conversion",
176 "OpenCL Zero Event Conversion",
George Burgess IV2099b542016-09-02 22:59:57 +0000177 "C specific type conversion",
178 "Incompatible pointer conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000179 };
180 return Name[Kind];
181}
182
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000183/// StandardConversionSequence - Set the standard conversion
184/// sequence to the identity conversion.
185void StandardConversionSequence::setAsIdentityConversion() {
186 First = ICK_Identity;
187 Second = ICK_Identity;
188 Third = ICK_Identity;
Douglas Gregore489a7d2010-02-28 18:30:25 +0000189 DeprecatedStringLiteralToCharPtr = false;
John McCall31168b02011-06-15 23:02:42 +0000190 QualificationIncludesObjCLifetime = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000191 ReferenceBinding = false;
192 DirectBinding = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +0000193 IsLvalueReference = true;
194 BindsToFunctionLvalue = false;
195 BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +0000196 BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +0000197 ObjCLifetimeConversionBinding = false;
Craig Topperc3ec1492014-05-26 06:22:03 +0000198 CopyConstructor = nullptr;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000199}
200
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000201/// getRank - Retrieve the rank of this standard conversion sequence
202/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
203/// implicit conversions.
204ImplicitConversionRank StandardConversionSequence::getRank() const {
205 ImplicitConversionRank Rank = ICR_Exact_Match;
206 if (GetConversionRank(First) > Rank)
207 Rank = GetConversionRank(First);
208 if (GetConversionRank(Second) > Rank)
209 Rank = GetConversionRank(Second);
210 if (GetConversionRank(Third) > Rank)
211 Rank = GetConversionRank(Third);
212 return Rank;
213}
214
215/// isPointerConversionToBool - Determines whether this conversion is
216/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump11289f42009-09-09 15:08:12 +0000217/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000218/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000219bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000220 // Note that FromType has not necessarily been transformed by the
221 // array-to-pointer or function-to-pointer implicit conversions, so
222 // check for their presence as well as checking whether FromType is
223 // a pointer.
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000224 if (getToType(1)->isBooleanType() &&
John McCall6d1116a2010-06-11 10:04:22 +0000225 (getFromType()->isPointerType() ||
226 getFromType()->isObjCObjectPointerType() ||
227 getFromType()->isBlockPointerType() ||
Anders Carlsson7da7cc52010-11-05 00:12:09 +0000228 getFromType()->isNullPtrType() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000229 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
230 return true;
231
232 return false;
233}
234
Douglas Gregor5c407d92008-10-23 00:40:37 +0000235/// isPointerConversionToVoidPointer - Determines whether this
236/// conversion is a conversion of a pointer to a void pointer. This is
237/// used as part of the ranking of standard conversion sequences (C++
238/// 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000239bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000240StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000241isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall0d1da222010-01-12 00:44:57 +0000242 QualType FromType = getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000243 QualType ToType = getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +0000244
245 // Note that FromType has not necessarily been transformed by the
246 // array-to-pointer implicit conversion, so check for its presence
247 // and redo the conversion to get a pointer.
248 if (First == ICK_Array_To_Pointer)
249 FromType = Context.getArrayDecayedType(FromType);
250
Douglas Gregor5d3d3fa2011-04-15 20:45:44 +0000251 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000252 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000253 return ToPtrType->getPointeeType()->isVoidType();
254
255 return false;
256}
257
Richard Smith66e05fe2012-01-18 05:21:49 +0000258/// Skip any implicit casts which could be either part of a narrowing conversion
259/// or after one in an implicit conversion.
260static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
261 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
262 switch (ICE->getCastKind()) {
263 case CK_NoOp:
264 case CK_IntegralCast:
265 case CK_IntegralToBoolean:
266 case CK_IntegralToFloating:
George Burgess IVdf1ed002016-01-13 01:52:39 +0000267 case CK_BooleanToSignedIntegral:
Richard Smith66e05fe2012-01-18 05:21:49 +0000268 case CK_FloatingToIntegral:
269 case CK_FloatingToBoolean:
270 case CK_FloatingCast:
271 Converted = ICE->getSubExpr();
272 continue;
273
274 default:
275 return Converted;
276 }
277 }
278
279 return Converted;
280}
281
282/// Check if this standard conversion sequence represents a narrowing
283/// conversion, according to C++11 [dcl.init.list]p7.
284///
285/// \param Ctx The AST context.
286/// \param Converted The result of applying this standard conversion sequence.
287/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
288/// value of the expression prior to the narrowing conversion.
Richard Smith5614ca72012-03-23 23:55:39 +0000289/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
290/// type of the expression prior to the narrowing conversion.
Richard Smith66e05fe2012-01-18 05:21:49 +0000291NarrowingKind
Richard Smithf8379a02012-01-18 23:55:52 +0000292StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
293 const Expr *Converted,
Richard Smith5614ca72012-03-23 23:55:39 +0000294 APValue &ConstantValue,
295 QualType &ConstantType) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000296 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
Richard Smith66e05fe2012-01-18 05:21:49 +0000297
298 // C++11 [dcl.init.list]p7:
299 // A narrowing conversion is an implicit conversion ...
300 QualType FromType = getToType(0);
301 QualType ToType = getToType(1);
Richard Smithed638862016-03-28 06:08:37 +0000302
303 // A conversion to an enumeration type is narrowing if the conversion to
304 // the underlying type is narrowing. This only arises for expressions of
305 // the form 'Enum{init}'.
306 if (auto *ET = ToType->getAs<EnumType>())
307 ToType = ET->getDecl()->getIntegerType();
308
Richard Smith66e05fe2012-01-18 05:21:49 +0000309 switch (Second) {
Richard Smith64ecacf2015-02-19 00:39:05 +0000310 // 'bool' is an integral type; dispatch to the right place to handle it.
311 case ICK_Boolean_Conversion:
312 if (FromType->isRealFloatingType())
313 goto FloatingIntegralConversion;
314 if (FromType->isIntegralOrUnscopedEnumerationType())
315 goto IntegralConversion;
316 // Boolean conversions can be from pointers and pointers to members
317 // [conv.bool], and those aren't considered narrowing conversions.
318 return NK_Not_Narrowing;
319
Richard Smith66e05fe2012-01-18 05:21:49 +0000320 // -- from a floating-point type to an integer type, or
321 //
322 // -- from an integer type or unscoped enumeration type to a floating-point
323 // type, except where the source is a constant expression and the actual
324 // value after conversion will fit into the target type and will produce
325 // the original value when converted back to the original type, or
326 case ICK_Floating_Integral:
Richard Smith64ecacf2015-02-19 00:39:05 +0000327 FloatingIntegralConversion:
Richard Smith66e05fe2012-01-18 05:21:49 +0000328 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
329 return NK_Type_Narrowing;
330 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
331 llvm::APSInt IntConstantValue;
332 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
Simon Pilgrimf9409872017-06-01 18:13:02 +0000333 assert(Initializer && "Unknown conversion expression");
Richard Smith52e624f2016-12-21 21:42:57 +0000334
335 // If it's value-dependent, we can't tell whether it's narrowing.
336 if (Initializer->isValueDependent())
337 return NK_Dependent_Narrowing;
338
Simon Pilgrimf9409872017-06-01 18:13:02 +0000339 if (Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
Richard Smith66e05fe2012-01-18 05:21:49 +0000340 // Convert the integer to the floating type.
341 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
342 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
343 llvm::APFloat::rmNearestTiesToEven);
344 // And back.
345 llvm::APSInt ConvertedValue = IntConstantValue;
346 bool ignored;
347 Result.convertToInteger(ConvertedValue,
348 llvm::APFloat::rmTowardZero, &ignored);
349 // If the resulting value is different, this was a narrowing conversion.
350 if (IntConstantValue != ConvertedValue) {
351 ConstantValue = APValue(IntConstantValue);
Richard Smith5614ca72012-03-23 23:55:39 +0000352 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000353 return NK_Constant_Narrowing;
354 }
355 } else {
356 // Variables are always narrowings.
357 return NK_Variable_Narrowing;
358 }
359 }
360 return NK_Not_Narrowing;
361
362 // -- from long double to double or float, or from double to float, except
363 // where the source is a constant expression and the actual value after
364 // conversion is within the range of values that can be represented (even
365 // if it cannot be represented exactly), or
366 case ICK_Floating_Conversion:
367 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
368 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
369 // FromType is larger than ToType.
370 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
Richard Smith52e624f2016-12-21 21:42:57 +0000371
372 // If it's value-dependent, we can't tell whether it's narrowing.
373 if (Initializer->isValueDependent())
374 return NK_Dependent_Narrowing;
375
Richard Smith66e05fe2012-01-18 05:21:49 +0000376 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
377 // Constant!
378 assert(ConstantValue.isFloat());
379 llvm::APFloat FloatVal = ConstantValue.getFloat();
380 // Convert the source value into the target type.
381 bool ignored;
382 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
383 Ctx.getFloatTypeSemantics(ToType),
384 llvm::APFloat::rmNearestTiesToEven, &ignored);
385 // If there was no overflow, the source value is within the range of
386 // values that can be represented.
Richard Smith5614ca72012-03-23 23:55:39 +0000387 if (ConvertStatus & llvm::APFloat::opOverflow) {
388 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000389 return NK_Constant_Narrowing;
Richard Smith5614ca72012-03-23 23:55:39 +0000390 }
Richard Smith66e05fe2012-01-18 05:21:49 +0000391 } else {
392 return NK_Variable_Narrowing;
393 }
394 }
395 return NK_Not_Narrowing;
396
397 // -- from an integer type or unscoped enumeration type to an integer type
398 // that cannot represent all the values of the original type, except where
399 // the source is a constant expression and the actual value after
400 // conversion will fit into the target type and will produce the original
401 // value when converted back to the original type.
Richard Smith64ecacf2015-02-19 00:39:05 +0000402 case ICK_Integral_Conversion:
403 IntegralConversion: {
Richard Smith66e05fe2012-01-18 05:21:49 +0000404 assert(FromType->isIntegralOrUnscopedEnumerationType());
405 assert(ToType->isIntegralOrUnscopedEnumerationType());
406 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
407 const unsigned FromWidth = Ctx.getIntWidth(FromType);
408 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
409 const unsigned ToWidth = Ctx.getIntWidth(ToType);
410
411 if (FromWidth > ToWidth ||
Richard Smith25a80d42012-06-13 01:07:41 +0000412 (FromWidth == ToWidth && FromSigned != ToSigned) ||
413 (FromSigned && !ToSigned)) {
Richard Smith66e05fe2012-01-18 05:21:49 +0000414 // Not all values of FromType can be represented in ToType.
415 llvm::APSInt InitializerValue;
416 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
Richard Smith52e624f2016-12-21 21:42:57 +0000417
418 // If it's value-dependent, we can't tell whether it's narrowing.
419 if (Initializer->isValueDependent())
420 return NK_Dependent_Narrowing;
421
Richard Smith25a80d42012-06-13 01:07:41 +0000422 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
423 // Such conversions on variables are always narrowing.
424 return NK_Variable_Narrowing;
Richard Smith72cd8ea2012-06-19 21:28:35 +0000425 }
426 bool Narrowing = false;
427 if (FromWidth < ToWidth) {
Richard Smith25a80d42012-06-13 01:07:41 +0000428 // Negative -> unsigned is narrowing. Otherwise, more bits is never
429 // narrowing.
430 if (InitializerValue.isSigned() && InitializerValue.isNegative())
Richard Smith72cd8ea2012-06-19 21:28:35 +0000431 Narrowing = true;
Richard Smith25a80d42012-06-13 01:07:41 +0000432 } else {
Richard Smith66e05fe2012-01-18 05:21:49 +0000433 // Add a bit to the InitializerValue so we don't have to worry about
434 // signed vs. unsigned comparisons.
435 InitializerValue = InitializerValue.extend(
436 InitializerValue.getBitWidth() + 1);
437 // Convert the initializer to and from the target width and signed-ness.
438 llvm::APSInt ConvertedValue = InitializerValue;
439 ConvertedValue = ConvertedValue.trunc(ToWidth);
440 ConvertedValue.setIsSigned(ToSigned);
441 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
442 ConvertedValue.setIsSigned(InitializerValue.isSigned());
443 // If the result is different, this was a narrowing conversion.
Richard Smith72cd8ea2012-06-19 21:28:35 +0000444 if (ConvertedValue != InitializerValue)
445 Narrowing = true;
446 }
447 if (Narrowing) {
448 ConstantType = Initializer->getType();
449 ConstantValue = APValue(InitializerValue);
450 return NK_Constant_Narrowing;
Richard Smith66e05fe2012-01-18 05:21:49 +0000451 }
452 }
453 return NK_Not_Narrowing;
454 }
455
456 default:
457 // Other kinds of conversions are not narrowings.
458 return NK_Not_Narrowing;
459 }
460}
461
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000462/// dump - Print this standard conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000463/// error. Useful for debugging overloading issues.
Yaron Kerencdae9412016-01-29 19:38:18 +0000464LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000465 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000466 bool PrintedSomething = false;
467 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000468 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000469 PrintedSomething = true;
470 }
471
472 if (Second != ICK_Identity) {
473 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000474 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000475 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000476 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000477
478 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000479 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000480 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000481 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000482 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000483 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000484 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000485 PrintedSomething = true;
486 }
487
488 if (Third != ICK_Identity) {
489 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000490 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000491 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000492 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000493 PrintedSomething = true;
494 }
495
496 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000497 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000498 }
499}
500
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000501/// dump - Print this user-defined conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000502/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000503void UserDefinedConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000504 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000505 if (Before.First || Before.Second || Before.Third) {
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000506 Before.dump();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000507 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000508 }
Sebastian Redl72ef7bc2011-11-01 15:53:09 +0000509 if (ConversionFunction)
510 OS << '\'' << *ConversionFunction << '\'';
511 else
512 OS << "aggregate initialization";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000513 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000514 OS << " -> ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000515 After.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000516 }
517}
518
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000519/// dump - Print this implicit conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000520/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000521void ImplicitConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000522 raw_ostream &OS = llvm::errs();
Richard Smitha93f1022013-09-06 22:30:28 +0000523 if (isStdInitializerListElement())
524 OS << "Worst std::initializer_list element conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000525 switch (ConversionKind) {
526 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000527 OS << "Standard conversion: ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000528 Standard.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000529 break;
530 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000531 OS << "User-defined conversion: ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000532 UserDefined.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000533 break;
534 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000535 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000536 break;
John McCall0d1da222010-01-12 00:44:57 +0000537 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000538 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000539 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000540 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000541 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000542 break;
543 }
544
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000545 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000546}
547
John McCall0d1da222010-01-12 00:44:57 +0000548void AmbiguousConversionSequence::construct() {
549 new (&conversions()) ConversionSet();
550}
551
552void AmbiguousConversionSequence::destruct() {
553 conversions().~ConversionSet();
554}
555
556void
557AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
558 FromTypePtr = O.FromTypePtr;
559 ToTypePtr = O.ToTypePtr;
560 new (&conversions()) ConversionSet(O.conversions());
561}
562
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000563namespace {
Larisse Voufo98b20f12013-07-19 23:00:19 +0000564 // Structure used by DeductionFailureInfo to store
Richard Smith44ecdbd2013-01-31 05:19:49 +0000565 // template argument information.
566 struct DFIArguments {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000567 TemplateArgument FirstArg;
568 TemplateArgument SecondArg;
569 };
Larisse Voufo98b20f12013-07-19 23:00:19 +0000570 // Structure used by DeductionFailureInfo to store
Richard Smith44ecdbd2013-01-31 05:19:49 +0000571 // template parameter and template argument information.
572 struct DFIParamWithArguments : DFIArguments {
573 TemplateParameter Param;
574 };
Richard Smith9b534542015-12-31 02:02:54 +0000575 // Structure used by DeductionFailureInfo to store template argument
576 // information and the index of the problematic call argument.
577 struct DFIDeducedMismatchArgs : DFIArguments {
578 TemplateArgumentList *TemplateArgs;
579 unsigned CallArgIndex;
580 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000581}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000582
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000583/// \brief Convert from Sema's representation of template deduction information
584/// to the form used in overload-candidate information.
Richard Smith17c00b42014-11-12 01:24:00 +0000585DeductionFailureInfo
586clang::MakeDeductionFailureInfo(ASTContext &Context,
587 Sema::TemplateDeductionResult TDK,
588 TemplateDeductionInfo &Info) {
Larisse Voufo98b20f12013-07-19 23:00:19 +0000589 DeductionFailureInfo Result;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000590 Result.Result = static_cast<unsigned>(TDK);
Richard Smith9ca64612012-05-07 09:03:25 +0000591 Result.HasDiagnostic = false;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000592 switch (TDK) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000593 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000594 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000595 case Sema::TDK_TooManyArguments:
596 case Sema::TDK_TooFewArguments:
Richard Smith9b534542015-12-31 02:02:54 +0000597 case Sema::TDK_MiscellaneousDeductionFailure:
Artem Belevich13e9b4d2016-12-07 19:27:16 +0000598 case Sema::TDK_CUDATargetMismatch:
Richard Smith9b534542015-12-31 02:02:54 +0000599 Result.Data = nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000600 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000601
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000602 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000603 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000604 Result.Data = Info.Param.getOpaqueValue();
605 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000606
Richard Smithc92d2062017-01-05 23:02:44 +0000607 case Sema::TDK_DeducedMismatch:
608 case Sema::TDK_DeducedMismatchNested: {
Richard Smith9b534542015-12-31 02:02:54 +0000609 // FIXME: Should allocate from normal heap so that we can free this later.
610 auto *Saved = new (Context) DFIDeducedMismatchArgs;
611 Saved->FirstArg = Info.FirstArg;
612 Saved->SecondArg = Info.SecondArg;
613 Saved->TemplateArgs = Info.take();
614 Saved->CallArgIndex = Info.CallArgIndex;
615 Result.Data = Saved;
616 break;
617 }
618
Richard Smith44ecdbd2013-01-31 05:19:49 +0000619 case Sema::TDK_NonDeducedMismatch: {
620 // FIXME: Should allocate from normal heap so that we can free this later.
621 DFIArguments *Saved = new (Context) DFIArguments;
622 Saved->FirstArg = Info.FirstArg;
623 Saved->SecondArg = Info.SecondArg;
624 Result.Data = Saved;
625 break;
626 }
627
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000628 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000629 case Sema::TDK_Underqualified: {
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000630 // FIXME: Should allocate from normal heap so that we can free this later.
631 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000632 Saved->Param = Info.Param;
633 Saved->FirstArg = Info.FirstArg;
634 Saved->SecondArg = Info.SecondArg;
635 Result.Data = Saved;
636 break;
637 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000638
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000639 case Sema::TDK_SubstitutionFailure:
Douglas Gregord09efd42010-05-08 20:07:26 +0000640 Result.Data = Info.take();
Richard Smith9ca64612012-05-07 09:03:25 +0000641 if (Info.hasSFINAEDiagnostic()) {
642 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
643 SourceLocation(), PartialDiagnostic::NullDiagnostic());
644 Info.takeSFINAEDiagnostic(*Diag);
645 Result.HasDiagnostic = true;
646 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000647 break;
Richard Smith6eedfe72017-01-09 08:01:21 +0000648
649 case Sema::TDK_Success:
650 case Sema::TDK_NonDependentConversionFailure:
651 llvm_unreachable("not a deduction failure");
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000652 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000653
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000654 return Result;
655}
John McCall0d1da222010-01-12 00:44:57 +0000656
Larisse Voufo98b20f12013-07-19 23:00:19 +0000657void DeductionFailureInfo::Destroy() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000658 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
659 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000660 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000661 case Sema::TDK_InstantiationDepth:
662 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000663 case Sema::TDK_TooManyArguments:
664 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000665 case Sema::TDK_InvalidExplicitArguments:
Artem Belevich13e9b4d2016-12-07 19:27:16 +0000666 case Sema::TDK_CUDATargetMismatch:
Richard Smith6eedfe72017-01-09 08:01:21 +0000667 case Sema::TDK_NonDependentConversionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000668 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000669
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000670 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000671 case Sema::TDK_Underqualified:
Richard Smith9b534542015-12-31 02:02:54 +0000672 case Sema::TDK_DeducedMismatch:
Richard Smithc92d2062017-01-05 23:02:44 +0000673 case Sema::TDK_DeducedMismatchNested:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000674 case Sema::TDK_NonDeducedMismatch:
Douglas Gregorb02d6b32010-05-08 20:20:05 +0000675 // FIXME: Destroy the data?
Craig Topperc3ec1492014-05-26 06:22:03 +0000676 Data = nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000677 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000678
679 case Sema::TDK_SubstitutionFailure:
Richard Smith9ca64612012-05-07 09:03:25 +0000680 // FIXME: Destroy the template argument list?
Craig Topperc3ec1492014-05-26 06:22:03 +0000681 Data = nullptr;
Richard Smith9ca64612012-05-07 09:03:25 +0000682 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
683 Diag->~PartialDiagnosticAt();
684 HasDiagnostic = false;
685 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000686 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000687
Douglas Gregor461761d2010-05-08 18:20:53 +0000688 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000689 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000690 break;
691 }
692}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000693
Larisse Voufo98b20f12013-07-19 23:00:19 +0000694PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
Richard Smith9ca64612012-05-07 09:03:25 +0000695 if (HasDiagnostic)
696 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
Craig Topperc3ec1492014-05-26 06:22:03 +0000697 return nullptr;
Richard Smith9ca64612012-05-07 09:03:25 +0000698}
699
Larisse Voufo98b20f12013-07-19 23:00:19 +0000700TemplateParameter DeductionFailureInfo::getTemplateParameter() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000701 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
702 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000703 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000704 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000705 case Sema::TDK_TooManyArguments:
706 case Sema::TDK_TooFewArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000707 case Sema::TDK_SubstitutionFailure:
Richard Smith9b534542015-12-31 02:02:54 +0000708 case Sema::TDK_DeducedMismatch:
Richard Smithc92d2062017-01-05 23:02:44 +0000709 case Sema::TDK_DeducedMismatchNested:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000710 case Sema::TDK_NonDeducedMismatch:
Artem Belevich13e9b4d2016-12-07 19:27:16 +0000711 case Sema::TDK_CUDATargetMismatch:
Richard Smith6eedfe72017-01-09 08:01:21 +0000712 case Sema::TDK_NonDependentConversionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000713 return TemplateParameter();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000714
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000715 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000716 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000717 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000718
719 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000720 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000721 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000722
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000723 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000724 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000725 break;
726 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000727
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000728 return TemplateParameter();
729}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000730
Larisse Voufo98b20f12013-07-19 23:00:19 +0000731TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
Douglas Gregord09efd42010-05-08 20:07:26 +0000732 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
Richard Smith44ecdbd2013-01-31 05:19:49 +0000733 case Sema::TDK_Success:
734 case Sema::TDK_Invalid:
735 case Sema::TDK_InstantiationDepth:
736 case Sema::TDK_TooManyArguments:
737 case Sema::TDK_TooFewArguments:
738 case Sema::TDK_Incomplete:
739 case Sema::TDK_InvalidExplicitArguments:
740 case Sema::TDK_Inconsistent:
741 case Sema::TDK_Underqualified:
742 case Sema::TDK_NonDeducedMismatch:
Artem Belevich13e9b4d2016-12-07 19:27:16 +0000743 case Sema::TDK_CUDATargetMismatch:
Richard Smith6eedfe72017-01-09 08:01:21 +0000744 case Sema::TDK_NonDependentConversionFailure:
Craig Topperc3ec1492014-05-26 06:22:03 +0000745 return nullptr;
Douglas Gregord09efd42010-05-08 20:07:26 +0000746
Richard Smith9b534542015-12-31 02:02:54 +0000747 case Sema::TDK_DeducedMismatch:
Richard Smithc92d2062017-01-05 23:02:44 +0000748 case Sema::TDK_DeducedMismatchNested:
Richard Smith9b534542015-12-31 02:02:54 +0000749 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
750
Richard Smith44ecdbd2013-01-31 05:19:49 +0000751 case Sema::TDK_SubstitutionFailure:
752 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000753
Richard Smith44ecdbd2013-01-31 05:19:49 +0000754 // Unhandled
755 case Sema::TDK_MiscellaneousDeductionFailure:
756 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000757 }
758
Craig Topperc3ec1492014-05-26 06:22:03 +0000759 return nullptr;
Douglas Gregord09efd42010-05-08 20:07:26 +0000760}
761
Larisse Voufo98b20f12013-07-19 23:00:19 +0000762const TemplateArgument *DeductionFailureInfo::getFirstArg() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000763 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
764 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000765 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000766 case Sema::TDK_InstantiationDepth:
767 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000768 case Sema::TDK_TooManyArguments:
769 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000770 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000771 case Sema::TDK_SubstitutionFailure:
Artem Belevich13e9b4d2016-12-07 19:27:16 +0000772 case Sema::TDK_CUDATargetMismatch:
Richard Smith6eedfe72017-01-09 08:01:21 +0000773 case Sema::TDK_NonDependentConversionFailure:
Craig Topperc3ec1492014-05-26 06:22:03 +0000774 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000775
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000776 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000777 case Sema::TDK_Underqualified:
Richard Smith9b534542015-12-31 02:02:54 +0000778 case Sema::TDK_DeducedMismatch:
Richard Smithc92d2062017-01-05 23:02:44 +0000779 case Sema::TDK_DeducedMismatchNested:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000780 case Sema::TDK_NonDeducedMismatch:
781 return &static_cast<DFIArguments*>(Data)->FirstArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000782
Douglas Gregor461761d2010-05-08 18:20:53 +0000783 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000784 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000785 break;
786 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000787
Craig Topperc3ec1492014-05-26 06:22:03 +0000788 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000789}
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000790
Larisse Voufo98b20f12013-07-19 23:00:19 +0000791const TemplateArgument *DeductionFailureInfo::getSecondArg() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000792 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
793 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000794 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000795 case Sema::TDK_InstantiationDepth:
796 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000797 case Sema::TDK_TooManyArguments:
798 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000799 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000800 case Sema::TDK_SubstitutionFailure:
Artem Belevich13e9b4d2016-12-07 19:27:16 +0000801 case Sema::TDK_CUDATargetMismatch:
Richard Smith6eedfe72017-01-09 08:01:21 +0000802 case Sema::TDK_NonDependentConversionFailure:
Craig Topperc3ec1492014-05-26 06:22:03 +0000803 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000804
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000805 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000806 case Sema::TDK_Underqualified:
Richard Smith9b534542015-12-31 02:02:54 +0000807 case Sema::TDK_DeducedMismatch:
Richard Smithc92d2062017-01-05 23:02:44 +0000808 case Sema::TDK_DeducedMismatchNested:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000809 case Sema::TDK_NonDeducedMismatch:
810 return &static_cast<DFIArguments*>(Data)->SecondArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000811
Douglas Gregor461761d2010-05-08 18:20:53 +0000812 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000813 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000814 break;
815 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000816
Craig Topperc3ec1492014-05-26 06:22:03 +0000817 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000818}
819
Richard Smith9b534542015-12-31 02:02:54 +0000820llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
Richard Smithc92d2062017-01-05 23:02:44 +0000821 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
822 case Sema::TDK_DeducedMismatch:
823 case Sema::TDK_DeducedMismatchNested:
Richard Smith9b534542015-12-31 02:02:54 +0000824 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
825
Richard Smithc92d2062017-01-05 23:02:44 +0000826 default:
827 return llvm::None;
828 }
Richard Smith9b534542015-12-31 02:02:54 +0000829}
830
Benjamin Kramer97e59492012-10-09 15:52:25 +0000831void OverloadCandidateSet::destroyCandidates() {
Richard Smith0bf93aa2012-07-18 23:52:59 +0000832 for (iterator i = begin(), e = end(); i != e; ++i) {
Richard Smith6eedfe72017-01-09 08:01:21 +0000833 for (auto &C : i->Conversions)
834 C.~ImplicitConversionSequence();
Richard Smith0bf93aa2012-07-18 23:52:59 +0000835 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
836 i->DeductionFailure.Destroy();
837 }
Benjamin Kramer97e59492012-10-09 15:52:25 +0000838}
839
840void OverloadCandidateSet::clear() {
841 destroyCandidates();
George Burgess IV177399e2017-01-09 04:12:14 +0000842 SlabAllocator.Reset();
843 NumInlineBytesUsed = 0;
Benjamin Kramerfb761ff2012-01-14 16:31:55 +0000844 Candidates.clear();
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000845 Functions.clear();
846}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000847
John McCall4124c492011-10-17 18:40:02 +0000848namespace {
849 class UnbridgedCastsSet {
850 struct Entry {
851 Expr **Addr;
852 Expr *Saved;
853 };
854 SmallVector<Entry, 2> Entries;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +0000855
John McCall4124c492011-10-17 18:40:02 +0000856 public:
857 void save(Sema &S, Expr *&E) {
858 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
859 Entry entry = { &E, E };
860 Entries.push_back(entry);
861 E = S.stripARCUnbridgedCast(E);
862 }
863
864 void restore() {
865 for (SmallVectorImpl<Entry>::iterator
Simon Pilgrimfb9662a2017-06-01 18:17:18 +0000866 i = Entries.begin(), e = Entries.end(); i != e; ++i)
John McCall4124c492011-10-17 18:40:02 +0000867 *i->Addr = i->Saved;
868 }
869 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000870}
John McCall4124c492011-10-17 18:40:02 +0000871
872/// checkPlaceholderForOverload - Do any interesting placeholder-like
873/// preprocessing on the given expression.
874///
875/// \param unbridgedCasts a collection to which to add unbridged casts;
876/// without this, they will be immediately diagnosed as errors
877///
878/// Return true on unrecoverable error.
Craig Topperc3ec1492014-05-26 06:22:03 +0000879static bool
880checkPlaceholderForOverload(Sema &S, Expr *&E,
881 UnbridgedCastsSet *unbridgedCasts = nullptr) {
John McCall4124c492011-10-17 18:40:02 +0000882 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
883 // We can't handle overloaded expressions here because overload
884 // resolution might reasonably tweak them.
885 if (placeholder->getKind() == BuiltinType::Overload) return false;
886
887 // If the context potentially accepts unbridged ARC casts, strip
888 // the unbridged cast and add it to the collection for later restoration.
889 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
890 unbridgedCasts) {
891 unbridgedCasts->save(S, E);
892 return false;
893 }
894
895 // Go ahead and check everything else.
896 ExprResult result = S.CheckPlaceholderExpr(E);
897 if (result.isInvalid())
898 return true;
899
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000900 E = result.get();
John McCall4124c492011-10-17 18:40:02 +0000901 return false;
902 }
903
904 // Nothing to do.
905 return false;
906}
907
908/// checkArgPlaceholdersForOverload - Check a set of call operands for
909/// placeholders.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000910static bool checkArgPlaceholdersForOverload(Sema &S,
911 MultiExprArg Args,
John McCall4124c492011-10-17 18:40:02 +0000912 UnbridgedCastsSet &unbridged) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000913 for (unsigned i = 0, e = Args.size(); i != e; ++i)
914 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
John McCall4124c492011-10-17 18:40:02 +0000915 return true;
916
917 return false;
918}
919
George Burgess IV2d82b092017-04-06 00:23:31 +0000920/// Determine whether the given New declaration is an overload of the
921/// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if
922/// New and Old cannot be overloaded, e.g., if New has the same signature as
923/// some function in Old (C++ 1.3.10) or if the Old declarations aren't
924/// functions (or function templates) at all. When it does return Ovl_Match or
925/// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be
926/// overloaded with. This decl may be a UsingShadowDecl on top of the underlying
927/// declaration.
928///
929/// Example: Given the following input:
930///
931/// void f(int, float); // #1
932/// void f(int, int); // #2
933/// int f(int, int); // #3
934///
935/// When we process #1, there is no previous declaration of "f", so IsOverload
936/// will not be used.
937///
938/// When we process #2, Old contains only the FunctionDecl for #1. By comparing
939/// the parameter types, we see that #1 and #2 are overloaded (since they have
940/// different signatures), so this routine returns Ovl_Overload; MatchedDecl is
941/// unchanged.
942///
943/// When we process #3, Old is an overload set containing #1 and #2. We compare
944/// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then
945/// #3 to #2. Since the signatures of #3 and #2 are identical (return types of
946/// functions are not part of the signature), IsOverload returns Ovl_Match and
947/// MatchedDecl will be set to point to the FunctionDecl for #2.
948///
949/// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class
950/// by a using declaration. The rules for whether to hide shadow declarations
951/// ignore some properties which otherwise figure into a function template's
952/// signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000953Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000954Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
955 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000956 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000957 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000958 NamedDecl *OldD = *I;
959
960 bool OldIsUsingDecl = false;
961 if (isa<UsingShadowDecl>(OldD)) {
962 OldIsUsingDecl = true;
963
964 // We can always introduce two using declarations into the same
965 // context, even if they have identical signatures.
966 if (NewIsUsingDecl) continue;
967
968 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
969 }
970
Richard Smithf091e122015-09-15 01:28:55 +0000971 // A using-declaration does not conflict with another declaration
972 // if one of them is hidden.
973 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
974 continue;
975
John McCalle9cccd82010-06-16 08:42:20 +0000976 // If either declaration was introduced by a using declaration,
977 // we'll need to use slightly different rules for matching.
978 // Essentially, these rules are the normal rules, except that
979 // function templates hide function templates with different
980 // return types or template parameter lists.
981 bool UseMemberUsingDeclRules =
John McCallc70fca62013-04-03 21:19:47 +0000982 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
983 !New->getFriendObjectKind();
John McCalle9cccd82010-06-16 08:42:20 +0000984
Alp Tokera2794f92014-01-22 07:29:52 +0000985 if (FunctionDecl *OldF = OldD->getAsFunction()) {
John McCalle9cccd82010-06-16 08:42:20 +0000986 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
987 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
988 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
989 continue;
990 }
991
Alp Tokera2794f92014-01-22 07:29:52 +0000992 if (!isa<FunctionTemplateDecl>(OldD) &&
993 !shouldLinkPossiblyHiddenDecl(*I, New))
Rafael Espindola5bddd6a2013-04-15 12:49:13 +0000994 continue;
995
John McCalldaa3d6b2009-12-09 03:35:25 +0000996 Match = *I;
997 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000998 }
Richard Smith151c4562016-12-20 21:35:28 +0000999 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +00001000 // We can overload with these, which can show up when doing
1001 // redeclaration checks for UsingDecls.
1002 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalla8987a2942010-11-10 03:01:53 +00001003 } else if (isa<TagDecl>(OldD)) {
1004 // We can always overload with tags by hiding them.
Richard Smithd8a9e372016-12-18 21:39:37 +00001005 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +00001006 // Optimistically assume that an unresolved using decl will
1007 // overload; if it doesn't, we'll have to diagnose during
1008 // template instantiation.
Richard Smithd8a9e372016-12-18 21:39:37 +00001009 //
1010 // Exception: if the scope is dependent and this is not a class
1011 // member, the using declaration can only introduce an enumerator.
1012 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1013 Match = *I;
1014 return Ovl_NonFunction;
1015 }
John McCall84d87672009-12-10 09:41:52 +00001016 } else {
John McCall1f82f242009-11-18 22:49:29 +00001017 // (C++ 13p1):
1018 // Only function declarations can be overloaded; object and type
1019 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +00001020 Match = *I;
1021 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +00001022 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001023 }
John McCall1f82f242009-11-18 22:49:29 +00001024
John McCalldaa3d6b2009-12-09 03:35:25 +00001025 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +00001026}
1027
Richard Smithac974a32013-06-30 09:48:50 +00001028bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
Justin Lebarba122ab2016-03-30 23:30:21 +00001029 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
Richard Smithac974a32013-06-30 09:48:50 +00001030 // C++ [basic.start.main]p2: This function shall not be overloaded.
1031 if (New->isMain())
Rafael Espindola576127d2012-12-28 14:21:58 +00001032 return false;
Rafael Espindola7cf35ef2013-01-12 01:47:40 +00001033
David Majnemerc729b0b2013-09-16 22:44:20 +00001034 // MSVCRT user defined entry points cannot be overloaded.
1035 if (New->isMSVCRTEntryPoint())
1036 return false;
1037
John McCall1f82f242009-11-18 22:49:29 +00001038 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1039 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1040
1041 // C++ [temp.fct]p2:
1042 // A function template can be overloaded with other function templates
1043 // and with normal (non-template) functions.
Craig Topperc3ec1492014-05-26 06:22:03 +00001044 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
John McCall1f82f242009-11-18 22:49:29 +00001045 return true;
1046
1047 // Is the function New an overload of the function Old?
Richard Smithac974a32013-06-30 09:48:50 +00001048 QualType OldQType = Context.getCanonicalType(Old->getType());
1049 QualType NewQType = Context.getCanonicalType(New->getType());
John McCall1f82f242009-11-18 22:49:29 +00001050
1051 // Compare the signatures (C++ 1.3.10) of the two functions to
1052 // determine whether they are overloads. If we find any mismatch
1053 // in the signature, they are overloads.
1054
1055 // If either of these functions is a K&R-style function (no
1056 // prototype), then we consider them to have matching signatures.
1057 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1058 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1059 return false;
1060
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001061 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1062 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
John McCall1f82f242009-11-18 22:49:29 +00001063
1064 // The signature of a function includes the types of its
1065 // parameters (C++ 1.3.10), which includes the presence or absence
1066 // of the ellipsis; see C++ DR 357).
1067 if (OldQType != NewQType &&
Alp Toker9cacbab2014-01-20 20:26:09 +00001068 (OldType->getNumParams() != NewType->getNumParams() ||
John McCall1f82f242009-11-18 22:49:29 +00001069 OldType->isVariadic() != NewType->isVariadic() ||
Alp Toker9cacbab2014-01-20 20:26:09 +00001070 !FunctionParamTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +00001071 return true;
1072
1073 // C++ [temp.over.link]p4:
1074 // The signature of a function template consists of its function
1075 // signature, its return type and its template parameter list. The names
1076 // of the template parameters are significant only for establishing the
1077 // relationship between the template parameters and the rest of the
1078 // signature.
1079 //
1080 // We check the return type and template parameter lists for function
1081 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +00001082 //
1083 // However, we don't consider either of these when deciding whether
1084 // a member introduced by a shadow declaration is hidden.
Justin Lebar39fd5292016-03-30 20:41:05 +00001085 if (!UseMemberUsingDeclRules && NewTemplate &&
Richard Smithac974a32013-06-30 09:48:50 +00001086 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1087 OldTemplate->getTemplateParameters(),
1088 false, TPL_TemplateMatch) ||
Alp Toker314cc812014-01-25 16:55:45 +00001089 OldType->getReturnType() != NewType->getReturnType()))
John McCall1f82f242009-11-18 22:49:29 +00001090 return true;
1091
1092 // If the function is a class member, its signature includes the
Douglas Gregorb2f8aa92011-01-26 17:47:49 +00001093 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall1f82f242009-11-18 22:49:29 +00001094 //
1095 // As part of this, also check whether one of the member functions
1096 // is static, in which case they are not overloads (C++
1097 // 13.1p2). While not part of the definition of the signature,
1098 // this check is important to determine whether these functions
1099 // can be overloaded.
Richard Smith574f4f62013-01-14 05:37:29 +00001100 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1101 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
John McCall1f82f242009-11-18 22:49:29 +00001102 if (OldMethod && NewMethod &&
Richard Smith574f4f62013-01-14 05:37:29 +00001103 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1104 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
Justin Lebar39fd5292016-03-30 20:41:05 +00001105 if (!UseMemberUsingDeclRules &&
Richard Smith574f4f62013-01-14 05:37:29 +00001106 (OldMethod->getRefQualifier() == RQ_None ||
1107 NewMethod->getRefQualifier() == RQ_None)) {
1108 // C++0x [over.load]p2:
1109 // - Member function declarations with the same name and the same
1110 // parameter-type-list as well as member function template
1111 // declarations with the same name, the same parameter-type-list, and
1112 // the same template parameter lists cannot be overloaded if any of
1113 // them, but not all, have a ref-qualifier (8.3.5).
Richard Smithac974a32013-06-30 09:48:50 +00001114 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
Richard Smith574f4f62013-01-14 05:37:29 +00001115 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
Richard Smithac974a32013-06-30 09:48:50 +00001116 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
Richard Smith574f4f62013-01-14 05:37:29 +00001117 }
1118 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001119 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001120
Richard Smith574f4f62013-01-14 05:37:29 +00001121 // We may not have applied the implicit const for a constexpr member
1122 // function yet (because we haven't yet resolved whether this is a static
1123 // or non-static member function). Add it now, on the assumption that this
1124 // is a redeclaration of OldMethod.
David Majnemer42350df2013-11-03 23:51:28 +00001125 unsigned OldQuals = OldMethod->getTypeQualifiers();
Richard Smith574f4f62013-01-14 05:37:29 +00001126 unsigned NewQuals = NewMethod->getTypeQualifiers();
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001127 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
Richard Smithe83b1d32013-06-25 18:46:26 +00001128 !isa<CXXConstructorDecl>(NewMethod))
Richard Smith574f4f62013-01-14 05:37:29 +00001129 NewQuals |= Qualifiers::Const;
David Majnemer42350df2013-11-03 23:51:28 +00001130
1131 // We do not allow overloading based off of '__restrict'.
1132 OldQuals &= ~Qualifiers::Restrict;
1133 NewQuals &= ~Qualifiers::Restrict;
1134 if (OldQuals != NewQuals)
Richard Smith574f4f62013-01-14 05:37:29 +00001135 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001136 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001137
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001138 // Though pass_object_size is placed on parameters and takes an argument, we
1139 // consider it to be a function-level modifier for the sake of function
1140 // identity. Either the function has one or more parameters with
1141 // pass_object_size or it doesn't.
1142 if (functionHasPassObjectSizeParams(New) !=
1143 functionHasPassObjectSizeParams(Old))
1144 return true;
1145
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001146 // enable_if attributes are an order-sensitive part of the signature.
1147 for (specific_attr_iterator<EnableIfAttr>
1148 NewI = New->specific_attr_begin<EnableIfAttr>(),
1149 NewE = New->specific_attr_end<EnableIfAttr>(),
1150 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1151 OldE = Old->specific_attr_end<EnableIfAttr>();
1152 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1153 if (NewI == NewE || OldI == OldE)
1154 return true;
1155 llvm::FoldingSetNodeID NewID, OldID;
1156 NewI->getCond()->Profile(NewID, Context, true);
1157 OldI->getCond()->Profile(OldID, Context, true);
Nick Lewyckyd950ae72014-01-21 01:30:30 +00001158 if (NewID != OldID)
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001159 return true;
1160 }
1161
Justin Lebarba122ab2016-03-30 23:30:21 +00001162 if (getLangOpts().CUDA && ConsiderCudaAttrs) {
Justin Lebare060feb2016-10-03 16:48:23 +00001163 // Don't allow overloading of destructors. (In theory we could, but it
1164 // would be a giant change to clang.)
1165 if (isa<CXXDestructorDecl>(New))
1166 return false;
1167
Artem Belevich94a55e82015-09-22 17:22:59 +00001168 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1169 OldTarget = IdentifyCUDATarget(Old);
Artem Belevich13e9b4d2016-12-07 19:27:16 +00001170 if (NewTarget == CFT_InvalidTarget)
Artem Belevich94a55e82015-09-22 17:22:59 +00001171 return false;
1172
1173 assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target.");
1174
Justin Lebar53b000af2016-10-03 16:48:27 +00001175 // Allow overloading of functions with same signature and different CUDA
1176 // target attributes.
Artem Belevich94a55e82015-09-22 17:22:59 +00001177 return NewTarget != OldTarget;
1178 }
1179
John McCall1f82f242009-11-18 22:49:29 +00001180 // The signatures match; this is not an overload.
1181 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001182}
1183
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00001184/// \brief Checks availability of the function depending on the current
1185/// function context. Inside an unavailable function, unavailability is ignored.
1186///
1187/// \returns true if \arg FD is unavailable and current context is inside
1188/// an available function, false otherwise.
1189bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
Duncan P. N. Exon Smith85363922016-03-08 10:28:52 +00001190 if (!FD->isUnavailable())
1191 return false;
1192
1193 // Walk up the context of the caller.
1194 Decl *C = cast<Decl>(CurContext);
1195 do {
1196 if (C->isUnavailable())
1197 return false;
1198 } while ((C = cast_or_null<Decl>(C->getDeclContext())));
1199 return true;
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00001200}
1201
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001202/// \brief Tries a user-defined conversion from From to ToType.
1203///
1204/// Produces an implicit conversion sequence for when a standard conversion
1205/// is not an option. See TryImplicitConversion for more information.
1206static ImplicitConversionSequence
1207TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1208 bool SuppressUserConversions,
1209 bool AllowExplicit,
1210 bool InOverloadResolution,
1211 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001212 bool AllowObjCWritebackConversion,
1213 bool AllowObjCConversionOnExplicit) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001214 ImplicitConversionSequence ICS;
1215
1216 if (SuppressUserConversions) {
1217 // We're not in the case above, so there is no conversion that
1218 // we can perform.
1219 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1220 return ICS;
1221 }
1222
1223 // Attempt user-defined conversion.
Richard Smith100b24a2014-04-17 01:52:14 +00001224 OverloadCandidateSet Conversions(From->getExprLoc(),
1225 OverloadCandidateSet::CSK_Normal);
Richard Smith48372b62015-01-27 03:30:40 +00001226 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1227 Conversions, AllowExplicit,
1228 AllowObjCConversionOnExplicit)) {
1229 case OR_Success:
1230 case OR_Deleted:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001231 ICS.setUserDefined();
1232 // C++ [over.ics.user]p4:
1233 // A conversion of an expression of class type to the same class
1234 // type is given Exact Match rank, and a conversion of an
1235 // expression of class type to a base class of that type is
1236 // given Conversion rank, in spite of the fact that a copy
1237 // constructor (i.e., a user-defined conversion function) is
1238 // called for those cases.
1239 if (CXXConstructorDecl *Constructor
1240 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1241 QualType FromCanon
1242 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1243 QualType ToCanon
1244 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1245 if (Constructor->isCopyConstructor() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00001246 (FromCanon == ToCanon ||
1247 S.IsDerivedFrom(From->getLocStart(), FromCanon, ToCanon))) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001248 // Turn this into a "standard" conversion sequence, so that it
1249 // gets ranked with standard conversion sequences.
Richard Smithc2bebe92016-05-11 20:37:46 +00001250 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001251 ICS.setStandard();
1252 ICS.Standard.setAsIdentityConversion();
1253 ICS.Standard.setFromType(From->getType());
1254 ICS.Standard.setAllToTypes(ToType);
1255 ICS.Standard.CopyConstructor = Constructor;
Richard Smithc2bebe92016-05-11 20:37:46 +00001256 ICS.Standard.FoundCopyConstructor = Found;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001257 if (ToCanon != FromCanon)
1258 ICS.Standard.Second = ICK_Derived_To_Base;
1259 }
1260 }
Richard Smith48372b62015-01-27 03:30:40 +00001261 break;
1262
1263 case OR_Ambiguous:
Richard Smith1bbaba82015-01-27 23:23:39 +00001264 ICS.setAmbiguous();
1265 ICS.Ambiguous.setFromType(From->getType());
1266 ICS.Ambiguous.setToType(ToType);
1267 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1268 Cand != Conversions.end(); ++Cand)
1269 if (Cand->Viable)
Richard Smithc2bebe92016-05-11 20:37:46 +00001270 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
Richard Smith1bbaba82015-01-27 23:23:39 +00001271 break;
Richard Smith48372b62015-01-27 03:30:40 +00001272
1273 // Fall through.
1274 case OR_No_Viable_Function:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001275 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Richard Smith48372b62015-01-27 03:30:40 +00001276 break;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001277 }
1278
1279 return ICS;
1280}
1281
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001282/// TryImplicitConversion - Attempt to perform an implicit conversion
1283/// from the given expression (Expr) to the given type (ToType). This
1284/// function returns an implicit conversion sequence that can be used
1285/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001286///
1287/// void f(float f);
1288/// void g(int i) { f(i); }
1289///
1290/// this routine would produce an implicit conversion sequence to
1291/// describe the initialization of f from i, which will be a standard
1292/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1293/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1294//
1295/// Note that this routine only determines how the conversion can be
1296/// performed; it does not actually perform the conversion. As such,
1297/// it will not produce any diagnostics if no conversion is available,
1298/// but will instead return an implicit conversion sequence of kind
1299/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +00001300///
1301/// If @p SuppressUserConversions, then user-defined conversions are
1302/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +00001303/// If @p AllowExplicit, then explicit user-defined conversions are
1304/// permitted.
John McCall31168b02011-06-15 23:02:42 +00001305///
1306/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1307/// writeback conversion, which allows __autoreleasing id* parameters to
1308/// be initialized with __strong id* or __weak id* arguments.
John McCall5c32be02010-08-24 20:38:10 +00001309static ImplicitConversionSequence
1310TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1311 bool SuppressUserConversions,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001312 bool AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001313 bool InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001314 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001315 bool AllowObjCWritebackConversion,
1316 bool AllowObjCConversionOnExplicit) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001317 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +00001318 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001319 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall0d1da222010-01-12 00:44:57 +00001320 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +00001321 return ICS;
1322 }
1323
David Blaikiebbafb8a2012-03-11 07:00:24 +00001324 if (!S.getLangOpts().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +00001325 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +00001326 return ICS;
1327 }
1328
Douglas Gregor836a7e82010-08-11 02:15:33 +00001329 // C++ [over.ics.user]p4:
1330 // A conversion of an expression of class type to the same class
1331 // type is given Exact Match rank, and a conversion of an
1332 // expression of class type to a base class of that type is
1333 // given Conversion rank, in spite of the fact that a copy/move
1334 // constructor (i.e., a user-defined conversion function) is
1335 // called for those cases.
1336 QualType FromType = From->getType();
1337 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00001338 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00001339 S.IsDerivedFrom(From->getLocStart(), FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001340 ICS.setStandard();
1341 ICS.Standard.setAsIdentityConversion();
1342 ICS.Standard.setFromType(FromType);
1343 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001344
Douglas Gregor5ab11652010-04-17 22:01:05 +00001345 // We don't actually check at this point whether there is a valid
1346 // copy/move constructor, since overloading just assumes that it
1347 // exists. When we actually perform initialization, we'll find the
1348 // appropriate constructor to copy the returned object, if needed.
Craig Topperc3ec1492014-05-26 06:22:03 +00001349 ICS.Standard.CopyConstructor = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001350
Douglas Gregor5ab11652010-04-17 22:01:05 +00001351 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +00001352 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +00001353 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001354
Douglas Gregor836a7e82010-08-11 02:15:33 +00001355 return ICS;
1356 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001357
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001358 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1359 AllowExplicit, InOverloadResolution, CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001360 AllowObjCWritebackConversion,
1361 AllowObjCConversionOnExplicit);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001362}
1363
John McCall31168b02011-06-15 23:02:42 +00001364ImplicitConversionSequence
1365Sema::TryImplicitConversion(Expr *From, QualType ToType,
1366 bool SuppressUserConversions,
1367 bool AllowExplicit,
1368 bool InOverloadResolution,
1369 bool CStyle,
1370 bool AllowObjCWritebackConversion) {
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00001371 return ::TryImplicitConversion(*this, From, ToType,
Richard Smith17c00b42014-11-12 01:24:00 +00001372 SuppressUserConversions, AllowExplicit,
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00001373 InOverloadResolution, CStyle,
Richard Smith17c00b42014-11-12 01:24:00 +00001374 AllowObjCWritebackConversion,
1375 /*AllowObjCConversionOnExplicit=*/false);
John McCall5c32be02010-08-24 20:38:10 +00001376}
1377
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001378/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley01296292011-04-08 18:41:53 +00001379/// expression From to the type ToType. Returns the
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001380/// converted expression. Flavor is the kind of conversion we're
1381/// performing, used in the error message. If @p AllowExplicit,
1382/// explicit user-defined conversions are permitted.
John Wiegley01296292011-04-08 18:41:53 +00001383ExprResult
1384Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redlcc152642011-10-16 18:19:06 +00001385 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001386 ImplicitConversionSequence ICS;
Sebastian Redlcc152642011-10-16 18:19:06 +00001387 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001388}
1389
John Wiegley01296292011-04-08 18:41:53 +00001390ExprResult
1391Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001392 AssignmentAction Action, bool AllowExplicit,
Sebastian Redlcc152642011-10-16 18:19:06 +00001393 ImplicitConversionSequence& ICS) {
John McCall526ab472011-10-25 17:37:35 +00001394 if (checkPlaceholderForOverload(*this, From))
1395 return ExprError();
1396
John McCall31168b02011-06-15 23:02:42 +00001397 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1398 bool AllowObjCWritebackConversion
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00001399 = getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001400 (Action == AA_Passing || Action == AA_Sending);
Fariborz Jahanian381edf52013-12-16 22:54:37 +00001401 if (getLangOpts().ObjC1)
1402 CheckObjCBridgeRelatedConversions(From->getLocStart(),
1403 ToType, From->getType(), From);
Richard Smith17c00b42014-11-12 01:24:00 +00001404 ICS = ::TryImplicitConversion(*this, From, ToType,
1405 /*SuppressUserConversions=*/false,
1406 AllowExplicit,
1407 /*InOverloadResolution=*/false,
1408 /*CStyle=*/false,
1409 AllowObjCWritebackConversion,
1410 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001411 return PerformImplicitConversion(From, ToType, ICS, Action);
1412}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001413
1414/// \brief Determine whether the conversion from FromType to ToType is a valid
Richard Smith3c4f8d22016-10-16 17:54:23 +00001415/// conversion that strips "noexcept" or "noreturn" off the nested function
1416/// type.
1417bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
Chandler Carruth53e61b02011-06-18 01:19:03 +00001418 QualType &ResultTy) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001419 if (Context.hasSameUnqualifiedType(FromType, ToType))
1420 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001421
John McCall991eb4b2010-12-21 00:44:39 +00001422 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
Richard Smith3c4f8d22016-10-16 17:54:23 +00001423 // or F(t noexcept) -> F(t)
John McCall991eb4b2010-12-21 00:44:39 +00001424 // where F adds one of the following at most once:
1425 // - a pointer
1426 // - a member pointer
1427 // - a block pointer
Richard Smitheb7ef2e2016-10-20 21:53:09 +00001428 // Changes here need matching changes in FindCompositePointerType.
John McCall991eb4b2010-12-21 00:44:39 +00001429 CanQualType CanTo = Context.getCanonicalType(ToType);
1430 CanQualType CanFrom = Context.getCanonicalType(FromType);
1431 Type::TypeClass TyClass = CanTo->getTypeClass();
1432 if (TyClass != CanFrom->getTypeClass()) return false;
1433 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1434 if (TyClass == Type::Pointer) {
1435 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1436 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1437 } else if (TyClass == Type::BlockPointer) {
1438 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1439 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1440 } else if (TyClass == Type::MemberPointer) {
Richard Smitheb7ef2e2016-10-20 21:53:09 +00001441 auto ToMPT = CanTo.getAs<MemberPointerType>();
1442 auto FromMPT = CanFrom.getAs<MemberPointerType>();
1443 // A function pointer conversion cannot change the class of the function.
1444 if (ToMPT->getClass() != FromMPT->getClass())
1445 return false;
1446 CanTo = ToMPT->getPointeeType();
1447 CanFrom = FromMPT->getPointeeType();
John McCall991eb4b2010-12-21 00:44:39 +00001448 } else {
1449 return false;
1450 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001451
John McCall991eb4b2010-12-21 00:44:39 +00001452 TyClass = CanTo->getTypeClass();
1453 if (TyClass != CanFrom->getTypeClass()) return false;
1454 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1455 return false;
1456 }
1457
Richard Smith3c4f8d22016-10-16 17:54:23 +00001458 const auto *FromFn = cast<FunctionType>(CanFrom);
1459 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
John McCall991eb4b2010-12-21 00:44:39 +00001460
Richard Smith6f427402016-10-20 00:01:36 +00001461 const auto *ToFn = cast<FunctionType>(CanTo);
Richard Smith3c4f8d22016-10-16 17:54:23 +00001462 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1463
1464 bool Changed = false;
1465
1466 // Drop 'noreturn' if not present in target type.
1467 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1468 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1469 Changed = true;
1470 }
1471
1472 // Drop 'noexcept' if not present in target type.
1473 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
Richard Smith6f427402016-10-20 00:01:36 +00001474 const auto *ToFPT = cast<FunctionProtoType>(ToFn);
Richard Smith3c4f8d22016-10-16 17:54:23 +00001475 if (FromFPT->isNothrow(Context) && !ToFPT->isNothrow(Context)) {
1476 FromFn = cast<FunctionType>(
1477 Context.getFunctionType(FromFPT->getReturnType(),
1478 FromFPT->getParamTypes(),
1479 FromFPT->getExtProtoInfo().withExceptionSpec(
1480 FunctionProtoType::ExceptionSpecInfo()))
1481 .getTypePtr());
1482 Changed = true;
1483 }
Akira Hatanakae9744792017-09-20 06:32:45 +00001484
1485 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1486 // only if the ExtParameterInfo lists of the two function prototypes can be
1487 // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1488 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
1489 bool CanUseToFPT, CanUseFromFPT;
1490 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1491 CanUseFromFPT, NewParamInfos) &&
1492 CanUseToFPT && !CanUseFromFPT) {
1493 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1494 ExtInfo.ExtParameterInfos =
1495 NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1496 QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1497 FromFPT->getParamTypes(), ExtInfo);
1498 FromFn = QT->getAs<FunctionType>();
1499 Changed = true;
1500 }
Richard Smith3c4f8d22016-10-16 17:54:23 +00001501 }
1502
1503 if (!Changed)
1504 return false;
1505
John McCall991eb4b2010-12-21 00:44:39 +00001506 assert(QualType(FromFn, 0).isCanonical());
1507 if (QualType(FromFn, 0) != CanTo) return false;
1508
1509 ResultTy = ToType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001510 return true;
1511}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001512
Douglas Gregor46188682010-05-18 22:42:18 +00001513/// \brief Determine whether the conversion from FromType to ToType is a valid
1514/// vector conversion.
1515///
1516/// \param ICK Will be set to the vector conversion kind, if this is a vector
1517/// conversion.
John McCall9b595db2014-02-04 23:58:19 +00001518static bool IsVectorConversion(Sema &S, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001519 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregor46188682010-05-18 22:42:18 +00001520 // We need at least one of these types to be a vector type to have a vector
1521 // conversion.
1522 if (!ToType->isVectorType() && !FromType->isVectorType())
1523 return false;
1524
1525 // Identical types require no conversions.
John McCall9b595db2014-02-04 23:58:19 +00001526 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor46188682010-05-18 22:42:18 +00001527 return false;
1528
1529 // There are no conversions between extended vector types, only identity.
1530 if (ToType->isExtVectorType()) {
1531 // There are no conversions between extended vector types other than the
1532 // identity conversion.
1533 if (FromType->isExtVectorType())
1534 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001535
Douglas Gregor46188682010-05-18 22:42:18 +00001536 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +00001537 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +00001538 ICK = ICK_Vector_Splat;
1539 return true;
1540 }
1541 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001542
1543 // We can perform the conversion between vector types in the following cases:
1544 // 1)vector types are equivalent AltiVec and GCC vector types
1545 // 2)lax vector conversions are permitted and the vector types are of the
1546 // same size
1547 if (ToType->isVectorType() && FromType->isVectorType()) {
John McCall9b595db2014-02-04 23:58:19 +00001548 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1549 S.isLaxVectorConversion(FromType, ToType)) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001550 ICK = ICK_Vector_Conversion;
1551 return true;
1552 }
Douglas Gregor46188682010-05-18 22:42:18 +00001553 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001554
Douglas Gregor46188682010-05-18 22:42:18 +00001555 return false;
1556}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001557
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001558static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1559 bool InOverloadResolution,
1560 StandardConversionSequence &SCS,
1561 bool CStyle);
George Burgess IV45461812015-10-11 20:13:20 +00001562
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001563/// IsStandardConversion - Determines whether there is a standard
1564/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1565/// expression From to the type ToType. Standard conversion sequences
1566/// only consider non-class types; for conversions that involve class
1567/// types, use TryImplicitConversion. If a conversion exists, SCS will
1568/// contain the standard conversion sequence required to perform this
1569/// conversion and this routine will return true. Otherwise, this
1570/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +00001571static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1572 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +00001573 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +00001574 bool CStyle,
1575 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001576 QualType FromType = From->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001577
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001578 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +00001579 SCS.setAsIdentityConversion();
Douglas Gregor47d3f272008-12-19 17:40:08 +00001580 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +00001581 SCS.setFromType(FromType);
Craig Topperc3ec1492014-05-26 06:22:03 +00001582 SCS.CopyConstructor = nullptr;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001583
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001584 // There are no standard conversions for class types in C++, so
George Burgess IV45461812015-10-11 20:13:20 +00001585 // abort early. When overloading in C, however, we do permit them.
1586 if (S.getLangOpts().CPlusPlus &&
1587 (FromType->isRecordType() || ToType->isRecordType()))
1588 return false;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001589
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001590 // The first conversion can be an lvalue-to-rvalue conversion,
1591 // array-to-pointer conversion, or function-to-pointer conversion
1592 // (C++ 4p1).
1593
John McCall5c32be02010-08-24 20:38:10 +00001594 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001595 DeclAccessPair AccessPair;
1596 if (FunctionDecl *Fn
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001597 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall5c32be02010-08-24 20:38:10 +00001598 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001599 // We were able to resolve the address of the overloaded function,
1600 // so we can convert to the type of that function.
1601 FromType = Fn->getType();
Ehsan Akhgaric3ad3ba2014-07-22 20:20:14 +00001602 SCS.setFromType(FromType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00001603
1604 // we can sometimes resolve &foo<int> regardless of ToType, so check
1605 // if the type matches (identity) or we are converting to bool
1606 if (!S.Context.hasSameUnqualifiedType(
1607 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1608 QualType resultTy;
1609 // if the function type matches except for [[noreturn]], it's ok
Richard Smith3c4f8d22016-10-16 17:54:23 +00001610 if (!S.IsFunctionConversion(FromType,
Douglas Gregorb491ed32011-02-19 21:32:49 +00001611 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00001612 // otherwise, only a boolean conversion is standard
1613 if (!ToType->isBooleanType())
1614 return false;
Douglas Gregor980fb162010-04-29 18:24:40 +00001615 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001616
Chandler Carruthffce2452011-03-29 08:08:18 +00001617 // Check if the "from" expression is taking the address of an overloaded
1618 // function and recompute the FromType accordingly. Take advantage of the
1619 // fact that non-static member functions *must* have such an address-of
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00001620 // expression.
Chandler Carruthffce2452011-03-29 08:08:18 +00001621 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1622 if (Method && !Method->isStatic()) {
1623 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1624 "Non-unary operator on non-static member address");
1625 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1626 == UO_AddrOf &&
1627 "Non-address-of operator on non-static member address");
1628 const Type *ClassType
1629 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1630 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruth7750f762011-03-29 18:38:10 +00001631 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1632 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1633 UO_AddrOf &&
Chandler Carruthffce2452011-03-29 08:08:18 +00001634 "Non-address-of operator for overloaded function expression");
1635 FromType = S.Context.getPointerType(FromType);
1636 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001637
Douglas Gregor980fb162010-04-29 18:24:40 +00001638 // Check that we've computed the proper type after overload resolution.
Richard Smith9095e5b2016-11-01 01:31:23 +00001639 // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't
1640 // be calling it from within an NDEBUG block.
Chandler Carruthffce2452011-03-29 08:08:18 +00001641 assert(S.Context.hasSameType(
1642 FromType,
1643 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001644 } else {
1645 return false;
1646 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001647 }
John McCall154a2fd2011-08-30 00:57:29 +00001648 // Lvalue-to-rvalue conversion (C++11 4.1):
1649 // A glvalue (3.10) of a non-function, non-array type T can
1650 // be converted to a prvalue.
1651 bool argIsLValue = From->isGLValue();
John McCall086a4642010-11-24 05:12:34 +00001652 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001653 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001654 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001655 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001656
Douglas Gregorc79862f2012-04-12 17:51:55 +00001657 // C11 6.3.2.1p2:
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00001658 // ... if the lvalue has atomic type, the value has the non-atomic version
Douglas Gregorc79862f2012-04-12 17:51:55 +00001659 // of the type of the lvalue ...
1660 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1661 FromType = Atomic->getValueType();
1662
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001663 // If T is a non-class type, the type of the rvalue is the
1664 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001665 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1666 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001667 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001668 } else if (FromType->isArrayType()) {
1669 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001670 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001671
1672 // An lvalue or rvalue of type "array of N T" or "array of unknown
1673 // bound of T" can be converted to an rvalue of type "pointer to
1674 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001675 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001676
John McCall5c32be02010-08-24 20:38:10 +00001677 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00001678 // This conversion is deprecated in C++03 (D.4)
Douglas Gregore489a7d2010-02-28 18:30:25 +00001679 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001680
1681 // For the purpose of ranking in overload resolution
1682 // (13.3.3.1.1), this conversion is considered an
1683 // array-to-pointer conversion followed by a qualification
1684 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001685 SCS.Second = ICK_Identity;
1686 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001687 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001688 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001689 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001690 }
John McCall086a4642010-11-24 05:12:34 +00001691 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001692 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001693 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001694
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001695 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1696 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1697 if (!S.checkAddressOfFunctionIsAvailable(FD))
1698 return false;
1699
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001700 // An lvalue of function type T can be converted to an rvalue of
1701 // type "pointer to T." The result is a pointer to the
1702 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001703 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001704 } else {
1705 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001706 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001707 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001708 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001709
1710 // The second conversion can be an integral promotion, floating
1711 // point promotion, integral conversion, floating point conversion,
1712 // floating-integral conversion, pointer conversion,
1713 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001714 // For overloading in C, this can also be a "compatible-type"
1715 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001716 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001717 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001718 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001719 // The unqualified versions of the types are the same: there's no
1720 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001721 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001722 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001723 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001724 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001725 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001726 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001727 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001728 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001729 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001730 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001731 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001732 SCS.Second = ICK_Complex_Promotion;
1733 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001734 } else if (ToType->isBooleanType() &&
1735 (FromType->isArithmeticType() ||
1736 FromType->isAnyPointerType() ||
1737 FromType->isBlockPointerType() ||
1738 FromType->isMemberPointerType() ||
1739 FromType->isNullPtrType())) {
1740 // Boolean conversions (C++ 4.12).
1741 SCS.Second = ICK_Boolean_Conversion;
1742 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001743 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001744 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001745 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001746 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001747 FromType = ToType.getUnqualifiedType();
Richard Smithb8a98242013-05-10 20:29:50 +00001748 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001749 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001750 SCS.Second = ICK_Complex_Conversion;
1751 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001752 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1753 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001754 // Complex-real conversions (C99 6.3.1.7)
1755 SCS.Second = ICK_Complex_Real;
1756 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001757 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001758 // FIXME: disable conversions between long double and __float128 if
1759 // their representation is different until there is back end support
1760 // We of course allow this conversion if long double is really double.
1761 if (&S.Context.getFloatTypeSemantics(FromType) !=
1762 &S.Context.getFloatTypeSemantics(ToType)) {
1763 bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1764 ToType == S.Context.LongDoubleTy) ||
1765 (FromType == S.Context.LongDoubleTy &&
1766 ToType == S.Context.Float128Ty));
1767 if (Float128AndLongDouble &&
1768 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) !=
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001769 &llvm::APFloat::IEEEdouble()))
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001770 return false;
1771 }
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001772 // Floating point conversions (C++ 4.8).
1773 SCS.Second = ICK_Floating_Conversion;
1774 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001775 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001776 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001777 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001778 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001779 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001780 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001781 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001782 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCall31168b02011-06-15 23:02:42 +00001783 SCS.Second = ICK_Block_Pointer_Conversion;
1784 } else if (AllowObjCWritebackConversion &&
1785 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1786 SCS.Second = ICK_Writeback_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001787 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1788 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001789 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001790 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001791 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregoraec25842011-04-26 23:16:46 +00001792 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001793 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall5c32be02010-08-24 20:38:10 +00001794 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001795 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001796 SCS.Second = ICK_Pointer_Member;
John McCall9b595db2014-02-04 23:58:19 +00001797 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001798 SCS.Second = SecondICK;
1799 FromType = ToType.getUnqualifiedType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001800 } else if (!S.getLangOpts().CPlusPlus &&
John McCall5c32be02010-08-24 20:38:10 +00001801 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001802 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001803 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001804 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001805 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1806 InOverloadResolution,
1807 SCS, CStyle)) {
1808 SCS.Second = ICK_TransparentUnionConversion;
1809 FromType = ToType;
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001810 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1811 CStyle)) {
1812 // tryAtomicConversion has updated the standard conversion sequence
Douglas Gregorc79862f2012-04-12 17:51:55 +00001813 // appropriately.
1814 return true;
George Burgess IV45461812015-10-11 20:13:20 +00001815 } else if (ToType->isEventT() &&
Guy Benyei259f9f42013-02-07 16:05:33 +00001816 From->isIntegerConstantExpr(S.getASTContext()) &&
George Burgess IV45461812015-10-11 20:13:20 +00001817 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
Guy Benyei259f9f42013-02-07 16:05:33 +00001818 SCS.Second = ICK_Zero_Event_Conversion;
1819 FromType = ToType;
Egor Churaev89831422016-12-23 14:55:49 +00001820 } else if (ToType->isQueueT() &&
1821 From->isIntegerConstantExpr(S.getASTContext()) &&
1822 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1823 SCS.Second = ICK_Zero_Queue_Conversion;
1824 FromType = ToType;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001825 } else {
1826 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001827 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001828 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001829 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001830
Richard Smitheb7ef2e2016-10-20 21:53:09 +00001831 // The third conversion can be a function pointer conversion or a
1832 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
John McCall31168b02011-06-15 23:02:42 +00001833 bool ObjCLifetimeConversion;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00001834 if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1835 // Function pointer conversions (removing 'noexcept') including removal of
1836 // 'noreturn' (Clang extension).
1837 SCS.Third = ICK_Function_Conversion;
1838 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1839 ObjCLifetimeConversion)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001840 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001841 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001842 FromType = ToType;
1843 } else {
1844 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001845 SCS.Third = ICK_Identity;
Richard Smith9c37e662016-10-20 17:57:33 +00001846 }
Richard Smitheb7ef2e2016-10-20 21:53:09 +00001847
1848 // C++ [over.best.ics]p6:
1849 // [...] Any difference in top-level cv-qualification is
1850 // subsumed by the initialization itself and does not constitute
1851 // a conversion. [...]
1852 QualType CanonFrom = S.Context.getCanonicalType(FromType);
1853 QualType CanonTo = S.Context.getCanonicalType(ToType);
1854 if (CanonFrom.getLocalUnqualifiedType()
1855 == CanonTo.getLocalUnqualifiedType() &&
1856 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1857 FromType = ToType;
1858 CanonFrom = CanonTo;
1859 }
1860
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001861 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001862
George Burgess IV45461812015-10-11 20:13:20 +00001863 if (CanonFrom == CanonTo)
1864 return true;
1865
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001866 // If we have not converted the argument type to the parameter type,
George Burgess IV45461812015-10-11 20:13:20 +00001867 // this is a bad conversion sequence, unless we're resolving an overload in C.
1868 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001869 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001870
George Burgess IV45461812015-10-11 20:13:20 +00001871 ExprResult ER = ExprResult{From};
George Burgess IV2099b542016-09-02 22:59:57 +00001872 Sema::AssignConvertType Conv =
1873 S.CheckSingleAssignmentConstraints(ToType, ER,
1874 /*Diagnose=*/false,
1875 /*DiagnoseCFAudited=*/false,
1876 /*ConvertRHS=*/false);
George Burgess IV6098fd12016-09-03 00:28:25 +00001877 ImplicitConversionKind SecondConv;
George Burgess IV2099b542016-09-02 22:59:57 +00001878 switch (Conv) {
1879 case Sema::Compatible:
George Burgess IV6098fd12016-09-03 00:28:25 +00001880 SecondConv = ICK_C_Only_Conversion;
George Burgess IV2099b542016-09-02 22:59:57 +00001881 break;
1882 // For our purposes, discarding qualifiers is just as bad as using an
1883 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
1884 // qualifiers, as well.
1885 case Sema::CompatiblePointerDiscardsQualifiers:
1886 case Sema::IncompatiblePointer:
1887 case Sema::IncompatiblePointerSign:
George Burgess IV6098fd12016-09-03 00:28:25 +00001888 SecondConv = ICK_Incompatible_Pointer_Conversion;
George Burgess IV2099b542016-09-02 22:59:57 +00001889 break;
1890 default:
George Burgess IV45461812015-10-11 20:13:20 +00001891 return false;
George Burgess IV2099b542016-09-02 22:59:57 +00001892 }
George Burgess IV45461812015-10-11 20:13:20 +00001893
George Burgess IV6098fd12016-09-03 00:28:25 +00001894 // First can only be an lvalue conversion, so we pretend that this was the
1895 // second conversion. First should already be valid from earlier in the
1896 // function.
1897 SCS.Second = SecondConv;
1898 SCS.setToType(1, ToType);
1899
1900 // Third is Identity, because Second should rank us worse than any other
1901 // conversion. This could also be ICK_Qualification, but it's simpler to just
1902 // lump everything in with the second conversion, and we don't gain anything
1903 // from making this ICK_Qualification.
1904 SCS.Third = ICK_Identity;
1905 SCS.setToType(2, ToType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001906 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001907}
George Burgess IV2099b542016-09-02 22:59:57 +00001908
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001909static bool
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00001910IsTransparentUnionStandardConversion(Sema &S, Expr* From,
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001911 QualType &ToType,
1912 bool InOverloadResolution,
1913 StandardConversionSequence &SCS,
1914 bool CStyle) {
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00001915
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001916 const RecordType *UT = ToType->getAsUnionType();
1917 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1918 return false;
1919 // The field to initialize within the transparent union.
1920 RecordDecl *UD = UT->getDecl();
1921 // It's compatible if the expression matches any of the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001922 for (const auto *it : UD->fields()) {
John McCall31168b02011-06-15 23:02:42 +00001923 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1924 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001925 ToType = it->getType();
1926 return true;
1927 }
1928 }
1929 return false;
1930}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001931
1932/// IsIntegralPromotion - Determines whether the conversion from the
1933/// expression From (whose potentially-adjusted type is FromType) to
1934/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1935/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001936bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001937 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001938 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001939 if (!To) {
1940 return false;
1941 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001942
1943 // An rvalue of type char, signed char, unsigned char, short int, or
1944 // unsigned short int can be converted to an rvalue of type int if
1945 // int can represent all the values of the source type; otherwise,
1946 // the source rvalue can be converted to an rvalue of type unsigned
1947 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001948 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1949 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001950 if (// We can promote any signed, promotable integer type to an int
1951 (FromType->isSignedIntegerType() ||
1952 // We can promote any unsigned integer type whose size is
1953 // less than int to an int.
Benjamin Kramer5ff67472016-04-11 08:26:13 +00001954 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001955 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001956 }
1957
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001958 return To->getKind() == BuiltinType::UInt;
1959 }
1960
Richard Smithb9c5a602012-09-13 21:18:54 +00001961 // C++11 [conv.prom]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001962 // A prvalue of an unscoped enumeration type whose underlying type is not
1963 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1964 // following types that can represent all the values of the enumeration
1965 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1966 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001967 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001968 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001969 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001970 // with lowest integer conversion rank (4.13) greater than the rank of long
1971 // long in which all the values of the enumeration can be represented. If
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001972 // there are two such extended types, the signed one is chosen.
Richard Smithb9c5a602012-09-13 21:18:54 +00001973 // C++11 [conv.prom]p4:
1974 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1975 // can be converted to a prvalue of its underlying type. Moreover, if
1976 // integral promotion can be applied to its underlying type, a prvalue of an
1977 // unscoped enumeration type whose underlying type is fixed can also be
1978 // converted to a prvalue of the promoted underlying type.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001979 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1980 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1981 // provided for a scoped enumeration.
1982 if (FromEnumType->getDecl()->isScoped())
1983 return false;
1984
Richard Smithb9c5a602012-09-13 21:18:54 +00001985 // We can perform an integral promotion to the underlying type of the enum,
Richard Smithac8c1752015-03-28 00:31:40 +00001986 // even if that's not the promoted type. Note that the check for promoting
1987 // the underlying type is based on the type alone, and does not consider
1988 // the bitfield-ness of the actual source expression.
Richard Smithb9c5a602012-09-13 21:18:54 +00001989 if (FromEnumType->getDecl()->isFixed()) {
1990 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1991 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
Richard Smithac8c1752015-03-28 00:31:40 +00001992 IsIntegralPromotion(nullptr, Underlying, ToType);
Richard Smithb9c5a602012-09-13 21:18:54 +00001993 }
1994
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001995 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001996 if (ToType->isIntegerType() &&
Richard Smithdb0ac552015-12-18 22:40:25 +00001997 isCompleteType(From->getLocStart(), FromType))
Richard Smith88f4bba2015-03-26 00:16:07 +00001998 return Context.hasSameUnqualifiedType(
1999 ToType, FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00002000 }
John McCall56774992009-12-09 09:09:27 +00002001
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00002002 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002003 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2004 // to an rvalue a prvalue of the first of the following types that can
2005 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00002006 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002007 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00002008 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002009 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00002010 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002011 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00002012 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002013 // Determine whether the type we're converting from is signed or
2014 // unsigned.
David Majnemerfa01a582011-07-22 21:09:04 +00002015 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002016 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002017
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002018 // The types we'll try to promote to, in the appropriate
2019 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00002020 QualType PromoteTypes[6] = {
2021 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00002022 Context.LongTy, Context.UnsignedLongTy ,
2023 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002024 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00002025 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002026 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2027 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00002028 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002029 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2030 // We found the type that we can promote to. If this is the
2031 // type we wanted, we have a promotion. Otherwise, no
2032 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002033 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002034 }
2035 }
2036 }
2037
2038 // An rvalue for an integral bit-field (9.6) can be converted to an
2039 // rvalue of type int if int can represent all the values of the
2040 // bit-field; otherwise, it can be converted to unsigned int if
2041 // unsigned int can represent all the values of the bit-field. If
2042 // the bit-field is larger yet, no integral promotion applies to
2043 // it. If the bit-field has an enumerated type, it is treated as any
2044 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00002045 // FIXME: We should delay checking of bit-fields until we actually perform the
2046 // conversion.
Richard Smith88f4bba2015-03-26 00:16:07 +00002047 if (From) {
John McCalld25db7e2013-05-06 21:39:12 +00002048 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
Richard Smith88f4bba2015-03-26 00:16:07 +00002049 llvm::APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00002050 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00002051 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
Richard Smith88f4bba2015-03-26 00:16:07 +00002052 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
Douglas Gregor71235ec2009-05-02 02:18:30 +00002053 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00002054
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00002055 // Are we promoting to an int from a bitfield that fits in an int?
2056 if (BitWidth < ToSize ||
2057 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
2058 return To->getKind() == BuiltinType::Int;
2059 }
Mike Stump11289f42009-09-09 15:08:12 +00002060
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00002061 // Are we promoting to an unsigned int from an unsigned bitfield
2062 // that fits into an unsigned int?
2063 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
2064 return To->getKind() == BuiltinType::UInt;
2065 }
Mike Stump11289f42009-09-09 15:08:12 +00002066
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00002067 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002068 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002069 }
Richard Smith88f4bba2015-03-26 00:16:07 +00002070 }
Mike Stump11289f42009-09-09 15:08:12 +00002071
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002072 // An rvalue of type bool can be converted to an rvalue of type int,
2073 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002074 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002075 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002076 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002077
2078 return false;
2079}
2080
2081/// IsFloatingPointPromotion - Determines whether the conversion from
2082/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2083/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00002084bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00002085 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2086 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002087 /// An rvalue of type float can be converted to an rvalue of type
2088 /// double. (C++ 4.6p1).
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002089 if (FromBuiltin->getKind() == BuiltinType::Float &&
2090 ToBuiltin->getKind() == BuiltinType::Double)
2091 return true;
2092
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002093 // C99 6.3.1.5p1:
2094 // When a float is promoted to double or long double, or a
2095 // double is promoted to long double [...].
David Blaikiebbafb8a2012-03-11 07:00:24 +00002096 if (!getLangOpts().CPlusPlus &&
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002097 (FromBuiltin->getKind() == BuiltinType::Float ||
2098 FromBuiltin->getKind() == BuiltinType::Double) &&
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002099 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2100 ToBuiltin->getKind() == BuiltinType::Float128))
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002101 return true;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002102
2103 // Half can be promoted to float.
Joey Goulydd7f4562013-01-23 11:56:20 +00002104 if (!getLangOpts().NativeHalfType &&
2105 FromBuiltin->getKind() == BuiltinType::Half &&
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002106 ToBuiltin->getKind() == BuiltinType::Float)
2107 return true;
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002108 }
2109
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002110 return false;
2111}
2112
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002113/// \brief Determine if a conversion is a complex promotion.
2114///
2115/// A complex promotion is defined as a complex -> complex conversion
2116/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00002117/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002118bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00002119 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002120 if (!FromComplex)
2121 return false;
2122
John McCall9dd450b2009-09-21 23:43:11 +00002123 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002124 if (!ToComplex)
2125 return false;
2126
2127 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00002128 ToComplex->getElementType()) ||
Craig Topperc3ec1492014-05-26 06:22:03 +00002129 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00002130 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002131}
2132
Douglas Gregor237f96c2008-11-26 23:31:11 +00002133/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2134/// the pointer type FromPtr to a pointer to type ToPointee, with the
2135/// same type qualifiers as FromPtr has on its pointee type. ToType,
2136/// if non-empty, will be a pointer to ToType that may or may not have
2137/// the right set of qualifiers on its pointee.
John McCall31168b02011-06-15 23:02:42 +00002138///
Mike Stump11289f42009-09-09 15:08:12 +00002139static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002140BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002141 QualType ToPointee, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002142 ASTContext &Context,
2143 bool StripObjCLifetime = false) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002144 assert((FromPtr->getTypeClass() == Type::Pointer ||
2145 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2146 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002147
John McCall31168b02011-06-15 23:02:42 +00002148 /// Conversions to 'id' subsume cv-qualifier conversions.
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002149 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00002150 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002151
2152 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002153 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00002154 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00002155 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00002156
John McCall31168b02011-06-15 23:02:42 +00002157 if (StripObjCLifetime)
2158 Quals.removeObjCLifetime();
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002159
Mike Stump11289f42009-09-09 15:08:12 +00002160 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002161 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00002162 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00002163 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00002164 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002165
2166 // Build a pointer to ToPointee. It has the right qualifiers
2167 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002168 if (isa<ObjCObjectPointerType>(ToType))
2169 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00002170 return Context.getPointerType(ToPointee);
2171 }
2172
2173 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002174 QualType QualifiedCanonToPointee
2175 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002176
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002177 if (isa<ObjCObjectPointerType>(ToType))
2178 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2179 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002180}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002181
Mike Stump11289f42009-09-09 15:08:12 +00002182static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00002183 bool InOverloadResolution,
2184 ASTContext &Context) {
2185 // Handle value-dependent integral null pointer constants correctly.
2186 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2187 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00002188 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00002189 return !InOverloadResolution;
2190
Douglas Gregor56751b52009-09-25 04:25:58 +00002191 return Expr->isNullPointerConstant(Context,
2192 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2193 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00002194}
Mike Stump11289f42009-09-09 15:08:12 +00002195
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002196/// IsPointerConversion - Determines whether the conversion of the
2197/// expression From, which has the (possibly adjusted) type FromType,
2198/// can be converted to the type ToType via a pointer conversion (C++
2199/// 4.10). If so, returns true and places the converted type (that
2200/// might differ from ToType in its cv-qualifiers at some level) into
2201/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00002202///
Douglas Gregora29dc052008-11-27 01:19:21 +00002203/// This routine also supports conversions to and from block pointers
2204/// and conversions with Objective-C's 'id', 'id<protocols...>', and
2205/// pointers to interfaces. FIXME: Once we've determined the
2206/// appropriate overloading rules for Objective-C, we may want to
2207/// split the Objective-C checks into a different routine; however,
2208/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00002209/// conversions, so for now they live here. IncompatibleObjC will be
2210/// set if the conversion is an allowed Objective-C conversion that
2211/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002212bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00002213 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00002214 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00002215 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00002216 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00002217 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2218 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00002219 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00002220
Mike Stump11289f42009-09-09 15:08:12 +00002221 // Conversion from a null pointer constant to any Objective-C pointer type.
2222 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002223 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00002224 ConvertedType = ToType;
2225 return true;
2226 }
2227
Douglas Gregor231d1c62008-11-27 00:15:41 +00002228 // Blocks: Block pointers can be converted to void*.
2229 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002230 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00002231 ConvertedType = ToType;
2232 return true;
2233 }
2234 // Blocks: A null pointer constant can be converted to a block
2235 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00002236 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002237 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00002238 ConvertedType = ToType;
2239 return true;
2240 }
2241
Sebastian Redl576fd422009-05-10 18:38:11 +00002242 // If the left-hand-side is nullptr_t, the right side can be a null
2243 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00002244 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002245 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00002246 ConvertedType = ToType;
2247 return true;
2248 }
2249
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002250 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002251 if (!ToTypePtr)
2252 return false;
2253
2254 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00002255 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002256 ConvertedType = ToType;
2257 return true;
2258 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002259
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002260 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002261 // , including objective-c pointers.
2262 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00002263 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002264 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002265 ConvertedType = BuildSimilarlyQualifiedPointerType(
2266 FromType->getAs<ObjCObjectPointerType>(),
2267 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002268 ToType, Context);
2269 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002270 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002271 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002272 if (!FromTypePtr)
2273 return false;
2274
2275 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002276
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002277 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-08-18 21:25:30 +00002278 // pointer conversion, so don't do all of the work below.
2279 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2280 return false;
2281
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002282 // An rvalue of type "pointer to cv T," where T is an object type,
2283 // can be converted to an rvalue of type "pointer to cv void" (C++
2284 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00002285 if (FromPointeeType->isIncompleteOrObjectType() &&
2286 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002287 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002288 ToPointeeType,
John McCall31168b02011-06-15 23:02:42 +00002289 ToType, Context,
2290 /*StripObjCLifetime=*/true);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002291 return true;
2292 }
2293
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002294 // MSVC allows implicit function to void* type conversion.
David Majnemer6bf02822015-10-31 08:42:14 +00002295 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002296 ToPointeeType->isVoidType()) {
2297 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2298 ToPointeeType,
2299 ToType, Context);
2300 return true;
2301 }
2302
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002303 // When we're overloading in C, we allow a special kind of pointer
2304 // conversion for compatible-but-not-identical pointee types.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002305 if (!getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002306 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002307 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002308 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00002309 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002310 return true;
2311 }
2312
Douglas Gregor5c407d92008-10-23 00:40:37 +00002313 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002314 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00002315 // An rvalue of type "pointer to cv D," where D is a class type,
2316 // can be converted to an rvalue of type "pointer to cv B," where
2317 // B is a base class (clause 10) of D. If B is an inaccessible
2318 // (clause 11) or ambiguous (10.2) base class of D, a program that
2319 // necessitates this conversion is ill-formed. The result of the
2320 // conversion is a pointer to the base class sub-object of the
2321 // derived class object. The null pointer value is converted to
2322 // the null pointer value of the destination type.
2323 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00002324 // Note that we do not check for ambiguity or inaccessibility
2325 // here. That is handled by CheckPointerConversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002326 if (getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002327 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00002328 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00002329 IsDerivedFrom(From->getLocStart(), FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002330 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002331 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002332 ToType, Context);
2333 return true;
2334 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002335
Fariborz Jahanianbc2ee932011-04-14 20:33:36 +00002336 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2337 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2338 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2339 ToPointeeType,
2340 ToType, Context);
2341 return true;
2342 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002343
Douglas Gregora119f102008-12-19 19:13:09 +00002344 return false;
2345}
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002346
Douglas Gregoraec25842011-04-26 23:16:46 +00002347/// \brief Adopt the given qualifiers for the given type.
2348static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2349 Qualifiers TQs = T.getQualifiers();
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002350
Douglas Gregoraec25842011-04-26 23:16:46 +00002351 // Check whether qualifiers already match.
2352 if (TQs == Qs)
2353 return T;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002354
Douglas Gregoraec25842011-04-26 23:16:46 +00002355 if (Qs.compatiblyIncludes(TQs))
2356 return Context.getQualifiedType(T, Qs);
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002357
Douglas Gregoraec25842011-04-26 23:16:46 +00002358 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2359}
Douglas Gregora119f102008-12-19 19:13:09 +00002360
2361/// isObjCPointerConversion - Determines whether this is an
2362/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2363/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00002364bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00002365 QualType& ConvertedType,
2366 bool &IncompatibleObjC) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002367 if (!getLangOpts().ObjC1)
Douglas Gregora119f102008-12-19 19:13:09 +00002368 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002369
Douglas Gregoraec25842011-04-26 23:16:46 +00002370 // The set of qualifiers on the type we're converting from.
2371 Qualifiers FromQualifiers = FromType.getQualifiers();
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002372
Steve Naroff7cae42b2009-07-10 23:34:53 +00002373 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00002374 const ObjCObjectPointerType* ToObjCPtr =
2375 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00002376 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00002377 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002378
Steve Naroff7cae42b2009-07-10 23:34:53 +00002379 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002380 // If the pointee types are the same (ignoring qualifications),
2381 // then this is not a pointer conversion.
2382 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2383 FromObjCPtr->getPointeeType()))
2384 return false;
2385
Douglas Gregorab209d82015-07-07 03:58:42 +00002386 // Conversion between Objective-C pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00002387 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002388 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2389 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002390 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002391 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2392 FromObjCPtr->getPointeeType()))
2393 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002394 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002395 ToObjCPtr->getPointeeType(),
2396 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002397 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002398 return true;
2399 }
2400
2401 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2402 // Okay: this is some kind of implicit downcast of Objective-C
2403 // interfaces, which is permitted. However, we're going to
2404 // complain about it.
2405 IncompatibleObjC = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002406 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002407 ToObjCPtr->getPointeeType(),
2408 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002409 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002410 return true;
2411 }
Mike Stump11289f42009-09-09 15:08:12 +00002412 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00002413 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00002414 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002415 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002416 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002417 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002418 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002419 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002420 // to a block pointer type.
2421 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002422 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002423 return true;
2424 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002425 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002426 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002427 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002428 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002429 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002430 // pointer to any object.
Douglas Gregoraec25842011-04-26 23:16:46 +00002431 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002432 return true;
2433 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002434 else
Douglas Gregora119f102008-12-19 19:13:09 +00002435 return false;
2436
Douglas Gregor033f56d2008-12-23 00:53:59 +00002437 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002438 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002439 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00002440 else if (const BlockPointerType *FromBlockPtr =
2441 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00002442 FromPointeeType = FromBlockPtr->getPointeeType();
2443 else
Douglas Gregora119f102008-12-19 19:13:09 +00002444 return false;
2445
Douglas Gregora119f102008-12-19 19:13:09 +00002446 // If we have pointers to pointers, recursively check whether this
2447 // is an Objective-C conversion.
2448 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2449 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2450 IncompatibleObjC)) {
2451 // We always complain about this conversion.
2452 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002453 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002454 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002455 return true;
2456 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002457 // Allow conversion of pointee being objective-c pointer to another one;
2458 // as in I* to id.
2459 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2460 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2461 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2462 IncompatibleObjC)) {
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002463
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002464 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002465 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002466 return true;
2467 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002468
Douglas Gregor033f56d2008-12-23 00:53:59 +00002469 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00002470 // differences in the argument and result types are in Objective-C
2471 // pointer conversions. If so, we permit the conversion (but
2472 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00002473 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002474 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002475 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002476 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002477 if (FromFunctionType && ToFunctionType) {
2478 // If the function types are exactly the same, this isn't an
2479 // Objective-C pointer conversion.
2480 if (Context.getCanonicalType(FromPointeeType)
2481 == Context.getCanonicalType(ToPointeeType))
2482 return false;
2483
2484 // Perform the quick checks that will tell us whether these
2485 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002486 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Douglas Gregora119f102008-12-19 19:13:09 +00002487 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2488 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2489 return false;
2490
2491 bool HasObjCConversion = false;
Alp Toker314cc812014-01-25 16:55:45 +00002492 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2493 Context.getCanonicalType(ToFunctionType->getReturnType())) {
Douglas Gregora119f102008-12-19 19:13:09 +00002494 // Okay, the types match exactly. Nothing to do.
Alp Toker314cc812014-01-25 16:55:45 +00002495 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2496 ToFunctionType->getReturnType(),
Douglas Gregora119f102008-12-19 19:13:09 +00002497 ConvertedType, IncompatibleObjC)) {
2498 // Okay, we have an Objective-C pointer conversion.
2499 HasObjCConversion = true;
2500 } else {
2501 // Function types are too different. Abort.
2502 return false;
2503 }
Mike Stump11289f42009-09-09 15:08:12 +00002504
Douglas Gregora119f102008-12-19 19:13:09 +00002505 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002506 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Douglas Gregora119f102008-12-19 19:13:09 +00002507 ArgIdx != NumArgs; ++ArgIdx) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002508 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2509 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Douglas Gregora119f102008-12-19 19:13:09 +00002510 if (Context.getCanonicalType(FromArgType)
2511 == Context.getCanonicalType(ToArgType)) {
2512 // Okay, the types match exactly. Nothing to do.
2513 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2514 ConvertedType, IncompatibleObjC)) {
2515 // Okay, we have an Objective-C pointer conversion.
2516 HasObjCConversion = true;
2517 } else {
2518 // Argument types are too different. Abort.
2519 return false;
2520 }
2521 }
2522
2523 if (HasObjCConversion) {
2524 // We had an Objective-C conversion. Allow this pointer
2525 // conversion, but complain about it.
Douglas Gregoraec25842011-04-26 23:16:46 +00002526 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002527 IncompatibleObjC = true;
2528 return true;
2529 }
2530 }
2531
Sebastian Redl72b597d2009-01-25 19:43:20 +00002532 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002533}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002534
John McCall31168b02011-06-15 23:02:42 +00002535/// \brief Determine whether this is an Objective-C writeback conversion,
2536/// used for parameter passing when performing automatic reference counting.
2537///
2538/// \param FromType The type we're converting form.
2539///
2540/// \param ToType The type we're converting to.
2541///
2542/// \param ConvertedType The type that will be produced after applying
2543/// this conversion.
2544bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2545 QualType &ConvertedType) {
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002546 if (!getLangOpts().ObjCAutoRefCount ||
John McCall31168b02011-06-15 23:02:42 +00002547 Context.hasSameUnqualifiedType(FromType, ToType))
2548 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002549
John McCall31168b02011-06-15 23:02:42 +00002550 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2551 QualType ToPointee;
2552 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2553 ToPointee = ToPointer->getPointeeType();
2554 else
2555 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002556
John McCall31168b02011-06-15 23:02:42 +00002557 Qualifiers ToQuals = ToPointee.getQualifiers();
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002558 if (!ToPointee->isObjCLifetimeType() ||
John McCall31168b02011-06-15 23:02:42 +00002559 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall18ce25e2012-02-08 00:46:36 +00002560 !ToQuals.withoutObjCLifetime().empty())
John McCall31168b02011-06-15 23:02:42 +00002561 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002562
John McCall31168b02011-06-15 23:02:42 +00002563 // Argument must be a pointer to __strong to __weak.
2564 QualType FromPointee;
2565 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2566 FromPointee = FromPointer->getPointeeType();
2567 else
2568 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002569
John McCall31168b02011-06-15 23:02:42 +00002570 Qualifiers FromQuals = FromPointee.getQualifiers();
2571 if (!FromPointee->isObjCLifetimeType() ||
2572 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2573 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2574 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002575
John McCall31168b02011-06-15 23:02:42 +00002576 // Make sure that we have compatible qualifiers.
2577 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2578 if (!ToQuals.compatiblyIncludes(FromQuals))
2579 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002580
John McCall31168b02011-06-15 23:02:42 +00002581 // Remove qualifiers from the pointee type we're converting from; they
2582 // aren't used in the compatibility check belong, and we'll be adding back
2583 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2584 FromPointee = FromPointee.getUnqualifiedType();
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002585
John McCall31168b02011-06-15 23:02:42 +00002586 // The unqualified form of the pointee types must be compatible.
2587 ToPointee = ToPointee.getUnqualifiedType();
2588 bool IncompatibleObjC;
2589 if (Context.typesAreCompatible(FromPointee, ToPointee))
2590 FromPointee = ToPointee;
2591 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2592 IncompatibleObjC))
2593 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002594
John McCall31168b02011-06-15 23:02:42 +00002595 /// \brief Construct the type we're converting to, which is a pointer to
2596 /// __autoreleasing pointee.
2597 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2598 ConvertedType = Context.getPointerType(FromPointee);
2599 return true;
2600}
2601
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002602bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2603 QualType& ConvertedType) {
2604 QualType ToPointeeType;
2605 if (const BlockPointerType *ToBlockPtr =
2606 ToType->getAs<BlockPointerType>())
2607 ToPointeeType = ToBlockPtr->getPointeeType();
2608 else
2609 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002610
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002611 QualType FromPointeeType;
2612 if (const BlockPointerType *FromBlockPtr =
2613 FromType->getAs<BlockPointerType>())
2614 FromPointeeType = FromBlockPtr->getPointeeType();
2615 else
2616 return false;
2617 // We have pointer to blocks, check whether the only
2618 // differences in the argument and result types are in Objective-C
2619 // pointer conversions. If so, we permit the conversion.
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002620
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002621 const FunctionProtoType *FromFunctionType
2622 = FromPointeeType->getAs<FunctionProtoType>();
2623 const FunctionProtoType *ToFunctionType
2624 = ToPointeeType->getAs<FunctionProtoType>();
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002625
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002626 if (!FromFunctionType || !ToFunctionType)
2627 return false;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002628
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002629 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002630 return true;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002631
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002632 // Perform the quick checks that will tell us whether these
2633 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002634 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002635 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2636 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002637
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002638 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2639 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2640 if (FromEInfo != ToEInfo)
2641 return false;
2642
2643 bool IncompatibleObjC = false;
Alp Toker314cc812014-01-25 16:55:45 +00002644 if (Context.hasSameType(FromFunctionType->getReturnType(),
2645 ToFunctionType->getReturnType())) {
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002646 // Okay, the types match exactly. Nothing to do.
2647 } else {
Alp Toker314cc812014-01-25 16:55:45 +00002648 QualType RHS = FromFunctionType->getReturnType();
2649 QualType LHS = ToFunctionType->getReturnType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002650 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002651 !RHS.hasQualifiers() && LHS.hasQualifiers())
2652 LHS = LHS.getUnqualifiedType();
2653
2654 if (Context.hasSameType(RHS,LHS)) {
2655 // OK exact match.
2656 } else if (isObjCPointerConversion(RHS, LHS,
2657 ConvertedType, IncompatibleObjC)) {
2658 if (IncompatibleObjC)
2659 return false;
2660 // Okay, we have an Objective-C pointer conversion.
2661 }
2662 else
2663 return false;
2664 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002665
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002666 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002667 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002668 ArgIdx != NumArgs; ++ArgIdx) {
2669 IncompatibleObjC = false;
Alp Toker9cacbab2014-01-20 20:26:09 +00002670 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2671 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002672 if (Context.hasSameType(FromArgType, ToArgType)) {
2673 // Okay, the types match exactly. Nothing to do.
2674 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2675 ConvertedType, IncompatibleObjC)) {
2676 if (IncompatibleObjC)
2677 return false;
2678 // Okay, we have an Objective-C pointer conversion.
2679 } else
2680 // Argument types are too different. Abort.
2681 return false;
2682 }
Akira Hatanakae9744792017-09-20 06:32:45 +00002683
2684 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
2685 bool CanUseToFPT, CanUseFromFPT;
2686 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
2687 CanUseToFPT, CanUseFromFPT,
2688 NewParamInfos))
Fariborz Jahanian97676972011-09-28 21:52:05 +00002689 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00002690
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002691 ConvertedType = ToType;
2692 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002693}
2694
Richard Trieucaff2472011-11-23 22:32:32 +00002695enum {
2696 ft_default,
2697 ft_different_class,
2698 ft_parameter_arity,
2699 ft_parameter_mismatch,
2700 ft_return_type,
Richard Smith3c4f8d22016-10-16 17:54:23 +00002701 ft_qualifer_mismatch,
2702 ft_noexcept
Richard Trieucaff2472011-11-23 22:32:32 +00002703};
2704
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002705/// Attempts to get the FunctionProtoType from a Type. Handles
2706/// MemberFunctionPointers properly.
2707static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2708 if (auto *FPT = FromType->getAs<FunctionProtoType>())
2709 return FPT;
2710
2711 if (auto *MPT = FromType->getAs<MemberPointerType>())
2712 return MPT->getPointeeType()->getAs<FunctionProtoType>();
2713
2714 return nullptr;
2715}
2716
Richard Trieucaff2472011-11-23 22:32:32 +00002717/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2718/// function types. Catches different number of parameter, mismatch in
2719/// parameter types, and different return types.
2720void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2721 QualType FromType, QualType ToType) {
Richard Trieu96ed5b62011-12-13 23:19:45 +00002722 // If either type is not valid, include no extra info.
2723 if (FromType.isNull() || ToType.isNull()) {
2724 PDiag << ft_default;
2725 return;
2726 }
2727
Richard Trieucaff2472011-11-23 22:32:32 +00002728 // Get the function type from the pointers.
2729 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2730 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2731 *ToMember = ToType->getAs<MemberPointerType>();
Richard Trieu9098c9f2014-05-22 01:39:16 +00002732 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
Richard Trieucaff2472011-11-23 22:32:32 +00002733 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2734 << QualType(FromMember->getClass(), 0);
2735 return;
2736 }
2737 FromType = FromMember->getPointeeType();
2738 ToType = ToMember->getPointeeType();
Richard Trieucaff2472011-11-23 22:32:32 +00002739 }
2740
Richard Trieu96ed5b62011-12-13 23:19:45 +00002741 if (FromType->isPointerType())
2742 FromType = FromType->getPointeeType();
2743 if (ToType->isPointerType())
2744 ToType = ToType->getPointeeType();
2745
2746 // Remove references.
Richard Trieucaff2472011-11-23 22:32:32 +00002747 FromType = FromType.getNonReferenceType();
2748 ToType = ToType.getNonReferenceType();
2749
Richard Trieucaff2472011-11-23 22:32:32 +00002750 // Don't print extra info for non-specialized template functions.
2751 if (FromType->isInstantiationDependentType() &&
2752 !FromType->getAs<TemplateSpecializationType>()) {
2753 PDiag << ft_default;
2754 return;
2755 }
2756
Richard Trieu96ed5b62011-12-13 23:19:45 +00002757 // No extra info for same types.
2758 if (Context.hasSameType(FromType, ToType)) {
2759 PDiag << ft_default;
2760 return;
2761 }
2762
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002763 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2764 *ToFunction = tryGetFunctionProtoType(ToType);
Richard Trieucaff2472011-11-23 22:32:32 +00002765
2766 // Both types need to be function types.
2767 if (!FromFunction || !ToFunction) {
2768 PDiag << ft_default;
2769 return;
2770 }
2771
Alp Toker9cacbab2014-01-20 20:26:09 +00002772 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2773 PDiag << ft_parameter_arity << ToFunction->getNumParams()
2774 << FromFunction->getNumParams();
Richard Trieucaff2472011-11-23 22:32:32 +00002775 return;
2776 }
2777
2778 // Handle different parameter types.
2779 unsigned ArgPos;
Alp Toker9cacbab2014-01-20 20:26:09 +00002780 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
Richard Trieucaff2472011-11-23 22:32:32 +00002781 PDiag << ft_parameter_mismatch << ArgPos + 1
Alp Toker9cacbab2014-01-20 20:26:09 +00002782 << ToFunction->getParamType(ArgPos)
2783 << FromFunction->getParamType(ArgPos);
Richard Trieucaff2472011-11-23 22:32:32 +00002784 return;
2785 }
2786
2787 // Handle different return type.
Alp Toker314cc812014-01-25 16:55:45 +00002788 if (!Context.hasSameType(FromFunction->getReturnType(),
2789 ToFunction->getReturnType())) {
2790 PDiag << ft_return_type << ToFunction->getReturnType()
2791 << FromFunction->getReturnType();
Richard Trieucaff2472011-11-23 22:32:32 +00002792 return;
2793 }
2794
2795 unsigned FromQuals = FromFunction->getTypeQuals(),
2796 ToQuals = ToFunction->getTypeQuals();
2797 if (FromQuals != ToQuals) {
2798 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2799 return;
2800 }
2801
Richard Smith3c4f8d22016-10-16 17:54:23 +00002802 // Handle exception specification differences on canonical type (in C++17
2803 // onwards).
2804 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2805 ->isNothrow(Context) !=
2806 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2807 ->isNothrow(Context)) {
2808 PDiag << ft_noexcept;
2809 return;
2810 }
2811
Richard Trieucaff2472011-11-23 22:32:32 +00002812 // Unable to find a difference, so add no extra info.
2813 PDiag << ft_default;
2814}
2815
Alp Toker9cacbab2014-01-20 20:26:09 +00002816/// FunctionParamTypesAreEqual - This routine checks two function proto types
Douglas Gregor2039ca02011-12-15 17:15:07 +00002817/// for equality of their argument types. Caller has already checked that
Eli Friedman5f508952013-06-18 22:41:37 +00002818/// they have same number of arguments. If the parameters are different,
2819/// ArgPos will have the parameter index of the first different parameter.
Alp Toker9cacbab2014-01-20 20:26:09 +00002820bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2821 const FunctionProtoType *NewType,
2822 unsigned *ArgPos) {
2823 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2824 N = NewType->param_type_begin(),
2825 E = OldType->param_type_end();
2826 O && (O != E); ++O, ++N) {
Richard Trieu4b03d982013-08-09 21:42:32 +00002827 if (!Context.hasSameType(O->getUnqualifiedType(),
2828 N->getUnqualifiedType())) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002829 if (ArgPos)
2830 *ArgPos = O - OldType->param_type_begin();
Larisse Voufo4154f462013-08-06 03:57:41 +00002831 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002832 }
2833 }
2834 return true;
2835}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002836
Douglas Gregor39c16d42008-10-24 04:54:22 +00002837/// CheckPointerConversion - Check the pointer conversion from the
2838/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00002839/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00002840/// conversions for which IsPointerConversion has already returned
2841/// true. It returns true and produces a diagnostic if there was an
2842/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002843bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002844 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002845 CXXCastPath& BasePath,
George Burgess IV60bc9722016-01-13 23:36:34 +00002846 bool IgnoreBaseAccess,
2847 bool Diagnose) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002848 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00002849 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002850
John McCall8cb679e2010-11-15 09:13:47 +00002851 Kind = CK_BitCast;
2852
George Burgess IV60bc9722016-01-13 23:36:34 +00002853 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
Argyrios Kyrtzidis3e3305d2014-02-02 05:26:43 +00002854 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
George Burgess IV60bc9722016-01-13 23:36:34 +00002855 Expr::NPCK_ZeroExpression) {
David Blaikie1c7c8f72012-08-08 17:33:31 +00002856 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2857 DiagRuntimeBehavior(From->getExprLoc(), From,
2858 PDiag(diag::warn_impcast_bool_to_null_pointer)
2859 << ToType << From->getSourceRange());
2860 else if (!isUnevaluatedContext())
2861 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2862 << ToType << From->getSourceRange();
2863 }
John McCall9320b872011-09-09 05:25:32 +00002864 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2865 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002866 QualType FromPointeeType = FromPtrType->getPointeeType(),
2867 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00002868
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002869 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2870 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002871 // We must have a derived-to-base conversion. Check an
2872 // ambiguous or inaccessible conversion.
George Burgess IV60bc9722016-01-13 23:36:34 +00002873 unsigned InaccessibleID = 0;
2874 unsigned AmbigiousID = 0;
2875 if (Diagnose) {
2876 InaccessibleID = diag::err_upcast_to_inaccessible_base;
2877 AmbigiousID = diag::err_ambiguous_derived_to_base_conv;
2878 }
2879 if (CheckDerivedToBaseConversion(
2880 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID,
2881 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
2882 &BasePath, IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002883 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002884
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002885 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00002886 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002887 }
David Majnemer6bf02822015-10-31 08:42:14 +00002888
George Burgess IV60bc9722016-01-13 23:36:34 +00002889 if (Diagnose && !IsCStyleOrFunctionalCast &&
2890 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
David Majnemer6bf02822015-10-31 08:42:14 +00002891 assert(getLangOpts().MSVCCompat &&
2892 "this should only be possible with MSVCCompat!");
2893 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
2894 << From->getSourceRange();
2895 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00002896 }
John McCall9320b872011-09-09 05:25:32 +00002897 } else if (const ObjCObjectPointerType *ToPtrType =
2898 ToType->getAs<ObjCObjectPointerType>()) {
2899 if (const ObjCObjectPointerType *FromPtrType =
2900 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002901 // Objective-C++ conversions are always okay.
2902 // FIXME: We should have a different class of conversions for the
2903 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00002904 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002905 return false;
John McCall9320b872011-09-09 05:25:32 +00002906 } else if (FromType->isBlockPointerType()) {
2907 Kind = CK_BlockPointerToObjCPointerCast;
2908 } else {
2909 Kind = CK_CPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00002910 }
John McCall9320b872011-09-09 05:25:32 +00002911 } else if (ToType->isBlockPointerType()) {
2912 if (!FromType->isBlockPointerType())
2913 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002914 }
John McCall8cb679e2010-11-15 09:13:47 +00002915
2916 // We shouldn't fall into this case unless it's valid for other
2917 // reasons.
2918 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2919 Kind = CK_NullToPointer;
2920
Douglas Gregor39c16d42008-10-24 04:54:22 +00002921 return false;
2922}
2923
Sebastian Redl72b597d2009-01-25 19:43:20 +00002924/// IsMemberPointerConversion - Determines whether the conversion of the
2925/// expression From, which has the (possibly adjusted) type FromType, can be
2926/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2927/// If so, returns true and places the converted type (that might differ from
2928/// ToType in its cv-qualifiers at some level) into ConvertedType.
2929bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002930 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00002931 bool InOverloadResolution,
2932 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002933 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002934 if (!ToTypePtr)
2935 return false;
2936
2937 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00002938 if (From->isNullPointerConstant(Context,
2939 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2940 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002941 ConvertedType = ToType;
2942 return true;
2943 }
2944
2945 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002946 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002947 if (!FromTypePtr)
2948 return false;
2949
2950 // A pointer to member of B can be converted to a pointer to member of D,
2951 // where D is derived from B (C++ 4.11p2).
2952 QualType FromClass(FromTypePtr->getClass(), 0);
2953 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002954
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002955 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00002956 IsDerivedFrom(From->getLocStart(), ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002957 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2958 ToClass.getTypePtr());
2959 return true;
2960 }
2961
2962 return false;
2963}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002964
Sebastian Redl72b597d2009-01-25 19:43:20 +00002965/// CheckMemberPointerConversion - Check the member pointer conversion from the
2966/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002967/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002968/// for which IsMemberPointerConversion has already returned true. It returns
2969/// true and produces a diagnostic if there was an error, or returns false
2970/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002971bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002972 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002973 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002974 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002975 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002976 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00002977 if (!FromPtrType) {
2978 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002979 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00002980 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00002981 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00002982 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00002983 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00002984 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00002985
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002986 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00002987 assert(ToPtrType && "No member pointer cast has a target type "
2988 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002989
Sebastian Redled8f2002009-01-28 18:33:18 +00002990 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2991 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002992
Sebastian Redled8f2002009-01-28 18:33:18 +00002993 // FIXME: What about dependent types?
2994 assert(FromClass->isRecordType() && "Pointer into non-class.");
2995 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002996
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002997 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002998 /*DetectVirtual=*/true);
Richard Smith0f59cb32015-12-18 21:45:41 +00002999 bool DerivationOkay =
3000 IsDerivedFrom(From->getLocStart(), ToClass, FromClass, Paths);
Sebastian Redled8f2002009-01-28 18:33:18 +00003001 assert(DerivationOkay &&
3002 "Should not have been called if derivation isn't OK.");
3003 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00003004
Sebastian Redled8f2002009-01-28 18:33:18 +00003005 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3006 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00003007 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3008 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3009 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3010 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00003011 }
Sebastian Redled8f2002009-01-28 18:33:18 +00003012
Douglas Gregor89ee6822009-02-28 01:32:25 +00003013 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00003014 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3015 << FromClass << ToClass << QualType(VBase, 0)
3016 << From->getSourceRange();
3017 return true;
3018 }
3019
John McCall5b0829a2010-02-10 09:31:12 +00003020 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00003021 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3022 Paths.front(),
3023 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00003024
Anders Carlssond7923c62009-08-22 23:33:40 +00003025 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00003026 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00003027 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00003028 return false;
3029}
3030
Douglas Gregorc9f019a2013-11-08 02:04:24 +00003031/// Determine whether the lifetime conversion between the two given
3032/// qualifiers sets is nontrivial.
3033static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3034 Qualifiers ToQuals) {
3035 // Converting anything to const __unsafe_unretained is trivial.
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003036 if (ToQuals.hasConst() &&
Douglas Gregorc9f019a2013-11-08 02:04:24 +00003037 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3038 return false;
3039
3040 return true;
3041}
3042
Douglas Gregor9a657932008-10-21 23:43:52 +00003043/// IsQualificationConversion - Determines whether the conversion from
3044/// an rvalue of type FromType to ToType is a qualification conversion
3045/// (C++ 4.4).
John McCall31168b02011-06-15 23:02:42 +00003046///
3047/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3048/// when the qualification conversion involves a change in the Objective-C
3049/// object lifetime.
Mike Stump11289f42009-09-09 15:08:12 +00003050bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003051Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00003052 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor9a657932008-10-21 23:43:52 +00003053 FromType = Context.getCanonicalType(FromType);
3054 ToType = Context.getCanonicalType(ToType);
John McCall31168b02011-06-15 23:02:42 +00003055 ObjCLifetimeConversion = false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003056
Douglas Gregor9a657932008-10-21 23:43:52 +00003057 // If FromType and ToType are the same type, this is not a
3058 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00003059 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00003060 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00003061
Douglas Gregor9a657932008-10-21 23:43:52 +00003062 // (C++ 4.4p4):
3063 // A conversion can add cv-qualifiers at levels other than the first
3064 // in multi-level pointers, subject to the following rules: [...]
3065 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00003066 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003067 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00003068 // Within each iteration of the loop, we check the qualifiers to
3069 // determine if this still looks like a qualification
3070 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003071 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00003072 // until there are no more pointers or pointers-to-members left to
3073 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003074 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00003075
Douglas Gregor90609aa2011-04-25 18:40:17 +00003076 Qualifiers FromQuals = FromType.getQualifiers();
3077 Qualifiers ToQuals = ToType.getQualifiers();
Andrey Bokhanko45d41322016-05-11 18:38:21 +00003078
3079 // Ignore __unaligned qualifier if this type is void.
3080 if (ToType.getUnqualifiedType()->isVoidType())
3081 FromQuals.removeUnaligned();
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003082
John McCall31168b02011-06-15 23:02:42 +00003083 // Objective-C ARC:
3084 // Check Objective-C lifetime conversions.
3085 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
3086 UnwrappedAnyPointer) {
3087 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00003088 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3089 ObjCLifetimeConversion = true;
John McCall31168b02011-06-15 23:02:42 +00003090 FromQuals.removeObjCLifetime();
3091 ToQuals.removeObjCLifetime();
3092 } else {
3093 // Qualification conversions cannot cast between different
3094 // Objective-C lifetime qualifiers.
3095 return false;
3096 }
3097 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003098
Douglas Gregorf30053d2011-05-08 06:09:53 +00003099 // Allow addition/removal of GC attributes but not changing GC attributes.
3100 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3101 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3102 FromQuals.removeObjCGCAttr();
3103 ToQuals.removeObjCGCAttr();
3104 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003105
Douglas Gregor9a657932008-10-21 23:43:52 +00003106 // -- for every j > 0, if const is in cv 1,j then const is in cv
3107 // 2,j, and similarly for volatile.
Douglas Gregor90609aa2011-04-25 18:40:17 +00003108 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor9a657932008-10-21 23:43:52 +00003109 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003110
Douglas Gregor9a657932008-10-21 23:43:52 +00003111 // -- if the cv 1,j and cv 2,j are different, then const is in
3112 // every cv for 0 < k < j.
Douglas Gregor90609aa2011-04-25 18:40:17 +00003113 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003114 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00003115 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003116
Douglas Gregor9a657932008-10-21 23:43:52 +00003117 // Keep track of whether all prior cv-qualifiers in the "to" type
3118 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00003119 PreviousToQualsIncludeConst
Douglas Gregor90609aa2011-04-25 18:40:17 +00003120 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003121 }
Douglas Gregor9a657932008-10-21 23:43:52 +00003122
3123 // We are left with FromType and ToType being the pointee types
3124 // after unwrapping the original FromType and ToType the same number
3125 // of types. If we unwrapped any pointers, and if FromType and
3126 // ToType have the same unqualified type (since we checked
3127 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003128 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00003129}
3130
Douglas Gregorc79862f2012-04-12 17:51:55 +00003131/// \brief - Determine whether this is a conversion from a scalar type to an
3132/// atomic type.
3133///
3134/// If successful, updates \c SCS's second and third steps in the conversion
3135/// sequence to finish the conversion.
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00003136static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3137 bool InOverloadResolution,
3138 StandardConversionSequence &SCS,
3139 bool CStyle) {
Douglas Gregorc79862f2012-04-12 17:51:55 +00003140 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3141 if (!ToAtomic)
3142 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003143
Douglas Gregorc79862f2012-04-12 17:51:55 +00003144 StandardConversionSequence InnerSCS;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003145 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
Douglas Gregorc79862f2012-04-12 17:51:55 +00003146 InOverloadResolution, InnerSCS,
3147 CStyle, /*AllowObjCWritebackConversion=*/false))
3148 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003149
Douglas Gregorc79862f2012-04-12 17:51:55 +00003150 SCS.Second = InnerSCS.Second;
3151 SCS.setToType(1, InnerSCS.getToType(1));
3152 SCS.Third = InnerSCS.Third;
3153 SCS.QualificationIncludesObjCLifetime
3154 = InnerSCS.QualificationIncludesObjCLifetime;
3155 SCS.setToType(2, InnerSCS.getToType(2));
3156 return true;
3157}
3158
Sebastian Redle5417162012-03-27 18:33:03 +00003159static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3160 CXXConstructorDecl *Constructor,
3161 QualType Type) {
3162 const FunctionProtoType *CtorType =
3163 Constructor->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00003164 if (CtorType->getNumParams() > 0) {
3165 QualType FirstArg = CtorType->getParamType(0);
Sebastian Redle5417162012-03-27 18:33:03 +00003166 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3167 return true;
3168 }
3169 return false;
3170}
3171
Sebastian Redl82ace982012-02-11 23:51:08 +00003172static OverloadingResult
3173IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3174 CXXRecordDecl *To,
3175 UserDefinedConversionSequence &User,
3176 OverloadCandidateSet &CandidateSet,
3177 bool AllowExplicit) {
Richard Smithc2bebe92016-05-11 20:37:46 +00003178 for (auto *D : S.LookupConstructors(To)) {
3179 auto Info = getConstructorInfo(D);
Richard Smith5179eb72016-06-28 19:03:57 +00003180 if (!Info)
Richard Smithc2bebe92016-05-11 20:37:46 +00003181 continue;
Sebastian Redl82ace982012-02-11 23:51:08 +00003182
Richard Smithc2bebe92016-05-11 20:37:46 +00003183 bool Usable = !Info.Constructor->isInvalidDecl() &&
3184 S.isInitListConstructor(Info.Constructor) &&
3185 (AllowExplicit || !Info.Constructor->isExplicit());
Sebastian Redl82ace982012-02-11 23:51:08 +00003186 if (Usable) {
Sebastian Redle5417162012-03-27 18:33:03 +00003187 // If the first argument is (a reference to) the target type,
3188 // suppress conversions.
Richard Smithc2bebe92016-05-11 20:37:46 +00003189 bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3190 S.Context, Info.Constructor, ToType);
3191 if (Info.ConstructorTmpl)
3192 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3193 /*ExplicitArgs*/ nullptr, From,
3194 CandidateSet, SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00003195 else
Richard Smithc2bebe92016-05-11 20:37:46 +00003196 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3197 CandidateSet, SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00003198 }
3199 }
3200
3201 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3202
3203 OverloadCandidateSet::iterator Best;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003204 switch (auto Result =
3205 CandidateSet.BestViableFunction(S, From->getLocStart(),
Fariborz Jahaniandcf06f42015-04-14 17:21:58 +00003206 Best, true)) {
3207 case OR_Deleted:
Sebastian Redl82ace982012-02-11 23:51:08 +00003208 case OR_Success: {
3209 // Record the standard conversion we used and the conversion function.
3210 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Sebastian Redl82ace982012-02-11 23:51:08 +00003211 QualType ThisType = Constructor->getThisType(S.Context);
3212 // Initializer lists don't have conversions as such.
3213 User.Before.setAsIdentityConversion();
3214 User.HadMultipleCandidates = HadMultipleCandidates;
3215 User.ConversionFunction = Constructor;
3216 User.FoundConversionFunction = Best->FoundDecl;
3217 User.After.setAsIdentityConversion();
3218 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3219 User.After.setAllToTypes(ToType);
Fariborz Jahaniandcf06f42015-04-14 17:21:58 +00003220 return Result;
Sebastian Redl82ace982012-02-11 23:51:08 +00003221 }
3222
3223 case OR_No_Viable_Function:
3224 return OR_No_Viable_Function;
Sebastian Redl82ace982012-02-11 23:51:08 +00003225 case OR_Ambiguous:
3226 return OR_Ambiguous;
3227 }
3228
3229 llvm_unreachable("Invalid OverloadResult!");
3230}
3231
Douglas Gregor576e98c2009-01-30 23:27:23 +00003232/// Determines whether there is a user-defined conversion sequence
3233/// (C++ [over.ics.user]) that converts expression From to the type
3234/// ToType. If such a conversion exists, User will contain the
3235/// user-defined conversion sequence that performs such a conversion
3236/// and this routine will return true. Otherwise, this routine returns
3237/// false and User is unspecified.
3238///
Douglas Gregor576e98c2009-01-30 23:27:23 +00003239/// \param AllowExplicit true if the conversion should consider C++0x
3240/// "explicit" conversion functions as well as non-explicit conversion
3241/// functions (C++0x [class.conv.fct]p2).
Douglas Gregor4b60a152013-11-07 22:34:54 +00003242///
3243/// \param AllowObjCConversionOnExplicit true if the conversion should
3244/// allow an extra Objective-C pointer conversion on uses of explicit
3245/// constructors. Requires \c AllowExplicit to also be set.
John McCall5c32be02010-08-24 20:38:10 +00003246static OverloadingResult
3247IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl82ace982012-02-11 23:51:08 +00003248 UserDefinedConversionSequence &User,
3249 OverloadCandidateSet &CandidateSet,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003250 bool AllowExplicit,
3251 bool AllowObjCConversionOnExplicit) {
Douglas Gregor2ee1d992013-11-08 01:20:25 +00003252 assert(AllowExplicit || !AllowObjCConversionOnExplicit);
Douglas Gregor4b60a152013-11-07 22:34:54 +00003253
Douglas Gregor5ab11652010-04-17 22:01:05 +00003254 // Whether we will only visit constructors.
3255 bool ConstructorsOnly = false;
3256
3257 // If the type we are conversion to is a class type, enumerate its
3258 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003259 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00003260 // C++ [over.match.ctor]p1:
3261 // When objects of class type are direct-initialized (8.5), or
3262 // copy-initialized from an expression of the same or a
3263 // derived class type (8.5), overload resolution selects the
3264 // constructor. [...] For copy-initialization, the candidate
3265 // functions are all the converting constructors (12.3.1) of
3266 // that class. The argument list is the expression-list within
3267 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00003268 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00003269 (From->getType()->getAs<RecordType>() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00003270 S.IsDerivedFrom(From->getLocStart(), From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00003271 ConstructorsOnly = true;
3272
Richard Smithdb0ac552015-12-18 22:40:25 +00003273 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003274 // We're not going to find any constructors.
3275 } else if (CXXRecordDecl *ToRecordDecl
3276 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003277
3278 Expr **Args = &From;
3279 unsigned NumArgs = 1;
3280 bool ListInitializing = false;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003281 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003282 // But first, see if there is an init-list-constructor that will work.
Sebastian Redl82ace982012-02-11 23:51:08 +00003283 OverloadingResult Result = IsInitializerListConstructorConversion(
3284 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3285 if (Result != OR_No_Viable_Function)
3286 return Result;
3287 // Never mind.
3288 CandidateSet.clear();
3289
3290 // If we're list-initializing, we pass the individual elements as
3291 // arguments, not the entire list.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003292 Args = InitList->getInits();
3293 NumArgs = InitList->getNumInits();
3294 ListInitializing = true;
3295 }
3296
Richard Smithc2bebe92016-05-11 20:37:46 +00003297 for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3298 auto Info = getConstructorInfo(D);
Richard Smith5179eb72016-06-28 19:03:57 +00003299 if (!Info)
Richard Smithc2bebe92016-05-11 20:37:46 +00003300 continue;
John McCalla0296f72010-03-19 07:35:19 +00003301
Richard Smithc2bebe92016-05-11 20:37:46 +00003302 bool Usable = !Info.Constructor->isInvalidDecl();
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003303 if (ListInitializing)
Richard Smithc2bebe92016-05-11 20:37:46 +00003304 Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit());
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003305 else
Richard Smithc2bebe92016-05-11 20:37:46 +00003306 Usable = Usable &&
3307 Info.Constructor->isConvertingConstructor(AllowExplicit);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003308 if (Usable) {
Sebastian Redld9170b02012-03-20 21:24:14 +00003309 bool SuppressUserConversions = !ConstructorsOnly;
3310 if (SuppressUserConversions && ListInitializing) {
3311 SuppressUserConversions = false;
3312 if (NumArgs == 1) {
3313 // If the first argument is (a reference to) the target type,
3314 // suppress conversions.
Sebastian Redle5417162012-03-27 18:33:03 +00003315 SuppressUserConversions = isFirstArgumentCompatibleWithType(
Richard Smithc2bebe92016-05-11 20:37:46 +00003316 S.Context, Info.Constructor, ToType);
Sebastian Redld9170b02012-03-20 21:24:14 +00003317 }
3318 }
Richard Smithc2bebe92016-05-11 20:37:46 +00003319 if (Info.ConstructorTmpl)
3320 S.AddTemplateOverloadCandidate(
3321 Info.ConstructorTmpl, Info.FoundDecl,
3322 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3323 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003324 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00003325 // Allow one user-defined conversion when user specifies a
3326 // From->ToType conversion via an static cast (c-style, etc).
Richard Smithc2bebe92016-05-11 20:37:46 +00003327 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003328 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003329 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003330 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00003331 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003332 }
3333 }
3334
Douglas Gregor5ab11652010-04-17 22:01:05 +00003335 // Enumerate conversion functions, if we're allowed to.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003336 if (ConstructorsOnly || isa<InitListExpr>(From)) {
Richard Smithdb0ac552015-12-18 22:40:25 +00003337 } else if (!S.isCompleteType(From->getLocStart(), From->getType())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003338 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00003339 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00003340 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00003341 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003342 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3343 // Add all of the conversion functions as candidates.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00003344 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3345 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00003346 DeclAccessPair FoundDecl = I.getPair();
3347 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003348 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3349 if (isa<UsingShadowDecl>(D))
3350 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3351
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003352 CXXConversionDecl *Conv;
3353 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00003354 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3355 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003356 else
John McCallda4458e2010-03-31 01:36:47 +00003357 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003358
3359 if (AllowExplicit || !Conv->isExplicit()) {
3360 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00003361 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3362 ActingContext, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003363 CandidateSet,
3364 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003365 else
John McCall5c32be02010-08-24 20:38:10 +00003366 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003367 From, ToType, CandidateSet,
3368 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003369 }
3370 }
3371 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00003372 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003373
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003374 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3375
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003376 OverloadCandidateSet::iterator Best;
Richard Smith48372b62015-01-27 03:30:40 +00003377 switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(),
3378 Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00003379 case OR_Success:
Richard Smith48372b62015-01-27 03:30:40 +00003380 case OR_Deleted:
John McCall5c32be02010-08-24 20:38:10 +00003381 // Record the standard conversion we used and the conversion function.
3382 if (CXXConstructorDecl *Constructor
3383 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3384 // C++ [over.ics.user]p1:
3385 // If the user-defined conversion is specified by a
3386 // constructor (12.3.1), the initial standard conversion
3387 // sequence converts the source type to the type required by
3388 // the argument of the constructor.
3389 //
3390 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003391 if (isa<InitListExpr>(From)) {
3392 // Initializer lists don't have conversions as such.
3393 User.Before.setAsIdentityConversion();
3394 } else {
3395 if (Best->Conversions[0].isEllipsis())
3396 User.EllipsisConversion = true;
3397 else {
3398 User.Before = Best->Conversions[0].Standard;
3399 User.EllipsisConversion = false;
3400 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003401 }
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003402 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003403 User.ConversionFunction = Constructor;
John McCall30909032011-09-21 08:36:56 +00003404 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003405 User.After.setAsIdentityConversion();
3406 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3407 User.After.setAllToTypes(ToType);
Richard Smith48372b62015-01-27 03:30:40 +00003408 return Result;
David Blaikie8a40f702012-01-17 06:56:22 +00003409 }
3410 if (CXXConversionDecl *Conversion
John McCall5c32be02010-08-24 20:38:10 +00003411 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3412 // C++ [over.ics.user]p1:
3413 //
3414 // [...] If the user-defined conversion is specified by a
3415 // conversion function (12.3.2), the initial standard
3416 // conversion sequence converts the source type to the
3417 // implicit object parameter of the conversion function.
3418 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003419 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003420 User.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00003421 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003422 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00003423
John McCall5c32be02010-08-24 20:38:10 +00003424 // C++ [over.ics.user]p2:
3425 // The second standard conversion sequence converts the
3426 // result of the user-defined conversion to the target type
3427 // for the sequence. Since an implicit conversion sequence
3428 // is an initialization, the special rules for
3429 // initialization by user-defined conversion apply when
3430 // selecting the best user-defined conversion for a
3431 // user-defined conversion sequence (see 13.3.3 and
3432 // 13.3.3.1).
3433 User.After = Best->FinalConversion;
Richard Smith48372b62015-01-27 03:30:40 +00003434 return Result;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003435 }
David Blaikie8a40f702012-01-17 06:56:22 +00003436 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003437
John McCall5c32be02010-08-24 20:38:10 +00003438 case OR_No_Viable_Function:
3439 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003440
John McCall5c32be02010-08-24 20:38:10 +00003441 case OR_Ambiguous:
3442 return OR_Ambiguous;
3443 }
3444
David Blaikie8a40f702012-01-17 06:56:22 +00003445 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003446}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003447
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003448bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00003449Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003450 ImplicitConversionSequence ICS;
Richard Smith100b24a2014-04-17 01:52:14 +00003451 OverloadCandidateSet CandidateSet(From->getExprLoc(),
3452 OverloadCandidateSet::CSK_Normal);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003453 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00003454 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003455 CandidateSet, false, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00003456 if (OvResult == OR_Ambiguous)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003457 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3458 << From->getType() << ToType << From->getSourceRange();
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003459 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
Larisse Voufo70bb43a2013-06-27 03:36:30 +00003460 if (!RequireCompleteType(From->getLocStart(), ToType,
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003461 diag::err_typecheck_nonviable_condition_incomplete,
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003462 From->getType(), From->getSourceRange()))
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003463 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
Nick Lewycky08426e22015-08-25 22:18:46 +00003464 << false << From->getType() << From->getSourceRange() << ToType;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003465 } else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003466 return false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003467 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003468 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003469}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003470
Douglas Gregor2837aa22012-02-22 17:32:19 +00003471/// \brief Compare the user-defined conversion functions or constructors
3472/// of two user-defined conversion sequences to determine whether any ordering
3473/// is possible.
3474static ImplicitConversionSequence::CompareKind
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003475compareConversionFunctions(Sema &S, FunctionDecl *Function1,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003476 FunctionDecl *Function2) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003477 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
Douglas Gregor2837aa22012-02-22 17:32:19 +00003478 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003479
Douglas Gregor2837aa22012-02-22 17:32:19 +00003480 // Objective-C++:
3481 // If both conversion functions are implicitly-declared conversions from
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003482 // a lambda closure type to a function pointer and a block pointer,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003483 // respectively, always prefer the conversion to a function pointer,
3484 // because the function pointer is more lightweight and is more likely
3485 // to keep code working.
Ted Kremenek8d265c22014-04-01 07:23:18 +00003486 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003487 if (!Conv1)
3488 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003489
Douglas Gregor2837aa22012-02-22 17:32:19 +00003490 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3491 if (!Conv2)
3492 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003493
Douglas Gregor2837aa22012-02-22 17:32:19 +00003494 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3495 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3496 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3497 if (Block1 != Block2)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003498 return Block1 ? ImplicitConversionSequence::Worse
3499 : ImplicitConversionSequence::Better;
Douglas Gregor2837aa22012-02-22 17:32:19 +00003500 }
3501
3502 return ImplicitConversionSequence::Indistinguishable;
3503}
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003504
3505static bool hasDeprecatedStringLiteralToCharPtrConversion(
3506 const ImplicitConversionSequence &ICS) {
3507 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3508 (ICS.isUserDefined() &&
3509 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3510}
3511
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003512/// CompareImplicitConversionSequences - Compare two implicit
3513/// conversion sequences to determine whether one is better than the
3514/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00003515static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +00003516CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +00003517 const ImplicitConversionSequence& ICS1,
3518 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003519{
3520 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3521 // conversion sequences (as defined in 13.3.3.1)
3522 // -- a standard conversion sequence (13.3.3.1.1) is a better
3523 // conversion sequence than a user-defined conversion sequence or
3524 // an ellipsis conversion sequence, and
3525 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3526 // conversion sequence than an ellipsis conversion sequence
3527 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00003528 //
John McCall0d1da222010-01-12 00:44:57 +00003529 // C++0x [over.best.ics]p10:
3530 // For the purpose of ranking implicit conversion sequences as
3531 // described in 13.3.3.2, the ambiguous conversion sequence is
3532 // treated as a user-defined sequence that is indistinguishable
3533 // from any other user-defined conversion sequence.
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003534
3535 // String literal to 'char *' conversion has been deprecated in C++03. It has
3536 // been removed from C++11. We still accept this conversion, if it happens at
3537 // the best viable function. Otherwise, this conversion is considered worse
3538 // than ellipsis conversion. Consider this as an extension; this is not in the
3539 // standard. For example:
3540 //
3541 // int &f(...); // #1
3542 // void f(char*); // #2
3543 // void g() { int &r = f("foo"); }
3544 //
3545 // In C++03, we pick #2 as the best viable function.
3546 // In C++11, we pick #1 as the best viable function, because ellipsis
3547 // conversion is better than string-literal to char* conversion (since there
3548 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3549 // convert arguments, #2 would be the best viable function in C++11.
3550 // If the best viable function has this conversion, a warning will be issued
3551 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3552
3553 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3554 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3555 hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3556 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3557 ? ImplicitConversionSequence::Worse
3558 : ImplicitConversionSequence::Better;
3559
Douglas Gregor5ab11652010-04-17 22:01:05 +00003560 if (ICS1.getKindRank() < ICS2.getKindRank())
3561 return ImplicitConversionSequence::Better;
David Blaikie8a40f702012-01-17 06:56:22 +00003562 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor5ab11652010-04-17 22:01:05 +00003563 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003564
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00003565 // The following checks require both conversion sequences to be of
3566 // the same kind.
3567 if (ICS1.getKind() != ICS2.getKind())
3568 return ImplicitConversionSequence::Indistinguishable;
3569
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003570 ImplicitConversionSequence::CompareKind Result =
3571 ImplicitConversionSequence::Indistinguishable;
3572
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003573 // Two implicit conversion sequences of the same form are
3574 // indistinguishable conversion sequences unless one of the
3575 // following rules apply: (C++ 13.3.3.2p3):
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003576
Larisse Voufo19d08672015-01-27 18:47:05 +00003577 // List-initialization sequence L1 is a better conversion sequence than
3578 // list-initialization sequence L2 if:
3579 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3580 // if not that,
NAKAMURA Takumib01d86b2015-02-25 11:02:00 +00003581 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
Larisse Voufo19d08672015-01-27 18:47:05 +00003582 // and N1 is smaller than N2.,
3583 // even if one of the other rules in this paragraph would otherwise apply.
3584 if (!ICS1.isBad()) {
3585 if (ICS1.isStdInitializerListElement() &&
3586 !ICS2.isStdInitializerListElement())
3587 return ImplicitConversionSequence::Better;
3588 if (!ICS1.isStdInitializerListElement() &&
3589 ICS2.isStdInitializerListElement())
3590 return ImplicitConversionSequence::Worse;
3591 }
3592
John McCall0d1da222010-01-12 00:44:57 +00003593 if (ICS1.isStandard())
Larisse Voufo19d08672015-01-27 18:47:05 +00003594 // Standard conversion sequence S1 is a better conversion sequence than
3595 // standard conversion sequence S2 if [...]
Richard Smith0f59cb32015-12-18 21:45:41 +00003596 Result = CompareStandardConversionSequences(S, Loc,
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003597 ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00003598 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003599 // User-defined conversion sequence U1 is a better conversion
3600 // sequence than another user-defined conversion sequence U2 if
3601 // they contain the same user-defined conversion function or
3602 // constructor and if the second standard conversion sequence of
3603 // U1 is better than the second standard conversion sequence of
3604 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00003605 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003606 ICS2.UserDefined.ConversionFunction)
Richard Smith0f59cb32015-12-18 21:45:41 +00003607 Result = CompareStandardConversionSequences(S, Loc,
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003608 ICS1.UserDefined.After,
3609 ICS2.UserDefined.After);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003610 else
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003611 Result = compareConversionFunctions(S,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003612 ICS1.UserDefined.ConversionFunction,
3613 ICS2.UserDefined.ConversionFunction);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003614 }
3615
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003616 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003617}
3618
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003619static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3620 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3621 Qualifiers Quals;
3622 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003623 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003624 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003625
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003626 return Context.hasSameUnqualifiedType(T1, T2);
3627}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003628
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003629// Per 13.3.3.2p3, compare the given standard conversion sequences to
3630// determine if one is a proper subset of the other.
3631static ImplicitConversionSequence::CompareKind
3632compareStandardConversionSubsets(ASTContext &Context,
3633 const StandardConversionSequence& SCS1,
3634 const StandardConversionSequence& SCS2) {
3635 ImplicitConversionSequence::CompareKind Result
3636 = ImplicitConversionSequence::Indistinguishable;
3637
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003638 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00003639 // any non-identity conversion sequence
Douglas Gregor377c1092011-06-05 06:15:20 +00003640 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3641 return ImplicitConversionSequence::Better;
3642 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3643 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003644
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003645 if (SCS1.Second != SCS2.Second) {
3646 if (SCS1.Second == ICK_Identity)
3647 Result = ImplicitConversionSequence::Better;
3648 else if (SCS2.Second == ICK_Identity)
3649 Result = ImplicitConversionSequence::Worse;
3650 else
3651 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003652 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003653 return ImplicitConversionSequence::Indistinguishable;
3654
3655 if (SCS1.Third == SCS2.Third) {
3656 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3657 : ImplicitConversionSequence::Indistinguishable;
3658 }
3659
3660 if (SCS1.Third == ICK_Identity)
3661 return Result == ImplicitConversionSequence::Worse
3662 ? ImplicitConversionSequence::Indistinguishable
3663 : ImplicitConversionSequence::Better;
3664
3665 if (SCS2.Third == ICK_Identity)
3666 return Result == ImplicitConversionSequence::Better
3667 ? ImplicitConversionSequence::Indistinguishable
3668 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003669
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003670 return ImplicitConversionSequence::Indistinguishable;
3671}
3672
Douglas Gregore696ebb2011-01-26 14:52:12 +00003673/// \brief Determine whether one of the given reference bindings is better
3674/// than the other based on what kind of bindings they are.
Richard Smith19172c42014-07-14 02:28:44 +00003675static bool
3676isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3677 const StandardConversionSequence &SCS2) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003678 // C++0x [over.ics.rank]p3b4:
3679 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3680 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003681 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00003682 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003683 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00003684 // reference*.
3685 //
3686 // FIXME: Rvalue references. We're going rogue with the above edits,
3687 // because the semantics in the current C++0x working paper (N3225 at the
3688 // time of this writing) break the standard definition of std::forward
3689 // and std::reference_wrapper when dealing with references to functions.
3690 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00003691 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3692 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3693 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003694
Douglas Gregore696ebb2011-01-26 14:52:12 +00003695 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3696 SCS2.IsLvalueReference) ||
3697 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
Richard Smith19172c42014-07-14 02:28:44 +00003698 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
Douglas Gregore696ebb2011-01-26 14:52:12 +00003699}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003700
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003701/// CompareStandardConversionSequences - Compare two standard
3702/// conversion sequences to determine whether one is better than the
3703/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00003704static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +00003705CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +00003706 const StandardConversionSequence& SCS1,
3707 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003708{
3709 // Standard conversion sequence S1 is a better conversion sequence
3710 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3711
3712 // -- S1 is a proper subsequence of S2 (comparing the conversion
3713 // sequences in the canonical form defined by 13.3.3.1.1,
3714 // excluding any Lvalue Transformation; the identity conversion
3715 // sequence is considered to be a subsequence of any
3716 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003717 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00003718 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003719 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003720
3721 // -- the rank of S1 is better than the rank of S2 (by the rules
3722 // defined below), or, if not that,
3723 ImplicitConversionRank Rank1 = SCS1.getRank();
3724 ImplicitConversionRank Rank2 = SCS2.getRank();
3725 if (Rank1 < Rank2)
3726 return ImplicitConversionSequence::Better;
3727 else if (Rank2 < Rank1)
3728 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003729
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003730 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3731 // are indistinguishable unless one of the following rules
3732 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00003733
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003734 // A conversion that is not a conversion of a pointer, or
3735 // pointer to member, to bool is better than another conversion
3736 // that is such a conversion.
3737 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3738 return SCS2.isPointerConversionToBool()
3739 ? ImplicitConversionSequence::Better
3740 : ImplicitConversionSequence::Worse;
3741
Douglas Gregor5c407d92008-10-23 00:40:37 +00003742 // C++ [over.ics.rank]p4b2:
3743 //
3744 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003745 // conversion of B* to A* is better than conversion of B* to
3746 // void*, and conversion of A* to void* is better than conversion
3747 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00003748 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003749 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00003750 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003751 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003752 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3753 // Exactly one of the conversion sequences is a conversion to
3754 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003755 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3756 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003757 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3758 // Neither conversion sequence converts to a void pointer; compare
3759 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003760 if (ImplicitConversionSequence::CompareKind DerivedCK
Richard Smith0f59cb32015-12-18 21:45:41 +00003761 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003762 return DerivedCK;
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003763 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3764 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003765 // Both conversion sequences are conversions to void
3766 // pointers. Compare the source types to determine if there's an
3767 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00003768 QualType FromType1 = SCS1.getFromType();
3769 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003770
3771 // Adjust the types we're converting from via the array-to-pointer
3772 // conversion, if we need to.
3773 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003774 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003775 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003776 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003777
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003778 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3779 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003780
Richard Smith0f59cb32015-12-18 21:45:41 +00003781 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003782 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00003783 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003784 return ImplicitConversionSequence::Worse;
3785
3786 // Objective-C++: If one interface is more specific than the
3787 // other, it is the better one.
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003788 const ObjCObjectPointerType* FromObjCPtr1
3789 = FromType1->getAs<ObjCObjectPointerType>();
3790 const ObjCObjectPointerType* FromObjCPtr2
3791 = FromType2->getAs<ObjCObjectPointerType>();
3792 if (FromObjCPtr1 && FromObjCPtr2) {
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003793 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003794 FromObjCPtr2);
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003795 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003796 FromObjCPtr1);
3797 if (AssignLeft != AssignRight) {
3798 return AssignLeft? ImplicitConversionSequence::Better
3799 : ImplicitConversionSequence::Worse;
3800 }
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003801 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003802 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003803
3804 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3805 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00003806 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00003807 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003808 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003809
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003810 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003811 // Check for a better reference binding based on the kind of bindings.
3812 if (isBetterReferenceBindingKind(SCS1, SCS2))
3813 return ImplicitConversionSequence::Better;
3814 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3815 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003816
Sebastian Redlb28b4072009-03-22 23:49:27 +00003817 // C++ [over.ics.rank]p3b4:
3818 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3819 // which the references refer are the same type except for
3820 // top-level cv-qualifiers, and the type to which the reference
3821 // initialized by S2 refers is more cv-qualified than the type
3822 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003823 QualType T1 = SCS1.getToType(2);
3824 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003825 T1 = S.Context.getCanonicalType(T1);
3826 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003827 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003828 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3829 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003830 if (UnqualT1 == UnqualT2) {
John McCall31168b02011-06-15 23:02:42 +00003831 // Objective-C++ ARC: If the references refer to objects with different
3832 // lifetimes, prefer bindings that don't change lifetime.
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003833 if (SCS1.ObjCLifetimeConversionBinding !=
John McCall31168b02011-06-15 23:02:42 +00003834 SCS2.ObjCLifetimeConversionBinding) {
3835 return SCS1.ObjCLifetimeConversionBinding
3836 ? ImplicitConversionSequence::Worse
3837 : ImplicitConversionSequence::Better;
3838 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003839
Chandler Carruth8e543b32010-12-12 08:17:55 +00003840 // If the type is an array type, promote the element qualifiers to the
3841 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003842 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003843 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003844 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003845 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003846 if (T2.isMoreQualifiedThan(T1))
3847 return ImplicitConversionSequence::Better;
3848 else if (T1.isMoreQualifiedThan(T2))
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003849 return ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003850 }
3851 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003852
Francois Pichet08d2fa02011-09-18 21:37:37 +00003853 // In Microsoft mode, prefer an integral conversion to a
3854 // floating-to-integral conversion if the integral conversion
3855 // is between types of the same size.
3856 // For example:
3857 // void f(float);
3858 // void f(int);
3859 // int main {
3860 // long a;
3861 // f(a);
3862 // }
3863 // Here, MSVC will call f(int) instead of generating a compile error
3864 // as clang will do in standard mode.
Alp Tokerbfa39342014-01-14 12:51:41 +00003865 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3866 SCS2.Second == ICK_Floating_Integral &&
Francois Pichet08d2fa02011-09-18 21:37:37 +00003867 S.Context.getTypeSize(SCS1.getFromType()) ==
Alp Tokerbfa39342014-01-14 12:51:41 +00003868 S.Context.getTypeSize(SCS1.getToType(2)))
Francois Pichet08d2fa02011-09-18 21:37:37 +00003869 return ImplicitConversionSequence::Better;
3870
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003871 return ImplicitConversionSequence::Indistinguishable;
3872}
3873
3874/// CompareQualificationConversions - Compares two standard conversion
3875/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00003876/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
Richard Smith17c00b42014-11-12 01:24:00 +00003877static ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003878CompareQualificationConversions(Sema &S,
3879 const StandardConversionSequence& SCS1,
3880 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00003881 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003882 // -- S1 and S2 differ only in their qualification conversion and
3883 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3884 // cv-qualification signature of type T1 is a proper subset of
3885 // the cv-qualification signature of type T2, and S1 is not the
3886 // deprecated string literal array-to-pointer conversion (4.2).
3887 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3888 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3889 return ImplicitConversionSequence::Indistinguishable;
3890
3891 // FIXME: the example in the standard doesn't use a qualification
3892 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003893 QualType T1 = SCS1.getToType(2);
3894 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003895 T1 = S.Context.getCanonicalType(T1);
3896 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003897 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003898 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3899 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003900
3901 // If the types are the same, we won't learn anything by unwrapped
3902 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003903 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003904 return ImplicitConversionSequence::Indistinguishable;
3905
Chandler Carruth607f38e2009-12-29 07:16:59 +00003906 // If the type is an array type, promote the element qualifiers to the type
3907 // for comparison.
3908 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003909 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003910 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003911 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003912
Mike Stump11289f42009-09-09 15:08:12 +00003913 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003914 = ImplicitConversionSequence::Indistinguishable;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003915
John McCall31168b02011-06-15 23:02:42 +00003916 // Objective-C++ ARC:
3917 // Prefer qualification conversions not involving a change in lifetime
3918 // to qualification conversions that do not change lifetime.
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003919 if (SCS1.QualificationIncludesObjCLifetime !=
John McCall31168b02011-06-15 23:02:42 +00003920 SCS2.QualificationIncludesObjCLifetime) {
3921 Result = SCS1.QualificationIncludesObjCLifetime
3922 ? ImplicitConversionSequence::Worse
3923 : ImplicitConversionSequence::Better;
3924 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00003925
John McCall5c32be02010-08-24 20:38:10 +00003926 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003927 // Within each iteration of the loop, we check the qualifiers to
3928 // determine if this still looks like a qualification
3929 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003930 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003931 // until there are no more pointers or pointers-to-members left
3932 // to unwrap. This essentially mimics what
3933 // IsQualificationConversion does, but here we're checking for a
3934 // strict subset of qualifiers.
3935 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3936 // The qualifiers are the same, so this doesn't tell us anything
3937 // about how the sequences rank.
3938 ;
3939 else if (T2.isMoreQualifiedThan(T1)) {
3940 // T1 has fewer qualifiers, so it could be the better sequence.
3941 if (Result == ImplicitConversionSequence::Worse)
3942 // Neither has qualifiers that are a subset of the other's
3943 // qualifiers.
3944 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003945
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003946 Result = ImplicitConversionSequence::Better;
3947 } else if (T1.isMoreQualifiedThan(T2)) {
3948 // T2 has fewer qualifiers, so it could be the better sequence.
3949 if (Result == ImplicitConversionSequence::Better)
3950 // Neither has qualifiers that are a subset of the other's
3951 // qualifiers.
3952 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003953
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003954 Result = ImplicitConversionSequence::Worse;
3955 } else {
3956 // Qualifiers are disjoint.
3957 return ImplicitConversionSequence::Indistinguishable;
3958 }
3959
3960 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00003961 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003962 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003963 }
3964
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003965 // Check that the winning standard conversion sequence isn't using
3966 // the deprecated string literal array to pointer conversion.
3967 switch (Result) {
3968 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003969 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003970 Result = ImplicitConversionSequence::Indistinguishable;
3971 break;
3972
3973 case ImplicitConversionSequence::Indistinguishable:
3974 break;
3975
3976 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003977 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003978 Result = ImplicitConversionSequence::Indistinguishable;
3979 break;
3980 }
3981
3982 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003983}
3984
Douglas Gregor5c407d92008-10-23 00:40:37 +00003985/// CompareDerivedToBaseConversions - Compares two standard conversion
3986/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00003987/// various kinds of derived-to-base conversions (C++
3988/// [over.ics.rank]p4b3). As part of these checks, we also look at
3989/// conversions between Objective-C interface types.
Richard Smith17c00b42014-11-12 01:24:00 +00003990static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +00003991CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +00003992 const StandardConversionSequence& SCS1,
3993 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00003994 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003995 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00003996 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003997 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003998
3999 // Adjust the types we're converting from via the array-to-pointer
4000 // conversion, if we need to.
4001 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00004002 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00004003 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00004004 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00004005
4006 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00004007 FromType1 = S.Context.getCanonicalType(FromType1);
4008 ToType1 = S.Context.getCanonicalType(ToType1);
4009 FromType2 = S.Context.getCanonicalType(FromType2);
4010 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00004011
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004012 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00004013 //
4014 // If class B is derived directly or indirectly from class A and
4015 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00004016 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004017 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00004018 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00004019 SCS2.Second == ICK_Pointer_Conversion &&
4020 /*FIXME: Remove if Objective-C id conversions get their own rank*/
4021 FromType1->isPointerType() && FromType2->isPointerType() &&
4022 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00004023 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004024 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00004025 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004026 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00004027 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004028 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00004029 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004030 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00004031
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004032 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00004033 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004034 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00004035 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004036 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00004037 return ImplicitConversionSequence::Worse;
4038 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004039
4040 // -- conversion of B* to A* is better than conversion of C* to A*,
4041 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004042 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004043 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004044 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004045 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00004046 }
4047 } else if (SCS1.Second == ICK_Pointer_Conversion &&
4048 SCS2.Second == ICK_Pointer_Conversion) {
4049 const ObjCObjectPointerType *FromPtr1
4050 = FromType1->getAs<ObjCObjectPointerType>();
4051 const ObjCObjectPointerType *FromPtr2
4052 = FromType2->getAs<ObjCObjectPointerType>();
4053 const ObjCObjectPointerType *ToPtr1
4054 = ToType1->getAs<ObjCObjectPointerType>();
4055 const ObjCObjectPointerType *ToPtr2
4056 = ToType2->getAs<ObjCObjectPointerType>();
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00004057
Douglas Gregor058d3de2011-01-31 18:51:41 +00004058 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4059 // Apply the same conversion ranking rules for Objective-C pointer types
4060 // that we do for C++ pointers to class types. However, we employ the
4061 // Objective-C pseudo-subtyping relationship used for assignment of
4062 // Objective-C pointer types.
4063 bool FromAssignLeft
4064 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4065 bool FromAssignRight
4066 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4067 bool ToAssignLeft
4068 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4069 bool ToAssignRight
4070 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
Alex Lorenza9832132017-04-06 13:06:34 +00004071
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00004072 // A conversion to an a non-id object pointer type or qualified 'id'
Douglas Gregor058d3de2011-01-31 18:51:41 +00004073 // type is better than a conversion to 'id'.
4074 if (ToPtr1->isObjCIdType() &&
4075 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4076 return ImplicitConversionSequence::Worse;
4077 if (ToPtr2->isObjCIdType() &&
4078 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4079 return ImplicitConversionSequence::Better;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00004080
4081 // A conversion to a non-id object pointer type is better than a
4082 // conversion to a qualified 'id' type
Douglas Gregor058d3de2011-01-31 18:51:41 +00004083 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4084 return ImplicitConversionSequence::Worse;
4085 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4086 return ImplicitConversionSequence::Better;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00004087
4088 // A conversion to an a non-Class object pointer type or qualified 'Class'
Douglas Gregor058d3de2011-01-31 18:51:41 +00004089 // type is better than a conversion to 'Class'.
4090 if (ToPtr1->isObjCClassType() &&
4091 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4092 return ImplicitConversionSequence::Worse;
4093 if (ToPtr2->isObjCClassType() &&
4094 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4095 return ImplicitConversionSequence::Better;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00004096
4097 // A conversion to a non-Class object pointer type is better than a
Douglas Gregor058d3de2011-01-31 18:51:41 +00004098 // conversion to a qualified 'Class' type.
4099 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4100 return ImplicitConversionSequence::Worse;
4101 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4102 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00004103
Douglas Gregor058d3de2011-01-31 18:51:41 +00004104 // -- "conversion of C* to B* is better than conversion of C* to A*,"
Alex Lorenza9832132017-04-06 13:06:34 +00004105 if (S.Context.hasSameType(FromType1, FromType2) &&
Douglas Gregor058d3de2011-01-31 18:51:41 +00004106 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
Alex Lorenza9832132017-04-06 13:06:34 +00004107 (ToAssignLeft != ToAssignRight)) {
4108 if (FromPtr1->isSpecialized()) {
4109 // "conversion of B<A> * to B * is better than conversion of B * to
4110 // C *.
4111 bool IsFirstSame =
4112 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4113 bool IsSecondSame =
4114 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4115 if (IsFirstSame) {
4116 if (!IsSecondSame)
4117 return ImplicitConversionSequence::Better;
4118 } else if (IsSecondSame)
4119 return ImplicitConversionSequence::Worse;
4120 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00004121 return ToAssignLeft? ImplicitConversionSequence::Worse
4122 : ImplicitConversionSequence::Better;
Alex Lorenza9832132017-04-06 13:06:34 +00004123 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00004124
4125 // -- "conversion of B* to A* is better than conversion of C* to A*,"
4126 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4127 (FromAssignLeft != FromAssignRight))
4128 return FromAssignLeft? ImplicitConversionSequence::Better
4129 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004130 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00004131 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00004132
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00004133 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004134 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4135 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4136 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004137 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004138 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004139 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004140 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004141 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004142 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004143 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004144 ToType2->getAs<MemberPointerType>();
4145 const Type *FromPointeeType1 = FromMemPointer1->getClass();
4146 const Type *ToPointeeType1 = ToMemPointer1->getClass();
4147 const Type *FromPointeeType2 = FromMemPointer2->getClass();
4148 const Type *ToPointeeType2 = ToMemPointer2->getClass();
4149 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4150 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4151 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4152 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00004153 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004154 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004155 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004156 return ImplicitConversionSequence::Worse;
Richard Smith0f59cb32015-12-18 21:45:41 +00004157 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004158 return ImplicitConversionSequence::Better;
4159 }
4160 // conversion of B::* to C::* is better than conversion of A::* to C::*
4161 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004162 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004163 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004164 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004165 return ImplicitConversionSequence::Worse;
4166 }
4167 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004168
Douglas Gregor5ab11652010-04-17 22:01:05 +00004169 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00004170 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00004171 // -- binding of an expression of type C to a reference of type
4172 // B& is better than binding an expression of type C to a
4173 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00004174 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4175 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004176 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004177 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004178 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004179 return ImplicitConversionSequence::Worse;
4180 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004181
Douglas Gregor2fe98832008-11-03 19:09:14 +00004182 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00004183 // -- binding of an expression of type B to a reference of type
4184 // A& is better than binding an expression of type C to a
4185 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00004186 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4187 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004188 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004189 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004190 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004191 return ImplicitConversionSequence::Worse;
4192 }
4193 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004194
Douglas Gregor5c407d92008-10-23 00:40:37 +00004195 return ImplicitConversionSequence::Indistinguishable;
4196}
4197
Douglas Gregor45bb4832013-03-26 23:36:30 +00004198/// \brief Determine whether the given type is valid, e.g., it is not an invalid
4199/// C++ class.
4200static bool isTypeValid(QualType T) {
4201 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4202 return !Record->isInvalidDecl();
4203
4204 return true;
4205}
4206
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004207/// CompareReferenceRelationship - Compare the two types T1 and T2 to
4208/// determine whether they are reference-related,
4209/// reference-compatible, reference-compatible with added
4210/// qualification, or incompatible, for use in C++ initialization by
4211/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4212/// type, and the first type (T1) is the pointee type of the reference
4213/// type being initialized.
4214Sema::ReferenceCompareResult
4215Sema::CompareReferenceRelationship(SourceLocation Loc,
4216 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004217 bool &DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004218 bool &ObjCConversion,
4219 bool &ObjCLifetimeConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004220 assert(!OrigT1->isReferenceType() &&
4221 "T1 must be the pointee type of the reference type");
4222 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4223
4224 QualType T1 = Context.getCanonicalType(OrigT1);
4225 QualType T2 = Context.getCanonicalType(OrigT2);
4226 Qualifiers T1Quals, T2Quals;
4227 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4228 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4229
4230 // C++ [dcl.init.ref]p4:
4231 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4232 // reference-related to "cv2 T2" if T1 is the same type as T2, or
4233 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004234 DerivedToBase = false;
4235 ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004236 ObjCLifetimeConversion = false;
Richard Smith1be59c52016-10-22 01:32:19 +00004237 QualType ConvertedT2;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004238 if (UnqualT1 == UnqualT2) {
4239 // Nothing to do.
Richard Smithdb0ac552015-12-18 22:40:25 +00004240 } else if (isCompleteType(Loc, OrigT2) &&
Douglas Gregor45bb4832013-03-26 23:36:30 +00004241 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00004242 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004243 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004244 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4245 UnqualT2->isObjCObjectOrInterfaceType() &&
4246 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4247 ObjCConversion = true;
Richard Smith1be59c52016-10-22 01:32:19 +00004248 else if (UnqualT2->isFunctionType() &&
4249 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2))
4250 // C++1z [dcl.init.ref]p4:
4251 // cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept
4252 // function" and T1 is "function"
4253 //
4254 // We extend this to also apply to 'noreturn', so allow any function
4255 // conversion between function types.
4256 return Ref_Compatible;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004257 else
4258 return Ref_Incompatible;
4259
4260 // At this point, we know that T1 and T2 are reference-related (at
4261 // least).
4262
4263 // If the type is an array type, promote the element qualifiers to the type
4264 // for comparison.
4265 if (isa<ArrayType>(T1) && T1Quals)
4266 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4267 if (isa<ArrayType>(T2) && T2Quals)
4268 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4269
4270 // C++ [dcl.init.ref]p4:
4271 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4272 // reference-related to T2 and cv1 is the same cv-qualification
4273 // as, or greater cv-qualification than, cv2. For purposes of
4274 // overload resolution, cases for which cv1 is greater
4275 // cv-qualification than cv2 are identified as
4276 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregord517d552011-04-28 17:56:11 +00004277 //
4278 // Note that we also require equivalence of Objective-C GC and address-space
4279 // qualifiers when performing these computations, so that e.g., an int in
4280 // address space 1 is not reference-compatible with an int in address
4281 // space 2.
John McCall31168b02011-06-15 23:02:42 +00004282 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4283 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00004284 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4285 ObjCLifetimeConversion = true;
4286
John McCall31168b02011-06-15 23:02:42 +00004287 T1Quals.removeObjCLifetime();
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00004288 T2Quals.removeObjCLifetime();
John McCall31168b02011-06-15 23:02:42 +00004289 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00004290
Andrey Bokhanko45d41322016-05-11 18:38:21 +00004291 // MS compiler ignores __unaligned qualifier for references; do the same.
4292 T1Quals.removeUnaligned();
4293 T2Quals.removeUnaligned();
4294
Richard Smithce766292016-10-21 23:01:55 +00004295 if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004296 return Ref_Compatible;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004297 else
4298 return Ref_Related;
4299}
4300
George Burgess IVd5c7e7c2017-01-14 05:19:34 +00004301/// \brief Look for a user-defined conversion to a value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00004302/// with DeclType. Return true if something definite is found.
4303static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00004304FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4305 QualType DeclType, SourceLocation DeclLoc,
4306 Expr *Init, QualType T2, bool AllowRvalues,
4307 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004308 assert(T2->isRecordType() && "Can only find conversions of record types.");
4309 CXXRecordDecl *T2RecordDecl
4310 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4311
Richard Smith100b24a2014-04-17 01:52:14 +00004312 OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal);
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004313 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4314 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004315 NamedDecl *D = *I;
4316 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4317 if (isa<UsingShadowDecl>(D))
4318 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4319
4320 FunctionTemplateDecl *ConvTemplate
4321 = dyn_cast<FunctionTemplateDecl>(D);
4322 CXXConversionDecl *Conv;
4323 if (ConvTemplate)
4324 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4325 else
4326 Conv = cast<CXXConversionDecl>(D);
4327
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004328 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00004329 // explicit conversions, skip it.
4330 if (!AllowExplicit && Conv->isExplicit())
4331 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004332
Douglas Gregor836a7e82010-08-11 02:15:33 +00004333 if (AllowRvalues) {
4334 bool DerivedToBase = false;
4335 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004336 bool ObjCLifetimeConversion = false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00004337
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004338 // If we are initializing an rvalue reference, don't permit conversion
4339 // functions that return lvalues.
4340 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4341 const ReferenceType *RefType
4342 = Conv->getConversionType()->getAs<LValueReferenceType>();
4343 if (RefType && !RefType->getPointeeType()->isFunctionType())
4344 continue;
4345 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00004346
Douglas Gregor836a7e82010-08-11 02:15:33 +00004347 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00004348 S.CompareReferenceRelationship(
4349 DeclLoc,
4350 Conv->getConversionType().getNonReferenceType()
4351 .getUnqualifiedType(),
4352 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCall31168b02011-06-15 23:02:42 +00004353 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth8e543b32010-12-12 08:17:55 +00004354 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00004355 continue;
4356 } else {
4357 // If the conversion function doesn't return a reference type,
4358 // it can't be considered for this conversion. An rvalue reference
4359 // is only acceptable if its referencee is a function type.
4360
4361 const ReferenceType *RefType =
4362 Conv->getConversionType()->getAs<ReferenceType>();
4363 if (!RefType ||
4364 (!RefType->isLValueReferenceType() &&
4365 !RefType->getPointeeType()->isFunctionType()))
4366 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00004367 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004368
Douglas Gregor836a7e82010-08-11 02:15:33 +00004369 if (ConvTemplate)
4370 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004371 Init, DeclType, CandidateSet,
4372 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor836a7e82010-08-11 02:15:33 +00004373 else
4374 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004375 DeclType, CandidateSet,
4376 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redld92badf2010-06-30 18:13:39 +00004377 }
4378
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004379 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4380
Sebastian Redld92badf2010-06-30 18:13:39 +00004381 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00004382 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004383 case OR_Success:
4384 // C++ [over.ics.ref]p1:
4385 //
4386 // [...] If the parameter binds directly to the result of
4387 // applying a conversion function to the argument
4388 // expression, the implicit conversion sequence is a
4389 // user-defined conversion sequence (13.3.3.1.2), with the
4390 // second standard conversion sequence either an identity
4391 // conversion or, if the conversion function returns an
4392 // entity of a type that is a derived class of the parameter
4393 // type, a derived-to-base Conversion.
4394 if (!Best->FinalConversion.DirectBinding)
4395 return false;
4396
4397 ICS.setUserDefined();
4398 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4399 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004400 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redld92badf2010-06-30 18:13:39 +00004401 ICS.UserDefined.ConversionFunction = Best->Function;
John McCall30909032011-09-21 08:36:56 +00004402 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redld92badf2010-06-30 18:13:39 +00004403 ICS.UserDefined.EllipsisConversion = false;
4404 assert(ICS.UserDefined.After.ReferenceBinding &&
4405 ICS.UserDefined.After.DirectBinding &&
4406 "Expected a direct reference binding!");
4407 return true;
4408
4409 case OR_Ambiguous:
4410 ICS.setAmbiguous();
4411 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4412 Cand != CandidateSet.end(); ++Cand)
4413 if (Cand->Viable)
Richard Smithc2bebe92016-05-11 20:37:46 +00004414 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
Sebastian Redld92badf2010-06-30 18:13:39 +00004415 return true;
4416
4417 case OR_No_Viable_Function:
4418 case OR_Deleted:
4419 // There was no suitable conversion, or we found a deleted
4420 // conversion; continue with other checks.
4421 return false;
4422 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004423
David Blaikie8a40f702012-01-17 06:56:22 +00004424 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redld92badf2010-06-30 18:13:39 +00004425}
4426
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004427/// \brief Compute an implicit conversion sequence for reference
4428/// initialization.
4429static ImplicitConversionSequence
Sebastian Redldf888642011-12-03 14:54:30 +00004430TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004431 SourceLocation DeclLoc,
4432 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00004433 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004434 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4435
4436 // Most paths end in a failed conversion.
4437 ImplicitConversionSequence ICS;
4438 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4439
4440 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4441 QualType T2 = Init->getType();
4442
4443 // If the initializer is the address of an overloaded function, try
4444 // to resolve the overloaded function. If all goes well, T2 is the
4445 // type of the resulting function.
4446 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4447 DeclAccessPair Found;
4448 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4449 false, Found))
4450 T2 = Fn->getType();
4451 }
4452
4453 // Compute some basic properties of the types and the initializer.
4454 bool isRValRef = DeclType->isRValueReferenceType();
4455 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004456 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004457 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00004458 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004459 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004460 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004461 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004462
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004463
Sebastian Redld92badf2010-06-30 18:13:39 +00004464 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00004465 // A reference to type "cv1 T1" is initialized by an expression
4466 // of type "cv2 T2" as follows:
4467
Sebastian Redld92badf2010-06-30 18:13:39 +00004468 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00004469 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004470 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4471 // reference-compatible with "cv2 T2," or
4472 //
4473 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
Richard Smithce766292016-10-21 23:01:55 +00004474 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004475 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00004476 // When a parameter of reference type binds directly (8.5.3)
4477 // to an argument expression, the implicit conversion sequence
4478 // is the identity conversion, unless the argument expression
4479 // has a type that is a derived class of the parameter type,
4480 // in which case the implicit conversion sequence is a
4481 // derived-to-base Conversion (13.3.3.1).
4482 ICS.setStandard();
4483 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004484 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4485 : ObjCConversion? ICK_Compatible_Conversion
4486 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00004487 ICS.Standard.Third = ICK_Identity;
4488 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4489 ICS.Standard.setToType(0, T2);
4490 ICS.Standard.setToType(1, T1);
4491 ICS.Standard.setToType(2, T1);
4492 ICS.Standard.ReferenceBinding = true;
4493 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004494 ICS.Standard.IsLvalueReference = !isRValRef;
4495 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4496 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004497 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004498 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Craig Topperc3ec1492014-05-26 06:22:03 +00004499 ICS.Standard.CopyConstructor = nullptr;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004500 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004501
Sebastian Redld92badf2010-06-30 18:13:39 +00004502 // Nothing more to do: the inaccessibility/ambiguity check for
4503 // derived-to-base conversions is suppressed when we're
4504 // computing the implicit conversion sequence (C++
4505 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004506 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00004507 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004508
Sebastian Redld92badf2010-06-30 18:13:39 +00004509 // -- has a class type (i.e., T2 is a class type), where T1 is
4510 // not reference-related to T2, and can be implicitly
4511 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4512 // is reference-compatible with "cv3 T3" 92) (this
4513 // conversion is selected by enumerating the applicable
4514 // conversion functions (13.3.1.6) and choosing the best
4515 // one through overload resolution (13.3)),
4516 if (!SuppressUserConversions && T2->isRecordType() &&
Richard Smithdb0ac552015-12-18 22:40:25 +00004517 S.isCompleteType(DeclLoc, T2) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00004518 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00004519 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4520 Init, T2, /*AllowRvalues=*/false,
4521 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00004522 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004523 }
4524 }
4525
Sebastian Redld92badf2010-06-30 18:13:39 +00004526 // -- Otherwise, the reference shall be an lvalue reference to a
4527 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00004528 // shall be an rvalue reference.
Richard Smithce4f6082012-05-24 04:29:20 +00004529 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004530 return ICS;
4531
Douglas Gregorf143cd52011-01-24 16:14:37 +00004532 // -- If the initializer expression
4533 //
4534 // -- is an xvalue, class prvalue, array prvalue or function
John McCall31168b02011-06-15 23:02:42 +00004535 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Richard Smithce766292016-10-21 23:01:55 +00004536 if (RefRelationship == Sema::Ref_Compatible &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004537 (InitCategory.isXValue() ||
Richard Smithce766292016-10-21 23:01:55 +00004538 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4539 (InitCategory.isLValue() && T2->isFunctionType()))) {
Douglas Gregorf143cd52011-01-24 16:14:37 +00004540 ICS.setStandard();
4541 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004542 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004543 : ObjCConversion? ICK_Compatible_Conversion
4544 : ICK_Identity;
4545 ICS.Standard.Third = ICK_Identity;
4546 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4547 ICS.Standard.setToType(0, T2);
4548 ICS.Standard.setToType(1, T1);
4549 ICS.Standard.setToType(2, T1);
4550 ICS.Standard.ReferenceBinding = true;
4551 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4552 // binding unless we're binding to a class prvalue.
4553 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4554 // allow the use of rvalue references in C++98/03 for the benefit of
4555 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004556 ICS.Standard.DirectBinding =
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004557 S.getLangOpts().CPlusPlus11 ||
Richard Smithb94afe12014-07-14 19:54:05 +00004558 !(InitCategory.isPRValue() || T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00004559 ICS.Standard.IsLvalueReference = !isRValRef;
4560 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004561 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00004562 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004563 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Craig Topperc3ec1492014-05-26 06:22:03 +00004564 ICS.Standard.CopyConstructor = nullptr;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004565 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004566 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00004567 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004568
Douglas Gregorf143cd52011-01-24 16:14:37 +00004569 // -- has a class type (i.e., T2 is a class type), where T1 is not
4570 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004571 // an xvalue, class prvalue, or function lvalue of type
4572 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00004573 // "cv3 T3",
4574 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004575 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00004576 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004577 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004578 // class subobject).
4579 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
Richard Smithdb0ac552015-12-18 22:40:25 +00004580 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004581 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4582 Init, T2, /*AllowRvalues=*/true,
4583 AllowExplicit)) {
4584 // In the second case, if the reference is an rvalue reference
4585 // and the second standard conversion sequence of the
4586 // user-defined conversion sequence includes an lvalue-to-rvalue
4587 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004588 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004589 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4590 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4591
Douglas Gregor95273c32011-01-21 16:36:05 +00004592 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00004593 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004594
Richard Smith19172c42014-07-14 02:28:44 +00004595 // A temporary of function type cannot be created; don't even try.
4596 if (T1->isFunctionType())
4597 return ICS;
4598
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004599 // -- Otherwise, a temporary of type "cv1 T1" is created and
4600 // initialized from the initializer expression using the
4601 // rules for a non-reference copy initialization (8.5). The
4602 // reference is then bound to the temporary. If T1 is
4603 // reference-related to T2, cv1 must be the same
4604 // cv-qualification as, or greater cv-qualification than,
4605 // cv2; otherwise, the program is ill-formed.
4606 if (RefRelationship == Sema::Ref_Related) {
4607 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4608 // we would be reference-compatible or reference-compatible with
4609 // added qualification. But that wasn't the case, so the reference
4610 // initialization fails.
John McCall31168b02011-06-15 23:02:42 +00004611 //
4612 // Note that we only want to check address spaces and cvr-qualifiers here.
Andrey Bokhanko45d41322016-05-11 18:38:21 +00004613 // ObjC GC, lifetime and unaligned qualifiers aren't important.
John McCall31168b02011-06-15 23:02:42 +00004614 Qualifiers T1Quals = T1.getQualifiers();
4615 Qualifiers T2Quals = T2.getQualifiers();
4616 T1Quals.removeObjCGCAttr();
4617 T1Quals.removeObjCLifetime();
4618 T2Quals.removeObjCGCAttr();
4619 T2Quals.removeObjCLifetime();
Andrey Bokhanko45d41322016-05-11 18:38:21 +00004620 // MS compiler ignores __unaligned qualifier for references; do the same.
4621 T1Quals.removeUnaligned();
4622 T2Quals.removeUnaligned();
John McCall31168b02011-06-15 23:02:42 +00004623 if (!T1Quals.compatiblyIncludes(T2Quals))
4624 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004625 }
4626
4627 // If at least one of the types is a class type, the types are not
4628 // related, and we aren't allowed any user conversions, the
4629 // reference binding fails. This case is important for breaking
4630 // recursion, since TryImplicitConversion below will attempt to
4631 // create a temporary through the use of a copy constructor.
4632 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4633 (T1->isRecordType() || T2->isRecordType()))
4634 return ICS;
4635
Douglas Gregorcba72b12011-01-21 05:18:22 +00004636 // If T1 is reference-related to T2 and the reference is an rvalue
4637 // reference, the initializer expression shall not be an lvalue.
4638 if (RefRelationship >= Sema::Ref_Related &&
4639 isRValRef && Init->Classify(S.Context).isLValue())
4640 return ICS;
4641
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004642 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004643 // When a parameter of reference type is not bound directly to
4644 // an argument expression, the conversion sequence is the one
4645 // required to convert the argument expression to the
4646 // underlying type of the reference according to
4647 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4648 // to copy-initializing a temporary of the underlying type with
4649 // the argument expression. Any difference in top-level
4650 // cv-qualification is subsumed by the initialization itself
4651 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00004652 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4653 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004654 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004655 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004656 /*AllowObjCWritebackConversion=*/false,
4657 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004658
4659 // Of course, that's still a reference binding.
4660 if (ICS.isStandard()) {
4661 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004662 ICS.Standard.IsLvalueReference = !isRValRef;
Richard Smith19172c42014-07-14 02:28:44 +00004663 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004664 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004665 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004666 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004667 } else if (ICS.isUserDefined()) {
Richard Smith19172c42014-07-14 02:28:44 +00004668 const ReferenceType *LValRefType =
4669 ICS.UserDefined.ConversionFunction->getReturnType()
4670 ->getAs<LValueReferenceType>();
4671
4672 // C++ [over.ics.ref]p3:
4673 // Except for an implicit object parameter, for which see 13.3.1, a
4674 // standard conversion sequence cannot be formed if it requires [...]
4675 // binding an rvalue reference to an lvalue other than a function
4676 // lvalue.
4677 // Note that the function case is not possible here.
4678 if (DeclType->isRValueReferenceType() && LValRefType) {
4679 // FIXME: This is the wrong BadConversionSequence. The problem is binding
4680 // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4681 // reference to an rvalue!
4682 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4683 return ICS;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004684 }
Richard Smith19172c42014-07-14 02:28:44 +00004685
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004686 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004687 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
Richard Smith19172c42014-07-14 02:28:44 +00004688 ICS.UserDefined.After.BindsToFunctionLvalue = false;
4689 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004690 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4691 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004692 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00004693
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004694 return ICS;
4695}
4696
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004697static ImplicitConversionSequence
4698TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4699 bool SuppressUserConversions,
4700 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004701 bool AllowObjCWritebackConversion,
4702 bool AllowExplicit = false);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004703
4704/// TryListConversion - Try to copy-initialize a value of type ToType from the
4705/// initializer list From.
4706static ImplicitConversionSequence
4707TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4708 bool SuppressUserConversions,
4709 bool InOverloadResolution,
4710 bool AllowObjCWritebackConversion) {
4711 // C++11 [over.ics.list]p1:
4712 // When an argument is an initializer list, it is not an expression and
4713 // special rules apply for converting it to a parameter type.
4714
4715 ImplicitConversionSequence Result;
4716 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4717
Sebastian Redl09edce02012-01-23 22:09:39 +00004718 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004719 // initialized from init lists.
Richard Smithdb0ac552015-12-18 22:40:25 +00004720 if (!S.isCompleteType(From->getLocStart(), ToType))
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004721 return Result;
4722
Larisse Voufo19d08672015-01-27 18:47:05 +00004723 // Per DR1467:
4724 // If the parameter type is a class X and the initializer list has a single
4725 // element of type cv U, where U is X or a class derived from X, the
4726 // implicit conversion sequence is the one required to convert the element
4727 // to the parameter type.
4728 //
4729 // Otherwise, if the parameter type is a character array [... ]
4730 // and the initializer list has a single element that is an
4731 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4732 // implicit conversion sequence is the identity conversion.
4733 if (From->getNumInits() == 1) {
4734 if (ToType->isRecordType()) {
4735 QualType InitType = From->getInit(0)->getType();
4736 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00004737 S.IsDerivedFrom(From->getLocStart(), InitType, ToType))
Larisse Voufo19d08672015-01-27 18:47:05 +00004738 return TryCopyInitialization(S, From->getInit(0), ToType,
4739 SuppressUserConversions,
4740 InOverloadResolution,
4741 AllowObjCWritebackConversion);
4742 }
Richard Smith1bbaba82015-01-27 23:23:39 +00004743 // FIXME: Check the other conditions here: array of character type,
4744 // initializer is a string literal.
4745 if (ToType->isArrayType()) {
Larisse Voufo19d08672015-01-27 18:47:05 +00004746 InitializedEntity Entity =
4747 InitializedEntity::InitializeParameter(S.Context, ToType,
4748 /*Consumed=*/false);
4749 if (S.CanPerformCopyInitialization(Entity, From)) {
4750 Result.setStandard();
4751 Result.Standard.setAsIdentityConversion();
4752 Result.Standard.setFromType(ToType);
4753 Result.Standard.setAllToTypes(ToType);
4754 return Result;
4755 }
4756 }
4757 }
4758
4759 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004760 // C++11 [over.ics.list]p2:
4761 // If the parameter type is std::initializer_list<X> or "array of X" and
4762 // all the elements can be implicitly converted to X, the implicit
4763 // conversion sequence is the worst conversion necessary to convert an
4764 // element of the list to X.
Larisse Voufo19d08672015-01-27 18:47:05 +00004765 //
4766 // C++14 [over.ics.list]p3:
NAKAMURA Takumib01d86b2015-02-25 11:02:00 +00004767 // Otherwise, if the parameter type is "array of N X", if the initializer
Larisse Voufo19d08672015-01-27 18:47:05 +00004768 // list has exactly N elements or if it has fewer than N elements and X is
4769 // default-constructible, and if all the elements of the initializer list
4770 // can be implicitly converted to X, the implicit conversion sequence is
4771 // the worst conversion necessary to convert an element of the list to X.
Richard Smith1bbaba82015-01-27 23:23:39 +00004772 //
4773 // FIXME: We're missing a lot of these checks.
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004774 bool toStdInitializerList = false;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004775 QualType X;
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004776 if (ToType->isArrayType())
Richard Smith0db1ea52012-12-09 06:48:56 +00004777 X = S.Context.getAsArrayType(ToType)->getElementType();
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004778 else
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004779 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004780 if (!X.isNull()) {
4781 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4782 Expr *Init = From->getInit(i);
4783 ImplicitConversionSequence ICS =
4784 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4785 InOverloadResolution,
4786 AllowObjCWritebackConversion);
4787 // If a single element isn't convertible, fail.
4788 if (ICS.isBad()) {
4789 Result = ICS;
4790 break;
4791 }
4792 // Otherwise, look for the worst conversion.
4793 if (Result.isBad() ||
Richard Smith0f59cb32015-12-18 21:45:41 +00004794 CompareImplicitConversionSequences(S, From->getLocStart(), ICS,
4795 Result) ==
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004796 ImplicitConversionSequence::Worse)
4797 Result = ICS;
4798 }
Douglas Gregor0f5c1c02012-04-04 23:09:20 +00004799
4800 // For an empty list, we won't have computed any conversion sequence.
4801 // Introduce the identity conversion sequence.
4802 if (From->getNumInits() == 0) {
4803 Result.setStandard();
4804 Result.Standard.setAsIdentityConversion();
4805 Result.Standard.setFromType(ToType);
4806 Result.Standard.setAllToTypes(ToType);
4807 }
4808
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004809 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004810 return Result;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004811 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004812
Larisse Voufo19d08672015-01-27 18:47:05 +00004813 // C++14 [over.ics.list]p4:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004814 // C++11 [over.ics.list]p3:
4815 // Otherwise, if the parameter is a non-aggregate class X and overload
4816 // resolution chooses a single best constructor [...] the implicit
4817 // conversion sequence is a user-defined conversion sequence. If multiple
4818 // constructors are viable but none is better than the others, the
4819 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004820 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4821 // This function can deal with initializer lists.
Richard Smitha93f1022013-09-06 22:30:28 +00004822 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4823 /*AllowExplicit=*/false,
4824 InOverloadResolution, /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004825 AllowObjCWritebackConversion,
4826 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004827 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004828
Larisse Voufo19d08672015-01-27 18:47:05 +00004829 // C++14 [over.ics.list]p5:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004830 // C++11 [over.ics.list]p4:
4831 // Otherwise, if the parameter has an aggregate type which can be
4832 // initialized from the initializer list [...] the implicit conversion
4833 // sequence is a user-defined conversion sequence.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004834 if (ToType->isAggregateType()) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004835 // Type is an aggregate, argument is an init list. At this point it comes
4836 // down to checking whether the initialization works.
4837 // FIXME: Find out whether this parameter is consumed or not.
Richard Smithb8c0f552016-12-09 18:49:13 +00004838 // FIXME: Expose SemaInit's aggregate initialization code so that we don't
4839 // need to call into the initialization code here; overload resolution
4840 // should not be doing that.
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004841 InitializedEntity Entity =
4842 InitializedEntity::InitializeParameter(S.Context, ToType,
4843 /*Consumed=*/false);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004844 if (S.CanPerformCopyInitialization(Entity, From)) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004845 Result.setUserDefined();
4846 Result.UserDefined.Before.setAsIdentityConversion();
4847 // Initializer lists don't have a type.
4848 Result.UserDefined.Before.setFromType(QualType());
4849 Result.UserDefined.Before.setAllToTypes(QualType());
4850
4851 Result.UserDefined.After.setAsIdentityConversion();
4852 Result.UserDefined.After.setFromType(ToType);
4853 Result.UserDefined.After.setAllToTypes(ToType);
Craig Topperc3ec1492014-05-26 06:22:03 +00004854 Result.UserDefined.ConversionFunction = nullptr;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004855 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004856 return Result;
4857 }
4858
Larisse Voufo19d08672015-01-27 18:47:05 +00004859 // C++14 [over.ics.list]p6:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004860 // C++11 [over.ics.list]p5:
4861 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redldf888642011-12-03 14:54:30 +00004862 if (ToType->isReferenceType()) {
4863 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4864 // mention initializer lists in any way. So we go by what list-
4865 // initialization would do and try to extrapolate from that.
4866
4867 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4868
4869 // If the initializer list has a single element that is reference-related
4870 // to the parameter type, we initialize the reference from that.
4871 if (From->getNumInits() == 1) {
4872 Expr *Init = From->getInit(0);
4873
4874 QualType T2 = Init->getType();
4875
4876 // If the initializer is the address of an overloaded function, try
4877 // to resolve the overloaded function. If all goes well, T2 is the
4878 // type of the resulting function.
4879 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4880 DeclAccessPair Found;
4881 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4882 Init, ToType, false, Found))
4883 T2 = Fn->getType();
4884 }
4885
4886 // Compute some basic properties of the types and the initializer.
4887 bool dummy1 = false;
4888 bool dummy2 = false;
4889 bool dummy3 = false;
4890 Sema::ReferenceCompareResult RefRelationship
4891 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4892 dummy2, dummy3);
4893
Richard Smith4d2bbd72013-09-06 01:22:42 +00004894 if (RefRelationship >= Sema::Ref_Related) {
Richard Smitha93f1022013-09-06 22:30:28 +00004895 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4896 SuppressUserConversions,
4897 /*AllowExplicit=*/false);
Richard Smith4d2bbd72013-09-06 01:22:42 +00004898 }
Sebastian Redldf888642011-12-03 14:54:30 +00004899 }
4900
4901 // Otherwise, we bind the reference to a temporary created from the
4902 // initializer list.
4903 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4904 InOverloadResolution,
4905 AllowObjCWritebackConversion);
4906 if (Result.isFailure())
4907 return Result;
4908 assert(!Result.isEllipsis() &&
4909 "Sub-initialization cannot result in ellipsis conversion.");
4910
4911 // Can we even bind to a temporary?
4912 if (ToType->isRValueReferenceType() ||
4913 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4914 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4915 Result.UserDefined.After;
4916 SCS.ReferenceBinding = true;
4917 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4918 SCS.BindsToRvalue = true;
4919 SCS.BindsToFunctionLvalue = false;
4920 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4921 SCS.ObjCLifetimeConversionBinding = false;
4922 } else
4923 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4924 From, ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004925 return Result;
Sebastian Redldf888642011-12-03 14:54:30 +00004926 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004927
Larisse Voufo19d08672015-01-27 18:47:05 +00004928 // C++14 [over.ics.list]p7:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004929 // C++11 [over.ics.list]p6:
4930 // Otherwise, if the parameter type is not a class:
4931 if (!ToType->isRecordType()) {
Larisse Voufo19d08672015-01-27 18:47:05 +00004932 // - if the initializer list has one element that is not itself an
4933 // initializer list, the implicit conversion sequence is the one
4934 // required to convert the element to the parameter type.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004935 unsigned NumInits = From->getNumInits();
Richard Smith1bbaba82015-01-27 23:23:39 +00004936 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004937 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4938 SuppressUserConversions,
4939 InOverloadResolution,
4940 AllowObjCWritebackConversion);
4941 // - if the initializer list has no elements, the implicit conversion
4942 // sequence is the identity conversion.
4943 else if (NumInits == 0) {
4944 Result.setStandard();
4945 Result.Standard.setAsIdentityConversion();
John McCallb73bc9a2012-04-04 02:40:27 +00004946 Result.Standard.setFromType(ToType);
4947 Result.Standard.setAllToTypes(ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004948 }
4949 return Result;
4950 }
4951
Larisse Voufo19d08672015-01-27 18:47:05 +00004952 // C++14 [over.ics.list]p8:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004953 // C++11 [over.ics.list]p7:
4954 // In all cases other than those enumerated above, no conversion is possible
4955 return Result;
4956}
4957
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004958/// TryCopyInitialization - Try to copy-initialize a value of type
4959/// ToType from the expression From. Return the implicit conversion
4960/// sequence required to pass this argument, which may be a bad
4961/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00004962/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00004963/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004964static ImplicitConversionSequence
4965TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004966 bool SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004967 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004968 bool AllowObjCWritebackConversion,
4969 bool AllowExplicit) {
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004970 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4971 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4972 InOverloadResolution,AllowObjCWritebackConversion);
4973
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004974 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004975 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004976 /*FIXME:*/From->getLocStart(),
4977 SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004978 AllowExplicit);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004979
John McCall5c32be02010-08-24 20:38:10 +00004980 return TryImplicitConversion(S, From, ToType,
4981 SuppressUserConversions,
4982 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004983 InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00004984 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004985 AllowObjCWritebackConversion,
4986 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004987}
4988
Anna Zaks1b068122011-07-28 19:46:48 +00004989static bool TryCopyInitialization(const CanQualType FromQTy,
4990 const CanQualType ToQTy,
4991 Sema &S,
4992 SourceLocation Loc,
4993 ExprValueKind FromVK) {
4994 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4995 ImplicitConversionSequence ICS =
4996 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4997
4998 return !ICS.isBad();
4999}
5000
Douglas Gregor436424c2008-11-18 23:14:02 +00005001/// TryObjectArgumentInitialization - Try to initialize the object
5002/// parameter of the given member function (@c Method) from the
5003/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00005004static ImplicitConversionSequence
Richard Smith0f59cb32015-12-18 21:45:41 +00005005TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00005006 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00005007 CXXMethodDecl *Method,
5008 CXXRecordDecl *ActingContext) {
5009 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00005010 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
5011 // const volatile object.
5012 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
5013 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00005014 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00005015
5016 // Set up the conversion sequence as a "bad" conversion, to allow us
5017 // to exit early.
5018 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00005019
5020 // We need to have an object of class type.
Douglas Gregor02824322011-01-26 19:30:28 +00005021 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005022 FromType = PT->getPointeeType();
5023
Douglas Gregor02824322011-01-26 19:30:28 +00005024 // When we had a pointer, it's implicitly dereferenced, so we
5025 // better have an lvalue.
5026 assert(FromClassification.isLValue());
5027 }
5028
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005029 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00005030
Douglas Gregor02824322011-01-26 19:30:28 +00005031 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005032 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00005033 // parameter is
5034 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005035 // - "lvalue reference to cv X" for functions declared without a
5036 // ref-qualifier or with the & ref-qualifier
5037 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00005038 // ref-qualifier
5039 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005040 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00005041 // cv-qualification on the member function declaration.
5042 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005043 // However, when finding an implicit conversion sequence for the argument, we
Richard Smith122f88d2016-12-06 23:52:28 +00005044 // are not allowed to perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00005045 // (C++ [over.match.funcs]p5). We perform a simplified version of
5046 // reference binding here, that allows class rvalues to bind to
5047 // non-constant references.
5048
Douglas Gregor02824322011-01-26 19:30:28 +00005049 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00005050 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005051 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005052 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00005053 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00005054 ICS.setBad(BadConversionSequence::bad_qualifiers,
Richard Smith03c66d32013-01-26 02:07:32 +00005055 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00005056 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00005057 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005058
5059 // Check that we have either the same type or a derived type. It
5060 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00005061 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00005062 ImplicitConversionKind SecondKind;
5063 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5064 SecondKind = ICK_Identity;
Richard Smith0f59cb32015-12-18 21:45:41 +00005065 } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00005066 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00005067 else {
John McCall65eb8792010-02-25 01:37:24 +00005068 ICS.setBad(BadConversionSequence::unrelated_class,
5069 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00005070 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00005071 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005072
Douglas Gregor02824322011-01-26 19:30:28 +00005073 // Check the ref-qualifier.
5074 switch (Method->getRefQualifier()) {
5075 case RQ_None:
5076 // Do nothing; we don't care about lvalueness or rvalueness.
5077 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005078
Douglas Gregor02824322011-01-26 19:30:28 +00005079 case RQ_LValue:
5080 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
5081 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005082 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00005083 ImplicitParamType);
5084 return ICS;
5085 }
5086 break;
5087
5088 case RQ_RValue:
5089 if (!FromClassification.isRValue()) {
5090 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005091 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00005092 ImplicitParamType);
5093 return ICS;
5094 }
5095 break;
5096 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005097
Douglas Gregor436424c2008-11-18 23:14:02 +00005098 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00005099 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00005100 ICS.Standard.setAsIdentityConversion();
5101 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00005102 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00005103 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00005104 ICS.Standard.ReferenceBinding = true;
5105 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005106 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00005107 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00005108 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5109 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5110 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00005111 return ICS;
5112}
5113
5114/// PerformObjectArgumentInitialization - Perform initialization of
5115/// the implicit object parameter for the given Method with the given
5116/// expression.
John Wiegley01296292011-04-08 18:41:53 +00005117ExprResult
5118Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005119 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00005120 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00005121 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005122 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00005123 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005124 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00005125
Douglas Gregor02824322011-01-26 19:30:28 +00005126 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005127 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005128 FromRecordType = PT->getPointeeType();
5129 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00005130 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005131 } else {
5132 FromRecordType = From->getType();
5133 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00005134 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005135 }
5136
John McCall6e9f8f62009-12-03 04:06:58 +00005137 // Note that we always use the true parent context when performing
5138 // the actual argument initialization.
Nico Weberb58e51c2014-11-19 05:21:39 +00005139 ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
Richard Smith0f59cb32015-12-18 21:45:41 +00005140 *this, From->getLocStart(), From->getType(), FromClassification, Method,
5141 Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005142 if (ICS.isBad()) {
5143 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
5144 Qualifiers FromQs = FromRecordType.getQualifiers();
5145 Qualifiers ToQs = DestType.getQualifiers();
5146 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5147 if (CVR) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005148 Diag(From->getLocStart(),
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005149 diag::err_member_function_call_bad_cvr)
5150 << Method->getDeclName() << FromRecordType << (CVR - 1)
5151 << From->getSourceRange();
5152 Diag(Method->getLocation(), diag::note_previous_decl)
5153 << Method->getDeclName();
John Wiegley01296292011-04-08 18:41:53 +00005154 return ExprError();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005155 }
5156 }
5157
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005158 return Diag(From->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00005159 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005160 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005161 }
Mike Stump11289f42009-09-09 15:08:12 +00005162
John Wiegley01296292011-04-08 18:41:53 +00005163 if (ICS.Standard.Second == ICK_Derived_To_Base) {
5164 ExprResult FromRes =
5165 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5166 if (FromRes.isInvalid())
5167 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005168 From = FromRes.get();
John Wiegley01296292011-04-08 18:41:53 +00005169 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005170
Douglas Gregorcc3f3252010-03-03 23:55:11 +00005171 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley01296292011-04-08 18:41:53 +00005172 From = ImpCastExprToType(From, DestType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005173 From->getValueKind()).get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005174 return From;
Douglas Gregor436424c2008-11-18 23:14:02 +00005175}
5176
Douglas Gregor5fb53972009-01-14 15:45:31 +00005177/// TryContextuallyConvertToBool - Attempt to contextually convert the
5178/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00005179static ImplicitConversionSequence
5180TryContextuallyConvertToBool(Sema &S, Expr *From) {
John McCall5c32be02010-08-24 20:38:10 +00005181 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00005182 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00005183 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00005184 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00005185 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005186 /*AllowObjCWritebackConversion=*/false,
5187 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00005188}
5189
5190/// PerformContextuallyConvertToBool - Perform a contextual conversion
5191/// of the expression From to bool (C++0x [conv]p3).
John Wiegley01296292011-04-08 18:41:53 +00005192ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00005193 if (checkPlaceholderForOverload(*this, From))
5194 return ExprError();
5195
John McCall5c32be02010-08-24 20:38:10 +00005196 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00005197 if (!ICS.isBad())
5198 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005199
Fariborz Jahanian76197412009-11-18 18:26:29 +00005200 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005201 return Diag(From->getLocStart(),
John McCall0009fcc2011-04-26 20:42:42 +00005202 diag::err_typecheck_bool_condition)
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00005203 << From->getType() << From->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00005204 return ExprError();
Douglas Gregor5fb53972009-01-14 15:45:31 +00005205}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005206
Richard Smithf8379a02012-01-18 23:55:52 +00005207/// Check that the specified conversion is permitted in a converted constant
5208/// expression, according to C++11 [expr.const]p3. Return true if the conversion
5209/// is acceptable.
5210static bool CheckConvertedConstantConversions(Sema &S,
5211 StandardConversionSequence &SCS) {
5212 // Since we know that the target type is an integral or unscoped enumeration
5213 // type, most conversion kinds are impossible. All possible First and Third
5214 // conversions are fine.
5215 switch (SCS.Second) {
5216 case ICK_Identity:
Richard Smith3c4f8d22016-10-16 17:54:23 +00005217 case ICK_Function_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005218 case ICK_Integral_Promotion:
Richard Smith410cc892014-11-26 03:26:53 +00005219 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
Egor Churaev89831422016-12-23 14:55:49 +00005220 case ICK_Zero_Queue_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005221 return true;
5222
5223 case ICK_Boolean_Conversion:
Richard Smithca24ed42012-09-13 22:00:12 +00005224 // Conversion from an integral or unscoped enumeration type to bool is
Richard Smith410cc892014-11-26 03:26:53 +00005225 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5226 // conversion, so we allow it in a converted constant expression.
5227 //
5228 // FIXME: Per core issue 1407, we should not allow this, but that breaks
5229 // a lot of popular code. We should at least add a warning for this
5230 // (non-conforming) extension.
Richard Smithca24ed42012-09-13 22:00:12 +00005231 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5232 SCS.getToType(2)->isBooleanType();
5233
Richard Smith410cc892014-11-26 03:26:53 +00005234 case ICK_Pointer_Conversion:
5235 case ICK_Pointer_Member:
5236 // C++1z: null pointer conversions and null member pointer conversions are
5237 // only permitted if the source type is std::nullptr_t.
5238 return SCS.getFromType()->isNullPtrType();
5239
5240 case ICK_Floating_Promotion:
5241 case ICK_Complex_Promotion:
5242 case ICK_Floating_Conversion:
5243 case ICK_Complex_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005244 case ICK_Floating_Integral:
Richard Smith410cc892014-11-26 03:26:53 +00005245 case ICK_Compatible_Conversion:
5246 case ICK_Derived_To_Base:
5247 case ICK_Vector_Conversion:
5248 case ICK_Vector_Splat:
Richard Smithf8379a02012-01-18 23:55:52 +00005249 case ICK_Complex_Real:
Richard Smith410cc892014-11-26 03:26:53 +00005250 case ICK_Block_Pointer_Conversion:
5251 case ICK_TransparentUnionConversion:
5252 case ICK_Writeback_Conversion:
5253 case ICK_Zero_Event_Conversion:
George Burgess IV45461812015-10-11 20:13:20 +00005254 case ICK_C_Only_Conversion:
George Burgess IV2099b542016-09-02 22:59:57 +00005255 case ICK_Incompatible_Pointer_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005256 return false;
5257
5258 case ICK_Lvalue_To_Rvalue:
5259 case ICK_Array_To_Pointer:
5260 case ICK_Function_To_Pointer:
Richard Smith410cc892014-11-26 03:26:53 +00005261 llvm_unreachable("found a first conversion kind in Second");
5262
Richard Smithf8379a02012-01-18 23:55:52 +00005263 case ICK_Qualification:
Richard Smith410cc892014-11-26 03:26:53 +00005264 llvm_unreachable("found a third conversion kind in Second");
Richard Smithf8379a02012-01-18 23:55:52 +00005265
5266 case ICK_Num_Conversion_Kinds:
5267 break;
5268 }
5269
5270 llvm_unreachable("unknown conversion kind");
5271}
5272
5273/// CheckConvertedConstantExpression - Check that the expression From is a
5274/// converted constant expression of type T, perform the conversion and produce
5275/// the converted expression, per C++11 [expr.const]p3.
Richard Smith410cc892014-11-26 03:26:53 +00005276static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5277 QualType T, APValue &Value,
5278 Sema::CCEKind CCE,
5279 bool RequireInt) {
5280 assert(S.getLangOpts().CPlusPlus11 &&
5281 "converted constant expression outside C++11");
Richard Smithf8379a02012-01-18 23:55:52 +00005282
Richard Smith410cc892014-11-26 03:26:53 +00005283 if (checkPlaceholderForOverload(S, From))
Richard Smithf8379a02012-01-18 23:55:52 +00005284 return ExprError();
5285
Richard Smith410cc892014-11-26 03:26:53 +00005286 // C++1z [expr.const]p3:
5287 // A converted constant expression of type T is an expression,
5288 // implicitly converted to type T, where the converted
5289 // expression is a constant expression and the implicit conversion
5290 // sequence contains only [... list of conversions ...].
Ismail Pazarbasi4a007742016-09-07 18:24:54 +00005291 // C++1z [stmt.if]p2:
5292 // If the if statement is of the form if constexpr, the value of the
5293 // condition shall be a contextually converted constant expression of type
5294 // bool.
Richard Smithf8379a02012-01-18 23:55:52 +00005295 ImplicitConversionSequence ICS =
Ismail Pazarbasi4a007742016-09-07 18:24:54 +00005296 CCE == Sema::CCEK_ConstexprIf
5297 ? TryContextuallyConvertToBool(S, From)
5298 : TryCopyInitialization(S, From, T,
5299 /*SuppressUserConversions=*/false,
5300 /*InOverloadResolution=*/false,
5301 /*AllowObjcWritebackConversion=*/false,
5302 /*AllowExplicit=*/false);
Craig Topperc3ec1492014-05-26 06:22:03 +00005303 StandardConversionSequence *SCS = nullptr;
Richard Smithf8379a02012-01-18 23:55:52 +00005304 switch (ICS.getKind()) {
5305 case ImplicitConversionSequence::StandardConversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005306 SCS = &ICS.Standard;
5307 break;
5308 case ImplicitConversionSequence::UserDefinedConversion:
Richard Smith410cc892014-11-26 03:26:53 +00005309 // We are converting to a non-class type, so the Before sequence
5310 // must be trivial.
Richard Smithf8379a02012-01-18 23:55:52 +00005311 SCS = &ICS.UserDefined.After;
5312 break;
5313 case ImplicitConversionSequence::AmbiguousConversion:
5314 case ImplicitConversionSequence::BadConversion:
Richard Smith410cc892014-11-26 03:26:53 +00005315 if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5316 return S.Diag(From->getLocStart(),
5317 diag::err_typecheck_converted_constant_expression)
5318 << From->getType() << From->getSourceRange() << T;
Richard Smithf8379a02012-01-18 23:55:52 +00005319 return ExprError();
5320
5321 case ImplicitConversionSequence::EllipsisConversion:
5322 llvm_unreachable("ellipsis conversion in converted constant expression");
5323 }
5324
Richard Smith410cc892014-11-26 03:26:53 +00005325 // Check that we would only use permitted conversions.
5326 if (!CheckConvertedConstantConversions(S, *SCS)) {
5327 return S.Diag(From->getLocStart(),
5328 diag::err_typecheck_converted_constant_expression_disallowed)
5329 << From->getType() << From->getSourceRange() << T;
5330 }
5331 // [...] and where the reference binding (if any) binds directly.
5332 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5333 return S.Diag(From->getLocStart(),
5334 diag::err_typecheck_converted_constant_expression_indirect)
5335 << From->getType() << From->getSourceRange() << T;
5336 }
5337
5338 ExprResult Result =
5339 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
Richard Smithf8379a02012-01-18 23:55:52 +00005340 if (Result.isInvalid())
5341 return Result;
5342
5343 // Check for a narrowing implicit conversion.
5344 APValue PreNarrowingValue;
Richard Smith5614ca72012-03-23 23:55:39 +00005345 QualType PreNarrowingType;
Richard Smith410cc892014-11-26 03:26:53 +00005346 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
Richard Smith5614ca72012-03-23 23:55:39 +00005347 PreNarrowingType)) {
Richard Smith52e624f2016-12-21 21:42:57 +00005348 case NK_Dependent_Narrowing:
5349 // Implicit conversion to a narrower type, but the expression is
5350 // value-dependent so we can't tell whether it's actually narrowing.
Richard Smithf8379a02012-01-18 23:55:52 +00005351 case NK_Variable_Narrowing:
5352 // Implicit conversion to a narrower type, and the value is not a constant
5353 // expression. We'll diagnose this in a moment.
5354 case NK_Not_Narrowing:
5355 break;
5356
5357 case NK_Constant_Narrowing:
Richard Smith410cc892014-11-26 03:26:53 +00005358 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00005359 << CCE << /*Constant*/1
Richard Smith410cc892014-11-26 03:26:53 +00005360 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
Richard Smithf8379a02012-01-18 23:55:52 +00005361 break;
5362
5363 case NK_Type_Narrowing:
Richard Smith410cc892014-11-26 03:26:53 +00005364 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00005365 << CCE << /*Constant*/0 << From->getType() << T;
5366 break;
5367 }
5368
Richard Smith52e624f2016-12-21 21:42:57 +00005369 if (Result.get()->isValueDependent()) {
5370 Value = APValue();
5371 return Result;
5372 }
5373
Richard Smithf8379a02012-01-18 23:55:52 +00005374 // Check the expression is a constant expression.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005375 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithf8379a02012-01-18 23:55:52 +00005376 Expr::EvalResult Eval;
5377 Eval.Diag = &Notes;
5378
Richard Smith410cc892014-11-26 03:26:53 +00005379 if ((T->isReferenceType()
5380 ? !Result.get()->EvaluateAsLValue(Eval, S.Context)
5381 : !Result.get()->EvaluateAsRValue(Eval, S.Context)) ||
5382 (RequireInt && !Eval.Val.isInt())) {
Richard Smithf8379a02012-01-18 23:55:52 +00005383 // The expression can't be folded, so we can't keep it at this position in
5384 // the AST.
5385 Result = ExprError();
Richard Smith911e1422012-01-30 22:27:01 +00005386 } else {
Richard Smith410cc892014-11-26 03:26:53 +00005387 Value = Eval.Val;
Richard Smith911e1422012-01-30 22:27:01 +00005388
5389 if (Notes.empty()) {
5390 // It's a constant expression.
5391 return Result;
5392 }
Richard Smithf8379a02012-01-18 23:55:52 +00005393 }
5394
5395 // It's not a constant expression. Produce an appropriate diagnostic.
5396 if (Notes.size() == 1 &&
5397 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
Richard Smith410cc892014-11-26 03:26:53 +00005398 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
Richard Smithf8379a02012-01-18 23:55:52 +00005399 else {
Richard Smith410cc892014-11-26 03:26:53 +00005400 S.Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smithf8379a02012-01-18 23:55:52 +00005401 << CCE << From->getSourceRange();
5402 for (unsigned I = 0; I < Notes.size(); ++I)
Richard Smith410cc892014-11-26 03:26:53 +00005403 S.Diag(Notes[I].first, Notes[I].second);
Richard Smithf8379a02012-01-18 23:55:52 +00005404 }
Richard Smith410cc892014-11-26 03:26:53 +00005405 return ExprError();
Richard Smithf8379a02012-01-18 23:55:52 +00005406}
5407
Richard Smith410cc892014-11-26 03:26:53 +00005408ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5409 APValue &Value, CCEKind CCE) {
5410 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5411}
5412
5413ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5414 llvm::APSInt &Value,
5415 CCEKind CCE) {
5416 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5417
5418 APValue V;
5419 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
Richard Smith01bfa682016-12-27 02:02:09 +00005420 if (!R.isInvalid() && !R.get()->isValueDependent())
Richard Smith410cc892014-11-26 03:26:53 +00005421 Value = V.getInt();
5422 return R;
5423}
5424
5425
John McCallfec112d2011-09-09 06:11:02 +00005426/// dropPointerConversions - If the given standard conversion sequence
5427/// involves any pointer conversions, remove them. This may change
5428/// the result type of the conversion sequence.
5429static void dropPointerConversion(StandardConversionSequence &SCS) {
5430 if (SCS.Second == ICK_Pointer_Conversion) {
5431 SCS.Second = ICK_Identity;
5432 SCS.Third = ICK_Identity;
5433 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5434 }
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005435}
John McCall5c32be02010-08-24 20:38:10 +00005436
John McCallfec112d2011-09-09 06:11:02 +00005437/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5438/// convert the expression From to an Objective-C pointer type.
5439static ImplicitConversionSequence
5440TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5441 // Do an implicit conversion to 'id'.
5442 QualType Ty = S.Context.getObjCIdType();
5443 ImplicitConversionSequence ICS
5444 = TryImplicitConversion(S, From, Ty,
5445 // FIXME: Are these flags correct?
5446 /*SuppressUserConversions=*/false,
5447 /*AllowExplicit=*/true,
5448 /*InOverloadResolution=*/false,
5449 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005450 /*AllowObjCWritebackConversion=*/false,
5451 /*AllowObjCConversionOnExplicit=*/true);
John McCallfec112d2011-09-09 06:11:02 +00005452
5453 // Strip off any final conversions to 'id'.
5454 switch (ICS.getKind()) {
5455 case ImplicitConversionSequence::BadConversion:
5456 case ImplicitConversionSequence::AmbiguousConversion:
5457 case ImplicitConversionSequence::EllipsisConversion:
5458 break;
5459
5460 case ImplicitConversionSequence::UserDefinedConversion:
5461 dropPointerConversion(ICS.UserDefined.After);
5462 break;
5463
5464 case ImplicitConversionSequence::StandardConversion:
5465 dropPointerConversion(ICS.Standard);
5466 break;
5467 }
5468
5469 return ICS;
5470}
5471
5472/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5473/// conversion of the expression From to an Objective-C pointer type.
Richard Smithe15a3702016-10-06 23:12:58 +00005474/// Returns a valid but null ExprResult if no conversion sequence exists.
John McCallfec112d2011-09-09 06:11:02 +00005475ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00005476 if (checkPlaceholderForOverload(*this, From))
5477 return ExprError();
5478
John McCall8b07ec22010-05-15 11:32:37 +00005479 QualType Ty = Context.getObjCIdType();
John McCallfec112d2011-09-09 06:11:02 +00005480 ImplicitConversionSequence ICS =
5481 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005482 if (!ICS.isBad())
5483 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
Richard Smithe15a3702016-10-06 23:12:58 +00005484 return ExprResult();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005485}
Douglas Gregor5fb53972009-01-14 15:45:31 +00005486
Richard Smith8dd34252012-02-04 07:07:42 +00005487/// Determine whether the provided type is an integral type, or an enumeration
5488/// type of a permitted flavor.
Richard Smithccc11812013-05-21 19:05:48 +00005489bool Sema::ICEConvertDiagnoser::match(QualType T) {
5490 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5491 : T->isIntegralOrUnscopedEnumerationType();
Richard Smith8dd34252012-02-04 07:07:42 +00005492}
5493
Larisse Voufo236bec22013-06-10 06:50:24 +00005494static ExprResult
5495diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5496 Sema::ContextualImplicitConverter &Converter,
5497 QualType T, UnresolvedSetImpl &ViableConversions) {
5498
5499 if (Converter.Suppress)
5500 return ExprError();
5501
5502 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5503 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5504 CXXConversionDecl *Conv =
5505 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5506 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5507 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5508 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005509 return From;
Larisse Voufo236bec22013-06-10 06:50:24 +00005510}
5511
5512static bool
5513diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5514 Sema::ContextualImplicitConverter &Converter,
5515 QualType T, bool HadMultipleCandidates,
5516 UnresolvedSetImpl &ExplicitConversions) {
5517 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5518 DeclAccessPair Found = ExplicitConversions[0];
5519 CXXConversionDecl *Conversion =
5520 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5521
5522 // The user probably meant to invoke the given explicit
5523 // conversion; use it.
5524 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5525 std::string TypeStr;
5526 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5527
5528 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5529 << FixItHint::CreateInsertion(From->getLocStart(),
5530 "static_cast<" + TypeStr + ">(")
5531 << FixItHint::CreateInsertion(
Alp Tokerb6cc5922014-05-03 03:45:55 +00005532 SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
Larisse Voufo236bec22013-06-10 06:50:24 +00005533 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5534
5535 // If we aren't in a SFINAE context, build a call to the
5536 // explicit conversion function.
5537 if (SemaRef.isSFINAEContext())
5538 return true;
5539
Craig Topperc3ec1492014-05-26 06:22:03 +00005540 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
Larisse Voufo236bec22013-06-10 06:50:24 +00005541 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5542 HadMultipleCandidates);
5543 if (Result.isInvalid())
5544 return true;
5545 // Record usage of conversion in an implicit cast.
5546 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005547 CK_UserDefinedConversion, Result.get(),
5548 nullptr, Result.get()->getValueKind());
Larisse Voufo236bec22013-06-10 06:50:24 +00005549 }
5550 return false;
5551}
5552
5553static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5554 Sema::ContextualImplicitConverter &Converter,
5555 QualType T, bool HadMultipleCandidates,
5556 DeclAccessPair &Found) {
5557 CXXConversionDecl *Conversion =
5558 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00005559 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
Larisse Voufo236bec22013-06-10 06:50:24 +00005560
5561 QualType ToType = Conversion->getConversionType().getNonReferenceType();
5562 if (!Converter.SuppressConversion) {
5563 if (SemaRef.isSFINAEContext())
5564 return true;
5565
5566 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5567 << From->getSourceRange();
5568 }
5569
5570 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5571 HadMultipleCandidates);
5572 if (Result.isInvalid())
5573 return true;
5574 // Record usage of conversion in an implicit cast.
5575 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005576 CK_UserDefinedConversion, Result.get(),
5577 nullptr, Result.get()->getValueKind());
Larisse Voufo236bec22013-06-10 06:50:24 +00005578 return false;
5579}
5580
5581static ExprResult finishContextualImplicitConversion(
5582 Sema &SemaRef, SourceLocation Loc, Expr *From,
5583 Sema::ContextualImplicitConverter &Converter) {
5584 if (!Converter.match(From->getType()) && !Converter.Suppress)
5585 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5586 << From->getSourceRange();
5587
5588 return SemaRef.DefaultLvalueConversion(From);
5589}
5590
5591static void
5592collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5593 UnresolvedSetImpl &ViableConversions,
5594 OverloadCandidateSet &CandidateSet) {
5595 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5596 DeclAccessPair FoundDecl = ViableConversions[I];
5597 NamedDecl *D = FoundDecl.getDecl();
5598 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5599 if (isa<UsingShadowDecl>(D))
5600 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5601
5602 CXXConversionDecl *Conv;
5603 FunctionTemplateDecl *ConvTemplate;
5604 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5605 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5606 else
5607 Conv = cast<CXXConversionDecl>(D);
5608
5609 if (ConvTemplate)
5610 SemaRef.AddTemplateConversionCandidate(
Douglas Gregor4b60a152013-11-07 22:34:54 +00005611 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5612 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005613 else
5614 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005615 ToType, CandidateSet,
5616 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005617 }
5618}
5619
Richard Smithccc11812013-05-21 19:05:48 +00005620/// \brief Attempt to convert the given expression to a type which is accepted
5621/// by the given converter.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005622///
Richard Smithccc11812013-05-21 19:05:48 +00005623/// This routine will attempt to convert an expression of class type to a
5624/// type accepted by the specified converter. In C++11 and before, the class
5625/// must have a single non-explicit conversion function converting to a matching
5626/// type. In C++1y, there can be multiple such conversion functions, but only
5627/// one target type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005628///
Douglas Gregor4799d032010-06-30 00:20:43 +00005629/// \param Loc The source location of the construct that requires the
5630/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005631///
James Dennett18348b62012-06-22 08:52:37 +00005632/// \param From The expression we're converting from.
Douglas Gregor4799d032010-06-30 00:20:43 +00005633///
Richard Smithccc11812013-05-21 19:05:48 +00005634/// \param Converter Used to control and diagnose the conversion process.
Richard Smith8dd34252012-02-04 07:07:42 +00005635///
Douglas Gregor4799d032010-06-30 00:20:43 +00005636/// \returns The expression, converted to an integral or enumeration type if
5637/// successful.
Richard Smithccc11812013-05-21 19:05:48 +00005638ExprResult Sema::PerformContextualImplicitConversion(
5639 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005640 // We can't perform any more checking for type-dependent expressions.
5641 if (From->isTypeDependent())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005642 return From;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005643
Eli Friedman1da70392012-01-26 00:26:18 +00005644 // Process placeholders immediately.
5645 if (From->hasPlaceholderType()) {
5646 ExprResult result = CheckPlaceholderExpr(From);
Larisse Voufo236bec22013-06-10 06:50:24 +00005647 if (result.isInvalid())
5648 return result;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005649 From = result.get();
Eli Friedman1da70392012-01-26 00:26:18 +00005650 }
5651
Richard Smithccc11812013-05-21 19:05:48 +00005652 // If the expression already has a matching type, we're golden.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005653 QualType T = From->getType();
Richard Smithccc11812013-05-21 19:05:48 +00005654 if (Converter.match(T))
Eli Friedman1da70392012-01-26 00:26:18 +00005655 return DefaultLvalueConversion(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005656
5657 // FIXME: Check for missing '()' if T is a function type?
5658
Richard Smithccc11812013-05-21 19:05:48 +00005659 // We can only perform contextual implicit conversions on objects of class
5660 // type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005661 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikiebbafb8a2012-03-11 07:00:24 +00005662 if (!RecordTy || !getLangOpts().CPlusPlus) {
Richard Smithccc11812013-05-21 19:05:48 +00005663 if (!Converter.Suppress)
5664 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005665 return From;
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005666 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005667
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005668 // We must have a complete class type.
Douglas Gregora6c5abb2012-05-04 16:48:41 +00005669 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
Richard Smithccc11812013-05-21 19:05:48 +00005670 ContextualImplicitConverter &Converter;
Douglas Gregore2b37442012-05-04 22:38:52 +00005671 Expr *From;
Richard Smithccc11812013-05-21 19:05:48 +00005672
5673 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
Richard Smithdb0ac552015-12-18 22:40:25 +00005674 : Converter(Converter), From(From) {}
Richard Smithccc11812013-05-21 19:05:48 +00005675
Craig Toppere14c0f82014-03-12 04:55:44 +00005676 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00005677 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005678 }
Richard Smithccc11812013-05-21 19:05:48 +00005679 } IncompleteDiagnoser(Converter, From);
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005680
Richard Smithdb0ac552015-12-18 22:40:25 +00005681 if (Converter.Suppress ? !isCompleteType(Loc, T)
5682 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005683 return From;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005684
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005685 // Look for a conversion to an integral or enumeration type.
Larisse Voufo236bec22013-06-10 06:50:24 +00005686 UnresolvedSet<4>
5687 ViableConversions; // These are *potentially* viable in C++1y.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005688 UnresolvedSet<4> ExplicitConversions;
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005689 const auto &Conversions =
Larisse Voufo236bec22013-06-10 06:50:24 +00005690 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005691
Larisse Voufo236bec22013-06-10 06:50:24 +00005692 bool HadMultipleCandidates =
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005693 (std::distance(Conversions.begin(), Conversions.end()) > 1);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005694
Larisse Voufo236bec22013-06-10 06:50:24 +00005695 // To check that there is only one target type, in C++1y:
5696 QualType ToType;
5697 bool HasUniqueTargetType = true;
5698
5699 // Collect explicit or viable (potentially in C++1y) conversions.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005700 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005701 NamedDecl *D = (*I)->getUnderlyingDecl();
5702 CXXConversionDecl *Conversion;
5703 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5704 if (ConvTemplate) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005705 if (getLangOpts().CPlusPlus14)
Larisse Voufo236bec22013-06-10 06:50:24 +00005706 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5707 else
5708 continue; // C++11 does not consider conversion operator templates(?).
5709 } else
5710 Conversion = cast<CXXConversionDecl>(D);
5711
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005712 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
Larisse Voufo236bec22013-06-10 06:50:24 +00005713 "Conversion operator templates are considered potentially "
5714 "viable in C++1y");
5715
5716 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5717 if (Converter.match(CurToType) || ConvTemplate) {
5718
5719 if (Conversion->isExplicit()) {
5720 // FIXME: For C++1y, do we need this restriction?
5721 // cf. diagnoseNoViableConversion()
5722 if (!ConvTemplate)
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005723 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
Larisse Voufo236bec22013-06-10 06:50:24 +00005724 } else {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005725 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005726 if (ToType.isNull())
5727 ToType = CurToType.getUnqualifiedType();
5728 else if (HasUniqueTargetType &&
5729 (CurToType.getUnqualifiedType() != ToType))
5730 HasUniqueTargetType = false;
5731 }
5732 ViableConversions.addDecl(I.getDecl(), I.getAccess());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005733 }
Richard Smith8dd34252012-02-04 07:07:42 +00005734 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005735 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005736
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005737 if (getLangOpts().CPlusPlus14) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005738 // C++1y [conv]p6:
5739 // ... An expression e of class type E appearing in such a context
5740 // is said to be contextually implicitly converted to a specified
5741 // type T and is well-formed if and only if e can be implicitly
5742 // converted to a type T that is determined as follows: E is searched
Larisse Voufo67170bd2013-06-10 08:25:58 +00005743 // for conversion functions whose return type is cv T or reference to
5744 // cv T such that T is allowed by the context. There shall be
Larisse Voufo236bec22013-06-10 06:50:24 +00005745 // exactly one such T.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005746
Larisse Voufo236bec22013-06-10 06:50:24 +00005747 // If no unique T is found:
5748 if (ToType.isNull()) {
5749 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5750 HadMultipleCandidates,
5751 ExplicitConversions))
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005752 return ExprError();
Larisse Voufo236bec22013-06-10 06:50:24 +00005753 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005754 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005755
Larisse Voufo236bec22013-06-10 06:50:24 +00005756 // If more than one unique Ts are found:
5757 if (!HasUniqueTargetType)
5758 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5759 ViableConversions);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005760
Larisse Voufo236bec22013-06-10 06:50:24 +00005761 // If one unique T is found:
5762 // First, build a candidate set from the previously recorded
5763 // potentially viable conversions.
Richard Smith100b24a2014-04-17 01:52:14 +00005764 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Larisse Voufo236bec22013-06-10 06:50:24 +00005765 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5766 CandidateSet);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005767
Larisse Voufo236bec22013-06-10 06:50:24 +00005768 // Then, perform overload resolution over the candidate set.
5769 OverloadCandidateSet::iterator Best;
5770 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5771 case OR_Success: {
5772 // Apply this conversion.
5773 DeclAccessPair Found =
5774 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5775 if (recordConversion(*this, Loc, From, Converter, T,
5776 HadMultipleCandidates, Found))
5777 return ExprError();
5778 break;
5779 }
5780 case OR_Ambiguous:
5781 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5782 ViableConversions);
5783 case OR_No_Viable_Function:
5784 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5785 HadMultipleCandidates,
5786 ExplicitConversions))
5787 return ExprError();
5788 // fall through 'OR_Deleted' case.
5789 case OR_Deleted:
5790 // We'll complain below about a non-integral condition type.
5791 break;
5792 }
5793 } else {
5794 switch (ViableConversions.size()) {
5795 case 0: {
5796 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5797 HadMultipleCandidates,
5798 ExplicitConversions))
Douglas Gregor4799d032010-06-30 00:20:43 +00005799 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005800
Larisse Voufo236bec22013-06-10 06:50:24 +00005801 // We'll complain below about a non-integral condition type.
5802 break;
Douglas Gregor4799d032010-06-30 00:20:43 +00005803 }
Larisse Voufo236bec22013-06-10 06:50:24 +00005804 case 1: {
5805 // Apply this conversion.
5806 DeclAccessPair Found = ViableConversions[0];
5807 if (recordConversion(*this, Loc, From, Converter, T,
5808 HadMultipleCandidates, Found))
5809 return ExprError();
5810 break;
5811 }
5812 default:
5813 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5814 ViableConversions);
5815 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005816 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005817
Larisse Voufo236bec22013-06-10 06:50:24 +00005818 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005819}
5820
Richard Smith100b24a2014-04-17 01:52:14 +00005821/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5822/// an acceptable non-member overloaded operator for a call whose
5823/// arguments have types T1 (and, if non-empty, T2). This routine
5824/// implements the check in C++ [over.match.oper]p3b2 concerning
5825/// enumeration types.
5826static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5827 FunctionDecl *Fn,
5828 ArrayRef<Expr *> Args) {
5829 QualType T1 = Args[0]->getType();
5830 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5831
5832 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5833 return true;
5834
5835 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5836 return true;
5837
5838 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5839 if (Proto->getNumParams() < 1)
5840 return false;
5841
5842 if (T1->isEnumeralType()) {
5843 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5844 if (Context.hasSameUnqualifiedType(T1, ArgType))
5845 return true;
5846 }
5847
5848 if (Proto->getNumParams() < 2)
5849 return false;
5850
5851 if (!T2.isNull() && T2->isEnumeralType()) {
5852 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5853 if (Context.hasSameUnqualifiedType(T2, ArgType))
5854 return true;
5855 }
5856
5857 return false;
5858}
5859
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005860/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00005861/// candidate functions, using the given function call arguments. If
5862/// @p SuppressUserConversions, then don't allow user-defined
5863/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00005864///
James Dennett2a4d13c2012-06-15 07:13:21 +00005865/// \param PartialOverloading true if we are performing "partial" overloading
Douglas Gregorcabea402009-09-22 15:41:20 +00005866/// based on an incomplete set of function arguments. This feature is used by
5867/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00005868void
5869Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00005870 DeclAccessPair FoundDecl,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005871 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005872 OverloadCandidateSet &CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00005873 bool SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005874 bool PartialOverloading,
Richard Smith6eedfe72017-01-09 08:01:21 +00005875 bool AllowExplicit,
5876 ConversionSequenceList EarlyConversions) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005877 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00005878 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005879 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00005880 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005881 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00005882
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005883 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005884 if (!isa<CXXConstructorDecl>(Method)) {
5885 // If we get here, it's because we're calling a member function
5886 // that is named without a member access expression (e.g.,
5887 // "this->f") that was either written explicitly or created
5888 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00005889 // function, e.g., X::f(). We use an empty type for the implied
5890 // object argument (C++ [over.call.func]p3), and the acting context
5891 // is irrelevant.
Richard Smith6eedfe72017-01-09 08:01:21 +00005892 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
George Burgess IVce6284b2017-01-28 02:19:40 +00005893 Expr::Classification::makeSimpleLValue(), Args,
5894 CandidateSet, SuppressUserConversions,
5895 PartialOverloading, EarlyConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005896 return;
5897 }
5898 // We treat a constructor like a non-member function, since its object
5899 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005900 }
5901
Douglas Gregorff7028a2009-11-13 23:59:09 +00005902 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005903 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00005904
Richard Smith100b24a2014-04-17 01:52:14 +00005905 // C++ [over.match.oper]p3:
5906 // if no operand has a class type, only those non-member functions in the
5907 // lookup set that have a first parameter of type T1 or "reference to
5908 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5909 // is a right operand) a second parameter of type T2 or "reference to
5910 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
5911 // candidate functions.
5912 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5913 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5914 return;
5915
Richard Smith8b86f2d2013-11-04 01:48:18 +00005916 // C++11 [class.copy]p11: [DR1402]
5917 // A defaulted move constructor that is defined as deleted is ignored by
5918 // overload resolution.
5919 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5920 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5921 Constructor->isMoveConstructor())
5922 return;
5923
Douglas Gregor27381f32009-11-23 12:27:39 +00005924 // Overload resolution is always an unevaluated context.
Faisal Valid143a0c2017-04-01 21:30:49 +00005925 EnterExpressionEvaluationContext Unevaluated(
5926 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005927
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005928 // Add this candidate
Richard Smith6eedfe72017-01-09 08:01:21 +00005929 OverloadCandidate &Candidate =
5930 CandidateSet.addCandidate(Args.size(), EarlyConversions);
John McCalla0296f72010-03-19 07:35:19 +00005931 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005932 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005933 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005934 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005935 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005936 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005937
John McCall578a1f82014-12-14 01:46:53 +00005938 if (Constructor) {
5939 // C++ [class.copy]p3:
5940 // A member function template is never instantiated to perform the copy
5941 // of a class object to an object of its class type.
5942 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
Richard Smith0f59cb32015-12-18 21:45:41 +00005943 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
John McCall578a1f82014-12-14 01:46:53 +00005944 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00005945 IsDerivedFrom(Args[0]->getLocStart(), Args[0]->getType(),
5946 ClassType))) {
John McCall578a1f82014-12-14 01:46:53 +00005947 Candidate.Viable = false;
5948 Candidate.FailureKind = ovl_fail_illegal_constructor;
5949 return;
5950 }
Richard Smith836a3b42017-01-13 20:46:54 +00005951
5952 // C++ [over.match.funcs]p8: (proposed DR resolution)
5953 // A constructor inherited from class type C that has a first parameter
5954 // of type "reference to P" (including such a constructor instantiated
5955 // from a template) is excluded from the set of candidate functions when
5956 // constructing an object of type cv D if the argument list has exactly
5957 // one argument and D is reference-related to P and P is reference-related
5958 // to C.
5959 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
5960 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
5961 Constructor->getParamDecl(0)->getType()->isReferenceType()) {
5962 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
5963 QualType C = Context.getRecordType(Constructor->getParent());
5964 QualType D = Context.getRecordType(Shadow->getParent());
5965 SourceLocation Loc = Args.front()->getExprLoc();
5966 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
5967 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
5968 Candidate.Viable = false;
5969 Candidate.FailureKind = ovl_fail_inhctor_slice;
5970 return;
5971 }
5972 }
John McCall578a1f82014-12-14 01:46:53 +00005973 }
5974
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005975 unsigned NumParams = Proto->getNumParams();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005976
5977 // (C++ 13.3.2p2): A candidate function having fewer than m
5978 // parameters is viable only if it has an ellipsis in its parameter
5979 // list (8.3.5).
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005980 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
Douglas Gregor2a920012009-09-23 14:56:09 +00005981 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005982 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005983 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005984 return;
5985 }
5986
5987 // (C++ 13.3.2p2): A candidate function having more than m parameters
5988 // is viable only if the (m+1)st parameter has a default argument
5989 // (8.3.6). For the purposes of overload resolution, the
5990 // parameter list is truncated on the right, so that there are
5991 // exactly m parameters.
5992 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005993 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005994 // Not enough arguments.
5995 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005996 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005997 return;
5998 }
5999
Peter Collingbourne7277fe82011-10-02 23:49:40 +00006000 // (CUDA B.1): Check for invalid calls between targets.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006001 if (getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00006002 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
Eli Bendersky9a220fc2014-09-29 20:38:29 +00006003 // Skip the check for callers that are implicit members, because in this
6004 // case we may not yet know what the member's target is; the target is
6005 // inferred for the member automatically, based on the bases and fields of
6006 // the class.
Justin Lebarb0080032016-08-10 01:09:11 +00006007 if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00006008 Candidate.Viable = false;
6009 Candidate.FailureKind = ovl_fail_bad_target;
6010 return;
6011 }
6012
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006013 // Determine the implicit conversion sequences for each of the
6014 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006015 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Richard Smith6eedfe72017-01-09 08:01:21 +00006016 if (Candidate.Conversions[ArgIdx].isInitialized()) {
6017 // We already formed a conversion sequence for this parameter during
6018 // template argument deduction.
6019 } else if (ArgIdx < NumParams) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006020 // (C++ 13.3.2p3): for F to be a viable function, there shall
6021 // exist for each argument an implicit conversion sequence
6022 // (13.3.3.1) that converts that argument to the corresponding
6023 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00006024 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00006025 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006026 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006027 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00006028 /*InOverloadResolution=*/true,
6029 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006030 getLangOpts().ObjCAutoRefCount,
Douglas Gregor6073dca2012-02-24 23:56:31 +00006031 AllowExplicit);
John McCall0d1da222010-01-12 00:44:57 +00006032 if (Candidate.Conversions[ArgIdx].isBad()) {
6033 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006034 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006035 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00006036 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006037 } else {
6038 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6039 // argument for which there is no corresponding parameter is
6040 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006041 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006042 }
6043 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006044
6045 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
6046 Candidate.Viable = false;
6047 Candidate.FailureKind = ovl_fail_enable_if;
6048 Candidate.DeductionFailure.Data = FailedAttr;
6049 return;
6050 }
Yaxun Liu5b746652016-12-18 05:18:55 +00006051
6052 if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) {
6053 Candidate.Viable = false;
6054 Candidate.FailureKind = ovl_fail_ext_disabled;
6055 return;
6056 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006057}
6058
Manman Rend2a3cd72016-04-07 19:30:20 +00006059ObjCMethodDecl *
6060Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
6061 SmallVectorImpl<ObjCMethodDecl *> &Methods) {
6062 if (Methods.size() <= 1)
Fariborz Jahanian0ded4242014-08-13 21:24:14 +00006063 return nullptr;
Manman Rend2a3cd72016-04-07 19:30:20 +00006064
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006065 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6066 bool Match = true;
6067 ObjCMethodDecl *Method = Methods[b];
6068 unsigned NumNamedArgs = Sel.getNumArgs();
6069 // Method might have more arguments than selector indicates. This is due
6070 // to addition of c-style arguments in method.
6071 if (Method->param_size() > NumNamedArgs)
6072 NumNamedArgs = Method->param_size();
6073 if (Args.size() < NumNamedArgs)
6074 continue;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00006075
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006076 for (unsigned i = 0; i < NumNamedArgs; i++) {
6077 // We can't do any type-checking on a type-dependent argument.
6078 if (Args[i]->isTypeDependent()) {
6079 Match = false;
6080 break;
6081 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00006082
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006083 ParmVarDecl *param = Method->parameters()[i];
6084 Expr *argExpr = Args[i];
6085 assert(argExpr && "SelectBestMethod(): missing expression");
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00006086
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006087 // Strip the unbridged-cast placeholder expression off unless it's
6088 // a consumed argument.
6089 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
6090 !param->hasAttr<CFConsumedAttr>())
6091 argExpr = stripARCUnbridgedCast(argExpr);
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00006092
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006093 // If the parameter is __unknown_anytype, move on to the next method.
6094 if (param->getType() == Context.UnknownAnyTy) {
6095 Match = false;
6096 break;
6097 }
George Burgess IV45461812015-10-11 20:13:20 +00006098
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006099 ImplicitConversionSequence ConversionState
6100 = TryCopyInitialization(*this, argExpr, param->getType(),
6101 /*SuppressUserConversions*/false,
6102 /*InOverloadResolution=*/true,
6103 /*AllowObjCWritebackConversion=*/
6104 getLangOpts().ObjCAutoRefCount,
6105 /*AllowExplicit*/false);
George Burgess IV2099b542016-09-02 22:59:57 +00006106 // This function looks for a reasonably-exact match, so we consider
6107 // incompatible pointer conversions to be a failure here.
6108 if (ConversionState.isBad() ||
6109 (ConversionState.isStandard() &&
6110 ConversionState.Standard.Second ==
6111 ICK_Incompatible_Pointer_Conversion)) {
6112 Match = false;
6113 break;
6114 }
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006115 }
6116 // Promote additional arguments to variadic methods.
6117 if (Match && Method->isVariadic()) {
6118 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6119 if (Args[i]->isTypeDependent()) {
6120 Match = false;
6121 break;
6122 }
6123 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6124 nullptr);
6125 if (Arg.isInvalid()) {
6126 Match = false;
6127 break;
6128 }
6129 }
Fariborz Jahanian180d76b2014-08-27 16:38:47 +00006130 } else {
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006131 // Check for extra arguments to non-variadic methods.
6132 if (Args.size() != NumNamedArgs)
6133 Match = false;
Fariborz Jahanian180d76b2014-08-27 16:38:47 +00006134 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6135 // Special case when selectors have no argument. In this case, select
6136 // one with the most general result type of 'id'.
6137 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6138 QualType ReturnT = Methods[b]->getReturnType();
6139 if (ReturnT->isObjCIdType())
6140 return Methods[b];
6141 }
6142 }
6143 }
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006144
6145 if (Match)
6146 return Method;
6147 }
6148 return nullptr;
6149}
6150
George Burgess IV2a6150d2015-10-16 01:17:38 +00006151// specific_attr_iterator iterates over enable_if attributes in reverse, and
6152// enable_if is order-sensitive. As a result, we need to reverse things
6153// sometimes. Size of 4 elements is arbitrary.
6154static SmallVector<EnableIfAttr *, 4>
6155getOrderedEnableIfAttrs(const FunctionDecl *Function) {
6156 SmallVector<EnableIfAttr *, 4> Result;
6157 if (!Function->hasAttrs())
6158 return Result;
6159
6160 const auto &FuncAttrs = Function->getAttrs();
6161 for (Attr *Attr : FuncAttrs)
6162 if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr))
6163 Result.push_back(EnableIf);
6164
6165 std::reverse(Result.begin(), Result.end());
6166 return Result;
6167}
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006168
George Burgess IV177399e2017-01-09 04:12:14 +00006169static bool
6170convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg,
6171 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap,
6172 bool MissingImplicitThis, Expr *&ConvertedThis,
6173 SmallVectorImpl<Expr *> &ConvertedArgs) {
6174 if (ThisArg) {
6175 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6176 assert(!isa<CXXConstructorDecl>(Method) &&
6177 "Shouldn't have `this` for ctors!");
6178 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
6179 ExprResult R = S.PerformObjectArgumentInitialization(
6180 ThisArg, /*Qualifier=*/nullptr, Method, Method);
6181 if (R.isInvalid())
6182 return false;
6183 ConvertedThis = R.get();
6184 } else {
6185 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
6186 (void)MD;
6187 assert((MissingImplicitThis || MD->isStatic() ||
6188 isa<CXXConstructorDecl>(MD)) &&
6189 "Expected `this` for non-ctor instance methods");
6190 }
6191 ConvertedThis = nullptr;
6192 }
Nick Lewyckye283c552015-08-25 22:33:16 +00006193
George Burgess IV458b3f32016-08-12 04:19:35 +00006194 // Ignore any variadic arguments. Converting them is pointless, since the
George Burgess IV177399e2017-01-09 04:12:14 +00006195 // user can't refer to them in the function condition.
George Burgess IV53b938d2016-08-12 04:12:31 +00006196 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6197
Nick Lewyckye283c552015-08-25 22:33:16 +00006198 // Convert the arguments.
George Burgess IV53b938d2016-08-12 04:12:31 +00006199 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
George Burgess IVe96abf72016-02-24 22:31:14 +00006200 ExprResult R;
George Burgess IV177399e2017-01-09 04:12:14 +00006201 R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6202 S.Context, Function->getParamDecl(I)),
George Burgess IVe96abf72016-02-24 22:31:14 +00006203 SourceLocation(), Args[I]);
George Burgess IVe96abf72016-02-24 22:31:14 +00006204
George Burgess IV177399e2017-01-09 04:12:14 +00006205 if (R.isInvalid())
6206 return false;
George Burgess IVe96abf72016-02-24 22:31:14 +00006207
George Burgess IVe96abf72016-02-24 22:31:14 +00006208 ConvertedArgs.push_back(R.get());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006209 }
6210
George Burgess IV177399e2017-01-09 04:12:14 +00006211 if (Trap.hasErrorOccurred())
6212 return false;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006213
Nick Lewyckye283c552015-08-25 22:33:16 +00006214 // Push default arguments if needed.
6215 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6216 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6217 ParmVarDecl *P = Function->getParamDecl(i);
George Burgess IV177399e2017-01-09 04:12:14 +00006218 ExprResult R = S.PerformCopyInitialization(
6219 InitializedEntity::InitializeParameter(S.Context,
Nick Lewyckye283c552015-08-25 22:33:16 +00006220 Function->getParamDecl(i)),
6221 SourceLocation(),
6222 P->hasUninstantiatedDefaultArg() ? P->getUninstantiatedDefaultArg()
6223 : P->getDefaultArg());
George Burgess IV177399e2017-01-09 04:12:14 +00006224 if (R.isInvalid())
6225 return false;
Nick Lewyckye283c552015-08-25 22:33:16 +00006226 ConvertedArgs.push_back(R.get());
6227 }
6228
George Burgess IV177399e2017-01-09 04:12:14 +00006229 if (Trap.hasErrorOccurred())
6230 return false;
Nick Lewyckye283c552015-08-25 22:33:16 +00006231 }
George Burgess IV177399e2017-01-09 04:12:14 +00006232 return true;
6233}
6234
6235EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
6236 bool MissingImplicitThis) {
6237 SmallVector<EnableIfAttr *, 4> EnableIfAttrs =
6238 getOrderedEnableIfAttrs(Function);
6239 if (EnableIfAttrs.empty())
6240 return nullptr;
6241
6242 SFINAETrap Trap(*this);
6243 SmallVector<Expr *, 16> ConvertedArgs;
6244 // FIXME: We should look into making enable_if late-parsed.
6245 Expr *DiscardedThis;
6246 if (!convertArgsForAvailabilityChecks(
6247 *this, Function, /*ThisArg=*/nullptr, Args, Trap,
6248 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
6249 return EnableIfAttrs[0];
Nick Lewyckye283c552015-08-25 22:33:16 +00006250
George Burgess IV2a6150d2015-10-16 01:17:38 +00006251 for (auto *EIA : EnableIfAttrs) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006252 APValue Result;
George Burgess IVe8f10cc2016-05-11 01:38:27 +00006253 // FIXME: This doesn't consider value-dependent cases, because doing so is
6254 // very difficult. Ideally, we should handle them more gracefully.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006255 if (!EIA->getCond()->EvaluateWithSubstitution(
George Burgess IVe8f10cc2016-05-11 01:38:27 +00006256 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006257 return EIA;
George Burgess IVe8f10cc2016-05-11 01:38:27 +00006258
6259 if (!Result.isInt() || !Result.getInt().getBoolValue())
6260 return EIA;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006261 }
Craig Topperc3ec1492014-05-26 06:22:03 +00006262 return nullptr;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006263}
6264
George Burgess IV177399e2017-01-09 04:12:14 +00006265template <typename CheckFn>
Argyrios Kyrtzidisa7233bd2017-05-24 00:46:27 +00006266static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
George Burgess IVce6284b2017-01-28 02:19:40 +00006267 bool ArgDependent, SourceLocation Loc,
6268 CheckFn &&IsSuccessful) {
6269 SmallVector<const DiagnoseIfAttr *, 8> Attrs;
Argyrios Kyrtzidisa7233bd2017-05-24 00:46:27 +00006270 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
George Burgess IVce6284b2017-01-28 02:19:40 +00006271 if (ArgDependent == DIA->getArgDependent())
6272 Attrs.push_back(DIA);
6273 }
6274
6275 // Common case: No diagnose_if attributes, so we can quit early.
6276 if (Attrs.empty())
6277 return false;
6278
6279 auto WarningBegin = std::stable_partition(
6280 Attrs.begin(), Attrs.end(),
6281 [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
6282
George Burgess IV177399e2017-01-09 04:12:14 +00006283 // Note that diagnose_if attributes are late-parsed, so they appear in the
6284 // correct order (unlike enable_if attributes).
George Burgess IVce6284b2017-01-28 02:19:40 +00006285 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
6286 IsSuccessful);
6287 if (ErrAttr != WarningBegin) {
6288 const DiagnoseIfAttr *DIA = *ErrAttr;
6289 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
6290 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6291 << DIA->getParent() << DIA->getCond()->getSourceRange();
6292 return true;
6293 }
George Burgess IV177399e2017-01-09 04:12:14 +00006294
George Burgess IVce6284b2017-01-28 02:19:40 +00006295 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
6296 if (IsSuccessful(DIA)) {
6297 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
6298 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6299 << DIA->getParent() << DIA->getCond()->getSourceRange();
6300 }
6301
6302 return false;
George Burgess IV177399e2017-01-09 04:12:14 +00006303}
6304
George Burgess IVce6284b2017-01-28 02:19:40 +00006305bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
6306 const Expr *ThisArg,
6307 ArrayRef<const Expr *> Args,
6308 SourceLocation Loc) {
6309 return diagnoseDiagnoseIfAttrsWith(
6310 *this, Function, /*ArgDependent=*/true, Loc,
6311 [&](const DiagnoseIfAttr *DIA) {
6312 APValue Result;
6313 // It's sane to use the same Args for any redecl of this function, since
6314 // EvaluateWithSubstitution only cares about the position of each
6315 // argument in the arg list, not the ParmVarDecl* it maps to.
6316 if (!DIA->getCond()->EvaluateWithSubstitution(
Argyrios Kyrtzidisa7233bd2017-05-24 00:46:27 +00006317 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
George Burgess IVce6284b2017-01-28 02:19:40 +00006318 return false;
6319 return Result.isInt() && Result.getInt().getBoolValue();
6320 });
George Burgess IV177399e2017-01-09 04:12:14 +00006321}
6322
Argyrios Kyrtzidisa7233bd2017-05-24 00:46:27 +00006323bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
George Burgess IVce6284b2017-01-28 02:19:40 +00006324 SourceLocation Loc) {
6325 return diagnoseDiagnoseIfAttrsWith(
Argyrios Kyrtzidisa7233bd2017-05-24 00:46:27 +00006326 *this, ND, /*ArgDependent=*/false, Loc,
George Burgess IVce6284b2017-01-28 02:19:40 +00006327 [&](const DiagnoseIfAttr *DIA) {
6328 bool Result;
6329 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
6330 Result;
6331 });
George Burgess IV177399e2017-01-09 04:12:14 +00006332}
6333
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006334/// \brief Add all of the function declarations in the given function set to
Nick Lewyckyed4265c2013-09-22 10:06:01 +00006335/// the overload candidate set.
John McCall4c4c1df2010-01-26 03:27:55 +00006336void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006337 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006338 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006339 TemplateArgumentListInfo *ExplicitTemplateArgs,
Richard Smithbcc22fc2012-03-09 08:00:36 +00006340 bool SuppressUserConversions,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006341 bool PartialOverloading) {
John McCall4c4c1df2010-01-26 03:27:55 +00006342 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00006343 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6344 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Erik Verbruggenf1898cf2017-03-28 07:22:21 +00006345 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
6346 QualType ObjectType;
6347 Expr::Classification ObjectClassification;
6348 if (Expr *E = Args[0]) {
6349 // Use the explit base to restrict the lookup:
6350 ObjectType = E->getType();
6351 ObjectClassification = E->Classify(Context);
6352 } // .. else there is an implit base.
John McCalla0296f72010-03-19 07:35:19 +00006353 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
Erik Verbruggenf1898cf2017-03-28 07:22:21 +00006354 cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
6355 ObjectClassification, Args.slice(1), CandidateSet,
6356 SuppressUserConversions, PartialOverloading);
6357 } else {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006358 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006359 SuppressUserConversions, PartialOverloading);
Erik Verbruggenf1898cf2017-03-28 07:22:21 +00006360 }
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006361 } else {
John McCalla0296f72010-03-19 07:35:19 +00006362 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006363 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
Erik Verbruggenf1898cf2017-03-28 07:22:21 +00006364 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic()) {
6365 QualType ObjectType;
6366 Expr::Classification ObjectClassification;
6367 if (Expr *E = Args[0]) {
6368 // Use the explit base to restrict the lookup:
6369 ObjectType = E->getType();
6370 ObjectClassification = E->Classify(Context);
6371 } // .. else there is an implit base.
George Burgess IV177399e2017-01-09 04:12:14 +00006372 AddMethodTemplateCandidate(
6373 FunTmpl, F.getPair(),
6374 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Erik Verbruggenf1898cf2017-03-28 07:22:21 +00006375 ExplicitTemplateArgs, ObjectType, ObjectClassification,
6376 Args.slice(1), CandidateSet, SuppressUserConversions,
6377 PartialOverloading);
6378 } else {
John McCalla0296f72010-03-19 07:35:19 +00006379 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smithbcc22fc2012-03-09 08:00:36 +00006380 ExplicitTemplateArgs, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006381 CandidateSet, SuppressUserConversions,
6382 PartialOverloading);
Erik Verbruggenf1898cf2017-03-28 07:22:21 +00006383 }
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006384 }
Douglas Gregor15448f82009-06-27 21:05:07 +00006385 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006386}
6387
John McCallf0f1cf02009-11-17 07:50:12 +00006388/// AddMethodCandidate - Adds a named decl (which is some kind of
6389/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00006390void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006391 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006392 Expr::Classification ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00006393 ArrayRef<Expr *> Args,
John McCallf0f1cf02009-11-17 07:50:12 +00006394 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006395 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00006396 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00006397 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00006398
6399 if (isa<UsingShadowDecl>(Decl))
6400 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006401
John McCallf0f1cf02009-11-17 07:50:12 +00006402 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6403 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6404 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00006405 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
George Burgess IVce6284b2017-01-28 02:19:40 +00006406 /*ExplicitArgs*/ nullptr, ObjectType,
6407 ObjectClassification, Args, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006408 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00006409 } else {
John McCalla0296f72010-03-19 07:35:19 +00006410 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
George Burgess IVce6284b2017-01-28 02:19:40 +00006411 ObjectType, ObjectClassification, Args, CandidateSet,
6412 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00006413 }
6414}
6415
Douglas Gregor436424c2008-11-18 23:14:02 +00006416/// AddMethodCandidate - Adds the given C++ member function to the set
6417/// of candidate functions, using the given function call arguments
6418/// and the object argument (@c Object). For example, in a call
6419/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6420/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6421/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00006422/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00006423void
John McCalla0296f72010-03-19 07:35:19 +00006424Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00006425 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006426 Expr::Classification ObjectClassification,
George Burgess IVce6284b2017-01-28 02:19:40 +00006427 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006428 OverloadCandidateSet &CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006429 bool SuppressUserConversions,
Richard Smith6eedfe72017-01-09 08:01:21 +00006430 bool PartialOverloading,
6431 ConversionSequenceList EarlyConversions) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006432 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00006433 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00006434 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00006435 assert(!isa<CXXConstructorDecl>(Method) &&
6436 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00006437
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006438 if (!CandidateSet.isNewCandidate(Method))
6439 return;
6440
Richard Smith8b86f2d2013-11-04 01:48:18 +00006441 // C++11 [class.copy]p23: [DR1402]
6442 // A defaulted move assignment operator that is defined as deleted is
6443 // ignored by overload resolution.
6444 if (Method->isDefaulted() && Method->isDeleted() &&
6445 Method->isMoveAssignmentOperator())
6446 return;
6447
Douglas Gregor27381f32009-11-23 12:27:39 +00006448 // Overload resolution is always an unevaluated context.
Faisal Valid143a0c2017-04-01 21:30:49 +00006449 EnterExpressionEvaluationContext Unevaluated(
6450 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006451
Douglas Gregor436424c2008-11-18 23:14:02 +00006452 // Add this candidate
Richard Smith6eedfe72017-01-09 08:01:21 +00006453 OverloadCandidate &Candidate =
6454 CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
John McCalla0296f72010-03-19 07:35:19 +00006455 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00006456 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006457 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006458 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006459 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor436424c2008-11-18 23:14:02 +00006460
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006461 unsigned NumParams = Proto->getNumParams();
Douglas Gregor436424c2008-11-18 23:14:02 +00006462
6463 // (C++ 13.3.2p2): A candidate function having fewer than m
6464 // parameters is viable only if it has an ellipsis in its parameter
6465 // list (8.3.5).
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006466 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6467 !Proto->isVariadic()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006468 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006469 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00006470 return;
6471 }
6472
6473 // (C++ 13.3.2p2): A candidate function having more than m parameters
6474 // is viable only if the (m+1)st parameter has a default argument
6475 // (8.3.6). For the purposes of overload resolution, the
6476 // parameter list is truncated on the right, so that there are
6477 // exactly m parameters.
6478 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006479 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006480 // Not enough arguments.
6481 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006482 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00006483 return;
6484 }
6485
6486 Candidate.Viable = true;
Douglas Gregor436424c2008-11-18 23:14:02 +00006487
John McCall6e9f8f62009-12-03 04:06:58 +00006488 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006489 // The implicit object argument is ignored.
6490 Candidate.IgnoreObjectArgument = true;
6491 else {
6492 // Determine the implicit conversion sequence for the object
6493 // parameter.
Richard Smith0f59cb32015-12-18 21:45:41 +00006494 Candidate.Conversions[0] = TryObjectArgumentInitialization(
6495 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6496 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00006497 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006498 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006499 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006500 return;
6501 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006502 }
6503
Eli Bendersky291a57e2014-09-25 23:59:08 +00006504 // (CUDA B.1): Check for invalid calls between targets.
6505 if (getLangOpts().CUDA)
6506 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
Justin Lebarb0080032016-08-10 01:09:11 +00006507 if (!IsAllowedCUDACall(Caller, Method)) {
Eli Bendersky291a57e2014-09-25 23:59:08 +00006508 Candidate.Viable = false;
6509 Candidate.FailureKind = ovl_fail_bad_target;
6510 return;
6511 }
6512
Douglas Gregor436424c2008-11-18 23:14:02 +00006513 // Determine the implicit conversion sequences for each of the
6514 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006515 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Richard Smith6eedfe72017-01-09 08:01:21 +00006516 if (Candidate.Conversions[ArgIdx + 1].isInitialized()) {
6517 // We already formed a conversion sequence for this parameter during
6518 // template argument deduction.
6519 } else if (ArgIdx < NumParams) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006520 // (C++ 13.3.2p3): for F to be a viable function, there shall
6521 // exist for each argument an implicit conversion sequence
6522 // (13.3.3.1) that converts that argument to the corresponding
6523 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00006524 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00006525 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006526 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006527 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00006528 /*InOverloadResolution=*/true,
6529 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006530 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00006531 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006532 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006533 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006534 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00006535 }
6536 } else {
6537 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6538 // argument for which there is no corresponding parameter is
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006539 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006540 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00006541 }
6542 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006543
6544 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6545 Candidate.Viable = false;
6546 Candidate.FailureKind = ovl_fail_enable_if;
6547 Candidate.DeductionFailure.Data = FailedAttr;
6548 return;
6549 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006550}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006551
Douglas Gregor97628d62009-08-21 00:16:32 +00006552/// \brief Add a C++ member function template as a candidate to the candidate
6553/// set, using template argument deduction to produce an appropriate member
6554/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00006555void
Douglas Gregor97628d62009-08-21 00:16:32 +00006556Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00006557 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006558 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006559 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006560 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006561 Expr::Classification ObjectClassification,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006562 ArrayRef<Expr *> Args,
Douglas Gregor97628d62009-08-21 00:16:32 +00006563 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006564 bool SuppressUserConversions,
6565 bool PartialOverloading) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006566 if (!CandidateSet.isNewCandidate(MethodTmpl))
6567 return;
6568
Douglas Gregor97628d62009-08-21 00:16:32 +00006569 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00006570 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00006571 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00006572 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00006573 // candidate functions in the usual way.113) A given name can refer to one
6574 // or more function templates and also to a set of overloaded non-template
6575 // functions. In such a case, the candidate functions generated from each
6576 // function template are combined with the set of non-template candidate
6577 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00006578 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006579 FunctionDecl *Specialization = nullptr;
Richard Smith6eedfe72017-01-09 08:01:21 +00006580 ConversionSequenceList Conversions;
6581 if (TemplateDeductionResult Result = DeduceTemplateArguments(
6582 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
6583 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6584 return CheckNonDependentConversions(
6585 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
6586 SuppressUserConversions, ActingContext, ObjectType,
6587 ObjectClassification);
6588 })) {
6589 OverloadCandidate &Candidate =
6590 CandidateSet.addCandidate(Conversions.size(), Conversions);
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006591 Candidate.FoundDecl = FoundDecl;
6592 Candidate.Function = MethodTmpl->getTemplatedDecl();
6593 Candidate.Viable = false;
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006594 Candidate.IsSurrogate = false;
Richard Smith9d05e152017-01-10 20:52:50 +00006595 Candidate.IgnoreObjectArgument =
6596 cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
6597 ObjectType.isNull();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006598 Candidate.ExplicitCallArguments = Args.size();
Richard Smith6eedfe72017-01-09 08:01:21 +00006599 if (Result == TDK_NonDependentConversionFailure)
6600 Candidate.FailureKind = ovl_fail_bad_conversion;
6601 else {
6602 Candidate.FailureKind = ovl_fail_bad_deduction;
6603 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6604 Info);
6605 }
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006606 return;
6607 }
Mike Stump11289f42009-09-09 15:08:12 +00006608
Douglas Gregor97628d62009-08-21 00:16:32 +00006609 // Add the function template specialization produced by template argument
6610 // deduction as a candidate.
6611 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00006612 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00006613 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00006614 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
George Burgess IVce6284b2017-01-28 02:19:40 +00006615 ActingContext, ObjectType, ObjectClassification, Args,
6616 CandidateSet, SuppressUserConversions, PartialOverloading,
6617 Conversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00006618}
6619
Douglas Gregor05155d82009-08-21 23:19:43 +00006620/// \brief Add a C++ function template specialization as a candidate
6621/// in the candidate set, using template argument deduction to produce
6622/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00006623void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006624Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00006625 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006626 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006627 ArrayRef<Expr *> Args,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +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(FunctionTemplate))
6632 return;
6633
Douglas Gregorad3f2fc2009-06-25 22:08:12 +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 Gregorad3f2fc2009-06-25 22:08:12 +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 Gregorad3f2fc2009-06-25 22:08:12 +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 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
6648 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6649 return CheckNonDependentConversions(FunctionTemplate, ParamTypes,
6650 Args, CandidateSet, Conversions,
6651 SuppressUserConversions);
6652 })) {
6653 OverloadCandidate &Candidate =
6654 CandidateSet.addCandidate(Conversions.size(), Conversions);
John McCalla0296f72010-03-19 07:35:19 +00006655 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00006656 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6657 Candidate.Viable = false;
6658 Candidate.IsSurrogate = false;
Richard Smith9d05e152017-01-10 20:52:50 +00006659 // Ignore the object argument if there is one, since we don't have an object
6660 // type.
6661 Candidate.IgnoreObjectArgument =
6662 isa<CXXMethodDecl>(Candidate.Function) &&
6663 !isa<CXXConstructorDecl>(Candidate.Function);
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006664 Candidate.ExplicitCallArguments = Args.size();
Richard Smith6eedfe72017-01-09 08:01:21 +00006665 if (Result == TDK_NonDependentConversionFailure)
6666 Candidate.FailureKind = ovl_fail_bad_conversion;
6667 else {
6668 Candidate.FailureKind = ovl_fail_bad_deduction;
6669 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6670 Info);
6671 }
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006672 return;
6673 }
Mike Stump11289f42009-09-09 15:08:12 +00006674
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006675 // Add the function template specialization produced by template argument
6676 // deduction as a candidate.
6677 assert(Specialization && "Missing function template specialization?");
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006678 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Richard Smith6eedfe72017-01-09 08:01:21 +00006679 SuppressUserConversions, PartialOverloading,
6680 /*AllowExplicit*/false, Conversions);
6681}
6682
6683/// Check that implicit conversion sequences can be formed for each argument
6684/// whose corresponding parameter has a non-dependent type, per DR1391's
6685/// [temp.deduct.call]p10.
6686bool Sema::CheckNonDependentConversions(
6687 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
6688 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
6689 ConversionSequenceList &Conversions, bool SuppressUserConversions,
6690 CXXRecordDecl *ActingContext, QualType ObjectType,
6691 Expr::Classification ObjectClassification) {
6692 // FIXME: The cases in which we allow explicit conversions for constructor
6693 // arguments never consider calling a constructor template. It's not clear
6694 // that is correct.
6695 const bool AllowExplicit = false;
6696
6697 auto *FD = FunctionTemplate->getTemplatedDecl();
6698 auto *Method = dyn_cast<CXXMethodDecl>(FD);
6699 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
6700 unsigned ThisConversions = HasThisConversion ? 1 : 0;
6701
6702 Conversions =
6703 CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
6704
6705 // Overload resolution is always an unevaluated context.
Faisal Valid143a0c2017-04-01 21:30:49 +00006706 EnterExpressionEvaluationContext Unevaluated(
6707 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Richard Smith6eedfe72017-01-09 08:01:21 +00006708
6709 // For a method call, check the 'this' conversion here too. DR1391 doesn't
6710 // require that, but this check should never result in a hard error, and
6711 // overload resolution is permitted to sidestep instantiations.
6712 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
6713 !ObjectType.isNull()) {
6714 Conversions[0] = TryObjectArgumentInitialization(
6715 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6716 Method, ActingContext);
6717 if (Conversions[0].isBad())
6718 return true;
6719 }
6720
6721 for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N;
6722 ++I) {
6723 QualType ParamType = ParamTypes[I];
6724 if (!ParamType->isDependentType()) {
6725 Conversions[ThisConversions + I]
6726 = TryCopyInitialization(*this, Args[I], ParamType,
6727 SuppressUserConversions,
6728 /*InOverloadResolution=*/true,
6729 /*AllowObjCWritebackConversion=*/
6730 getLangOpts().ObjCAutoRefCount,
6731 AllowExplicit);
6732 if (Conversions[ThisConversions + I].isBad())
6733 return true;
6734 }
6735 }
6736
6737 return false;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006738}
Mike Stump11289f42009-09-09 15:08:12 +00006739
Douglas Gregor4b60a152013-11-07 22:34:54 +00006740/// Determine whether this is an allowable conversion from the result
6741/// of an explicit conversion operator to the expected type, per C++
6742/// [over.match.conv]p1 and [over.match.ref]p1.
6743///
6744/// \param ConvType The return type of the conversion function.
6745///
6746/// \param ToType The type we are converting to.
6747///
6748/// \param AllowObjCPointerConversion Allow a conversion from one
6749/// Objective-C pointer to another.
6750///
6751/// \returns true if the conversion is allowable, false otherwise.
6752static bool isAllowableExplicitConversion(Sema &S,
6753 QualType ConvType, QualType ToType,
6754 bool AllowObjCPointerConversion) {
6755 QualType ToNonRefType = ToType.getNonReferenceType();
6756
6757 // Easy case: the types are the same.
6758 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6759 return true;
6760
6761 // Allow qualification conversions.
6762 bool ObjCLifetimeConversion;
6763 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6764 ObjCLifetimeConversion))
6765 return true;
6766
6767 // If we're not allowed to consider Objective-C pointer conversions,
6768 // we're done.
6769 if (!AllowObjCPointerConversion)
6770 return false;
6771
6772 // Is this an Objective-C pointer conversion?
6773 bool IncompatibleObjC = false;
6774 QualType ConvertedType;
6775 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6776 IncompatibleObjC);
6777}
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00006778
Douglas Gregora1f013e2008-11-07 22:36:19 +00006779/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00006780/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00006781/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00006782/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00006783/// (which may or may not be the same type as the type that the
6784/// conversion function produces).
6785void
6786Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006787 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006788 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00006789 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006790 OverloadCandidateSet& CandidateSet,
6791 bool AllowObjCConversionOnExplicit) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006792 assert(!Conversion->getDescribedFunctionTemplate() &&
6793 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00006794 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006795 if (!CandidateSet.isNewCandidate(Conversion))
6796 return;
6797
Richard Smith2a7d4812013-05-04 07:00:32 +00006798 // If the conversion function has an undeduced return type, trigger its
6799 // deduction now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006800 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00006801 if (DeduceReturnType(Conversion, From->getExprLoc()))
6802 return;
6803 ConvType = Conversion->getConversionType().getNonReferenceType();
6804 }
6805
Richard Smith089c3162013-09-21 21:55:46 +00006806 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6807 // operator is only a candidate if its return type is the target type or
6808 // can be converted to the target type with a qualification conversion.
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00006809 if (Conversion->isExplicit() &&
6810 !isAllowableExplicitConversion(*this, ConvType, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006811 AllowObjCConversionOnExplicit))
Richard Smith089c3162013-09-21 21:55:46 +00006812 return;
6813
Douglas Gregor27381f32009-11-23 12:27:39 +00006814 // Overload resolution is always an unevaluated context.
Faisal Valid143a0c2017-04-01 21:30:49 +00006815 EnterExpressionEvaluationContext Unevaluated(
6816 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006817
Douglas Gregora1f013e2008-11-07 22:36:19 +00006818 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006819 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCalla0296f72010-03-19 07:35:19 +00006820 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006821 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006822 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006823 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006824 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00006825 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00006826 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00006827 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006828 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006829
Douglas Gregor6affc782010-08-19 15:37:02 +00006830 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006831 // For conversion functions, the function is considered to be a member of
6832 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00006833 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006834 //
6835 // Determine the implicit conversion sequence for the implicit
6836 // object parameter.
6837 QualType ImplicitParamType = From->getType();
6838 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6839 ImplicitParamType = FromPtrType->getPointeeType();
6840 CXXRecordDecl *ConversionContext
6841 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006842
Richard Smith0f59cb32015-12-18 21:45:41 +00006843 Candidate.Conversions[0] = TryObjectArgumentInitialization(
6844 *this, CandidateSet.getLocation(), From->getType(),
6845 From->Classify(Context), Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006846
John McCall0d1da222010-01-12 00:44:57 +00006847 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006848 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006849 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006850 return;
6851 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006852
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006853 // We won't go through a user-defined type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006854 // derived to base as such conversions are given Conversion Rank. They only
6855 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6856 QualType FromCanon
6857 = Context.getCanonicalType(From->getType().getUnqualifiedType());
6858 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
Richard Smith0f59cb32015-12-18 21:45:41 +00006859 if (FromCanon == ToCanon ||
6860 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006861 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006862 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006863 return;
6864 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006865
Douglas Gregora1f013e2008-11-07 22:36:19 +00006866 // To determine what the conversion from the result of calling the
6867 // conversion function to the type we're eventually trying to
6868 // convert to (ToType), we need to synthesize a call to the
6869 // conversion function and attempt copy initialization from it. This
6870 // makes sure that we get the right semantics with respect to
6871 // lvalues/rvalues and the type. Fortunately, we can allocate this
6872 // call on the stack and we don't need its arguments to be
6873 // well-formed.
John McCall113bee02012-03-10 09:33:50 +00006874 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00006875 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00006876 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6877 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00006878 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00006879 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00006880
Richard Smith48d24642011-07-13 22:53:21 +00006881 QualType ConversionType = Conversion->getConversionType();
Richard Smithdb0ac552015-12-18 22:40:25 +00006882 if (!isCompleteType(From->getLocStart(), ConversionType)) {
Douglas Gregor72ebdab2010-11-13 19:36:57 +00006883 Candidate.Viable = false;
6884 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6885 return;
6886 }
6887
Richard Smith48d24642011-07-13 22:53:21 +00006888 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCall7decc9e2010-11-18 06:31:45 +00006889
Mike Stump11289f42009-09-09 15:08:12 +00006890 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00006891 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6892 // allocator).
Richard Smith48d24642011-07-13 22:53:21 +00006893 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00006894 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00006895 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00006896 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006897 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00006898 /*SuppressUserConversions=*/true,
John McCall31168b02011-06-15 23:02:42 +00006899 /*InOverloadResolution=*/false,
6900 /*AllowObjCWritebackConversion=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00006901
John McCall0d1da222010-01-12 00:44:57 +00006902 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006903 case ImplicitConversionSequence::StandardConversion:
6904 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006905
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006906 // C++ [over.ics.user]p3:
6907 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006908 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006909 // shall have exact match rank.
6910 if (Conversion->getPrimaryTemplate() &&
6911 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6912 Candidate.Viable = false;
6913 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006914 return;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006915 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006916
Douglas Gregorcba72b12011-01-21 05:18:22 +00006917 // C++0x [dcl.init.ref]p5:
6918 // In the second case, if the reference is an rvalue reference and
6919 // the second standard conversion sequence of the user-defined
6920 // conversion sequence includes an lvalue-to-rvalue conversion, the
6921 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006922 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00006923 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6924 Candidate.Viable = false;
6925 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006926 return;
Douglas Gregorcba72b12011-01-21 05:18:22 +00006927 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00006928 break;
6929
6930 case ImplicitConversionSequence::BadConversion:
6931 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006932 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006933 return;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006934
6935 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006936 llvm_unreachable(
Douglas Gregora1f013e2008-11-07 22:36:19 +00006937 "Can only end up with a standard conversion sequence or failure");
6938 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006939
Craig Topper5fc8fc22014-08-27 06:28:36 +00006940 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006941 Candidate.Viable = false;
6942 Candidate.FailureKind = ovl_fail_enable_if;
6943 Candidate.DeductionFailure.Data = FailedAttr;
6944 return;
6945 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00006946}
6947
Douglas Gregor05155d82009-08-21 23:19:43 +00006948/// \brief Adds a conversion function template specialization
6949/// candidate to the overload set, using template argument deduction
6950/// to deduce the template arguments of the conversion function
6951/// template from the type that we are converting to (C++
6952/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00006953void
Douglas Gregor05155d82009-08-21 23:19:43 +00006954Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00006955 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006956 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00006957 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006958 OverloadCandidateSet &CandidateSet,
6959 bool AllowObjCConversionOnExplicit) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006960 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
6961 "Only conversion function templates permitted here");
6962
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006963 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6964 return;
6965
Craig Toppere6706e42012-09-19 02:26:47 +00006966 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006967 CXXConversionDecl *Specialization = nullptr;
Douglas Gregor05155d82009-08-21 23:19:43 +00006968 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00006969 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00006970 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006971 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006972 Candidate.FoundDecl = FoundDecl;
6973 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6974 Candidate.Viable = false;
6975 Candidate.FailureKind = ovl_fail_bad_deduction;
6976 Candidate.IsSurrogate = false;
6977 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006978 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006979 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006980 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00006981 return;
6982 }
Mike Stump11289f42009-09-09 15:08:12 +00006983
Douglas Gregor05155d82009-08-21 23:19:43 +00006984 // Add the conversion function template specialization produced by
6985 // template argument deduction as a candidate.
6986 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00006987 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006988 CandidateSet, AllowObjCConversionOnExplicit);
Douglas Gregor05155d82009-08-21 23:19:43 +00006989}
6990
Douglas Gregorab7897a2008-11-19 22:57:39 +00006991/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
6992/// converts the given @c Object to a function pointer via the
6993/// conversion function @c Conversion, and then attempts to call it
6994/// with the given arguments (C++ [over.call.object]p2-4). Proto is
6995/// the type of function that we'll eventually be calling.
6996void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006997 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006998 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006999 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00007000 Expr *Object,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007001 ArrayRef<Expr *> Args,
Douglas Gregorab7897a2008-11-19 22:57:39 +00007002 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00007003 if (!CandidateSet.isNewCandidate(Conversion))
7004 return;
7005
Douglas Gregor27381f32009-11-23 12:27:39 +00007006 // Overload resolution is always an unevaluated context.
Faisal Valid143a0c2017-04-01 21:30:49 +00007007 EnterExpressionEvaluationContext Unevaluated(
7008 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00007009
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00007010 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00007011 Candidate.FoundDecl = FoundDecl;
Craig Topperc3ec1492014-05-26 06:22:03 +00007012 Candidate.Function = nullptr;
Douglas Gregorab7897a2008-11-19 22:57:39 +00007013 Candidate.Surrogate = Conversion;
7014 Candidate.Viable = true;
7015 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007016 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00007017 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregorab7897a2008-11-19 22:57:39 +00007018
7019 // Determine the implicit conversion sequence for the implicit
7020 // object parameter.
Richard Smith0f59cb32015-12-18 21:45:41 +00007021 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
7022 *this, CandidateSet.getLocation(), Object->getType(),
7023 Object->Classify(Context), Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00007024 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00007025 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00007026 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00007027 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00007028 return;
7029 }
7030
7031 // The first conversion is actually a user-defined conversion whose
7032 // first conversion is ObjectInit's standard conversion (which is
7033 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00007034 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00007035 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00007036 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00007037 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00007038 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00007039 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump11289f42009-09-09 15:08:12 +00007040 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00007041 = Candidate.Conversions[0].UserDefined.Before;
7042 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
7043
Mike Stump11289f42009-09-09 15:08:12 +00007044 // Find the
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00007045 unsigned NumParams = Proto->getNumParams();
Douglas Gregorab7897a2008-11-19 22:57:39 +00007046
7047 // (C++ 13.3.2p2): A candidate function having fewer than m
7048 // parameters is viable only if it has an ellipsis in its parameter
7049 // list (8.3.5).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00007050 if (Args.size() > NumParams && !Proto->isVariadic()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00007051 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00007052 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00007053 return;
7054 }
7055
7056 // Function types don't have any default arguments, so just check if
7057 // we have enough arguments.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00007058 if (Args.size() < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00007059 // Not enough arguments.
7060 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00007061 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00007062 return;
7063 }
7064
7065 // Determine the implicit conversion sequences for each of the
7066 // arguments.
Richard Smithe54c3072013-05-05 15:51:06 +00007067 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00007068 if (ArgIdx < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00007069 // (C++ 13.3.2p3): for F to be a viable function, there shall
7070 // exist for each argument an implicit conversion sequence
7071 // (13.3.3.1) that converts that argument to the corresponding
7072 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00007073 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00007074 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00007075 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00007076 /*SuppressUserConversions=*/false,
John McCall31168b02011-06-15 23:02:42 +00007077 /*InOverloadResolution=*/false,
7078 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00007079 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00007080 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00007081 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00007082 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007083 return;
Douglas Gregorab7897a2008-11-19 22:57:39 +00007084 }
7085 } else {
7086 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7087 // argument for which there is no corresponding parameter is
7088 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00007089 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00007090 }
7091 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007092
Craig Topper5fc8fc22014-08-27 06:28:36 +00007093 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007094 Candidate.Viable = false;
7095 Candidate.FailureKind = ovl_fail_enable_if;
7096 Candidate.DeductionFailure.Data = FailedAttr;
7097 return;
7098 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00007099}
7100
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007101/// \brief Add overload candidates for overloaded operators that are
7102/// member functions.
7103///
7104/// Add the overloaded operator candidates that are member functions
7105/// for the operator Op that was used in an operator expression such
7106/// as "x Op y". , Args/NumArgs provides the operator arguments, and
7107/// CandidateSet will store the added overload candidates. (C++
7108/// [over.match.oper]).
7109void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
7110 SourceLocation OpLoc,
Richard Smithe54c3072013-05-05 15:51:06 +00007111 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007112 OverloadCandidateSet& CandidateSet,
7113 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00007114 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7115
7116 // C++ [over.match.oper]p3:
7117 // For a unary operator @ with an operand of a type whose
7118 // cv-unqualified version is T1, and for a binary operator @ with
7119 // a left operand of a type whose cv-unqualified version is T1 and
7120 // a right operand of a type whose cv-unqualified version is T2,
7121 // three sets of candidate functions, designated member
7122 // candidates, non-member candidates and built-in candidates, are
7123 // constructed as follows:
7124 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00007125
Richard Smith0feaf0c2013-04-20 12:41:22 +00007126 // -- If T1 is a complete class type or a class currently being
7127 // defined, the set of member candidates is the result of the
7128 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
7129 // the set of member candidates is empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007130 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Richard Smith0feaf0c2013-04-20 12:41:22 +00007131 // Complete the type if it can be completed.
Richard Smithdb0ac552015-12-18 22:40:25 +00007132 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
Richard Smith82b8d4e2015-12-18 22:19:11 +00007133 return;
Richard Smith0feaf0c2013-04-20 12:41:22 +00007134 // If the type is neither complete nor being defined, bail out now.
7135 if (!T1Rec->getDecl()->getDefinition())
Douglas Gregor6a1f9652009-08-27 23:35:55 +00007136 return;
Mike Stump11289f42009-09-09 15:08:12 +00007137
John McCall27b18f82009-11-17 02:14:36 +00007138 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
7139 LookupQualifiedName(Operators, T1Rec->getDecl());
7140 Operators.suppressDiagnostics();
7141
Mike Stump11289f42009-09-09 15:08:12 +00007142 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00007143 OperEnd = Operators.end();
7144 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00007145 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00007146 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
George Burgess IVce6284b2017-01-28 02:19:40 +00007147 Args[0]->Classify(Context), Args.slice(1),
George Burgess IV177399e2017-01-09 04:12:14 +00007148 CandidateSet, /*SuppressUserConversions=*/false);
Douglas Gregor436424c2008-11-18 23:14:02 +00007149 }
Douglas Gregor436424c2008-11-18 23:14:02 +00007150}
7151
Douglas Gregora11693b2008-11-12 17:17:38 +00007152/// AddBuiltinCandidate - Add a candidate for a built-in
7153/// operator. ResultTy and ParamTys are the result and parameter types
7154/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00007155/// arguments being passed to the candidate. IsAssignmentOperator
7156/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00007157/// operator. NumContextualBoolArguments is the number of arguments
7158/// (at the beginning of the argument list) that will be contextually
7159/// converted to bool.
George Burgess IVc07c3892017-06-08 18:19:25 +00007160void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
Douglas Gregorc5e61072009-01-13 00:52:54 +00007161 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00007162 bool IsAssignmentOperator,
7163 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00007164 // Overload resolution is always an unevaluated context.
Faisal Valid143a0c2017-04-01 21:30:49 +00007165 EnterExpressionEvaluationContext Unevaluated(
7166 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00007167
Douglas Gregora11693b2008-11-12 17:17:38 +00007168 // Add this candidate
Richard Smithe54c3072013-05-05 15:51:06 +00007169 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
Craig Topperc3ec1492014-05-26 06:22:03 +00007170 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
7171 Candidate.Function = nullptr;
Douglas Gregor1d248c52008-12-12 02:00:36 +00007172 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007173 Candidate.IgnoreObjectArgument = false;
George Burgess IV5f6ab9a2017-06-08 20:55:21 +00007174 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
Douglas Gregora11693b2008-11-12 17:17:38 +00007175
7176 // Determine the implicit conversion sequences for each of the
7177 // arguments.
7178 Candidate.Viable = true;
Richard Smithe54c3072013-05-05 15:51:06 +00007179 Candidate.ExplicitCallArguments = Args.size();
7180 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00007181 // C++ [over.match.oper]p4:
7182 // For the built-in assignment operators, conversions of the
7183 // left operand are restricted as follows:
7184 // -- no temporaries are introduced to hold the left operand, and
7185 // -- no user-defined conversions are applied to the left
7186 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00007187 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00007188 //
7189 // We block these conversions by turning off user-defined
7190 // conversions, since that is the only way that initialization of
7191 // a reference to a non-class type can occur from something that
7192 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00007193 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00007194 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00007195 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00007196 Candidate.Conversions[ArgIdx]
7197 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00007198 } else {
Mike Stump11289f42009-09-09 15:08:12 +00007199 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00007200 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00007201 ArgIdx == 0 && IsAssignmentOperator,
John McCall31168b02011-06-15 23:02:42 +00007202 /*InOverloadResolution=*/false,
7203 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00007204 getLangOpts().ObjCAutoRefCount);
Douglas Gregor5fb53972009-01-14 15:45:31 +00007205 }
John McCall0d1da222010-01-12 00:44:57 +00007206 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007207 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00007208 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00007209 break;
7210 }
Douglas Gregora11693b2008-11-12 17:17:38 +00007211 }
7212}
7213
Craig Toppercd7b0332013-07-01 06:29:40 +00007214namespace {
7215
Douglas Gregora11693b2008-11-12 17:17:38 +00007216/// BuiltinCandidateTypeSet - A set of types that will be used for the
7217/// candidate operator functions for built-in operators (C++
7218/// [over.built]). The types are separated into pointer types and
7219/// enumeration types.
7220class BuiltinCandidateTypeSet {
7221 /// TypeSet - A set of types.
Richard Smith95853072016-03-25 00:08:53 +00007222 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
7223 llvm::SmallPtrSet<QualType, 8>> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00007224
7225 /// PointerTypes - The set of pointer types that will be used in the
7226 /// built-in candidates.
7227 TypeSet PointerTypes;
7228
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007229 /// MemberPointerTypes - The set of member pointer types that will be
7230 /// used in the built-in candidates.
7231 TypeSet MemberPointerTypes;
7232
Douglas Gregora11693b2008-11-12 17:17:38 +00007233 /// EnumerationTypes - The set of enumeration types that will be
7234 /// used in the built-in candidates.
7235 TypeSet EnumerationTypes;
7236
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007237 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007238 /// candidates.
7239 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00007240
7241 /// \brief A flag indicating non-record types are viable candidates
7242 bool HasNonRecordTypes;
7243
7244 /// \brief A flag indicating whether either arithmetic or enumeration types
7245 /// were present in the candidate set.
7246 bool HasArithmeticOrEnumeralTypes;
7247
Douglas Gregor80af3132011-05-21 23:15:46 +00007248 /// \brief A flag indicating whether the nullptr type was present in the
7249 /// candidate set.
7250 bool HasNullPtrType;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00007251
Douglas Gregor8a2e6012009-08-24 15:23:48 +00007252 /// Sema - The semantic analysis instance where we are building the
7253 /// candidate type set.
7254 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00007255
Douglas Gregora11693b2008-11-12 17:17:38 +00007256 /// Context - The AST context in which we will build the type sets.
7257 ASTContext &Context;
7258
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007259 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7260 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007261 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00007262
7263public:
7264 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00007265 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00007266
Mike Stump11289f42009-09-09 15:08:12 +00007267 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00007268 : HasNonRecordTypes(false),
7269 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor80af3132011-05-21 23:15:46 +00007270 HasNullPtrType(false),
Chandler Carruth00a38332010-12-13 01:44:01 +00007271 SemaRef(SemaRef),
7272 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00007273
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007274 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007275 SourceLocation Loc,
7276 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007277 bool AllowExplicitConversions,
7278 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00007279
7280 /// pointer_begin - First pointer type found;
7281 iterator pointer_begin() { return PointerTypes.begin(); }
7282
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007283 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00007284 iterator pointer_end() { return PointerTypes.end(); }
7285
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007286 /// member_pointer_begin - First member pointer type found;
7287 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
7288
7289 /// member_pointer_end - Past the last member pointer type found;
7290 iterator member_pointer_end() { return MemberPointerTypes.end(); }
7291
Douglas Gregora11693b2008-11-12 17:17:38 +00007292 /// enumeration_begin - First enumeration type found;
7293 iterator enumeration_begin() { return EnumerationTypes.begin(); }
7294
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007295 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00007296 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007297
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007298 iterator vector_begin() { return VectorTypes.begin(); }
7299 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00007300
7301 bool hasNonRecordTypes() { return HasNonRecordTypes; }
7302 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor80af3132011-05-21 23:15:46 +00007303 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregora11693b2008-11-12 17:17:38 +00007304};
7305
Craig Toppercd7b0332013-07-01 06:29:40 +00007306} // end anonymous namespace
7307
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007308/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00007309/// the set of pointer types along with any more-qualified variants of
7310/// that type. For example, if @p Ty is "int const *", this routine
7311/// will add "int const *", "int const volatile *", "int const
7312/// restrict *", and "int const volatile restrict *" to the set of
7313/// pointer types. Returns true if the add of @p Ty itself succeeded,
7314/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00007315///
7316/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007317bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007318BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7319 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00007320
Douglas Gregora11693b2008-11-12 17:17:38 +00007321 // Insert this type.
Richard Smith95853072016-03-25 00:08:53 +00007322 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00007323 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007324
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00007325 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00007326 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00007327 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00007328 if (!PointerTy) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00007329 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7330 PointeeTy = PTy->getPointeeType();
7331 buildObjCPtr = true;
7332 } else {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00007333 PointeeTy = PointerTy->getPointeeType();
Douglas Gregor5bee2582012-06-04 00:15:09 +00007334 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00007335
Sebastian Redl4990a632009-11-18 20:39:26 +00007336 // Don't add qualified variants of arrays. For one, they're not allowed
7337 // (the qualifier would sink to the element type), and for another, the
7338 // only overload situation where it matters is subscript or pointer +- int,
7339 // and those shouldn't have qualifier variants anyway.
7340 if (PointeeTy->isArrayType())
7341 return true;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00007342
John McCall8ccfcb52009-09-24 19:53:00 +00007343 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007344 bool hasVolatile = VisibleQuals.hasVolatile();
7345 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007346
John McCall8ccfcb52009-09-24 19:53:00 +00007347 // Iterate through all strict supersets of BaseCVR.
7348 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7349 if ((CVR | BaseCVR) != CVR) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00007350 // Skip over volatile if no volatile found anywhere in the types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007351 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00007352
Douglas Gregor5bee2582012-06-04 00:15:09 +00007353 // Skip over restrict if no restrict found anywhere in the types, or if
7354 // the type cannot be restrict-qualified.
7355 if ((CVR & Qualifiers::Restrict) &&
7356 (!hasRestrict ||
7357 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7358 continue;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00007359
Douglas Gregor5bee2582012-06-04 00:15:09 +00007360 // Build qualified pointee type.
John McCall8ccfcb52009-09-24 19:53:00 +00007361 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00007362
Douglas Gregor5bee2582012-06-04 00:15:09 +00007363 // Build qualified pointer type.
7364 QualType QPointerTy;
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00007365 if (!buildObjCPtr)
Douglas Gregor5bee2582012-06-04 00:15:09 +00007366 QPointerTy = Context.getPointerType(QPointeeTy);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00007367 else
Douglas Gregor5bee2582012-06-04 00:15:09 +00007368 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00007369
Douglas Gregor5bee2582012-06-04 00:15:09 +00007370 // Insert qualified pointer type.
7371 PointerTypes.insert(QPointerTy);
Douglas Gregora11693b2008-11-12 17:17:38 +00007372 }
7373
7374 return true;
7375}
7376
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007377/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7378/// to the set of pointer types along with any more-qualified variants of
7379/// that type. For example, if @p Ty is "int const *", this routine
7380/// will add "int const *", "int const volatile *", "int const
7381/// restrict *", and "int const volatile restrict *" to the set of
7382/// pointer types. Returns true if the add of @p Ty itself succeeded,
7383/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00007384///
7385/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007386bool
7387BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7388 QualType Ty) {
7389 // Insert this type.
Richard Smith95853072016-03-25 00:08:53 +00007390 if (!MemberPointerTypes.insert(Ty))
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007391 return false;
7392
John McCall8ccfcb52009-09-24 19:53:00 +00007393 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
7394 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007395
John McCall8ccfcb52009-09-24 19:53:00 +00007396 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00007397 // Don't add qualified variants of arrays. For one, they're not allowed
7398 // (the qualifier would sink to the element type), and for another, the
7399 // only overload situation where it matters is subscript or pointer +- int,
7400 // and those shouldn't have qualifier variants anyway.
7401 if (PointeeTy->isArrayType())
7402 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00007403 const Type *ClassTy = PointerTy->getClass();
7404
7405 // Iterate through all strict supersets of the pointee type's CVR
7406 // qualifiers.
7407 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7408 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7409 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007410
John McCall8ccfcb52009-09-24 19:53:00 +00007411 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00007412 MemberPointerTypes.insert(
7413 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007414 }
7415
7416 return true;
7417}
7418
Douglas Gregora11693b2008-11-12 17:17:38 +00007419/// AddTypesConvertedFrom - Add each of the types to which the type @p
7420/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007421/// primarily interested in pointer types and enumeration types. We also
7422/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00007423/// AllowUserConversions is true if we should look at the conversion
7424/// functions of a class type, and AllowExplicitConversions if we
7425/// should also include the explicit conversion functions of a class
7426/// type.
Mike Stump11289f42009-09-09 15:08:12 +00007427void
Douglas Gregor5fb53972009-01-14 15:45:31 +00007428BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007429 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00007430 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007431 bool AllowExplicitConversions,
7432 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007433 // Only deal with canonical types.
7434 Ty = Context.getCanonicalType(Ty);
7435
7436 // Look through reference types; they aren't part of the type of an
7437 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007438 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00007439 Ty = RefTy->getPointeeType();
7440
John McCall33ddac02011-01-19 10:06:00 +00007441 // If we're dealing with an array type, decay to the pointer.
7442 if (Ty->isArrayType())
7443 Ty = SemaRef.Context.getArrayDecayedType(Ty);
7444
7445 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007446 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00007447
Chandler Carruth00a38332010-12-13 01:44:01 +00007448 // Flag if we ever add a non-record type.
7449 const RecordType *TyRec = Ty->getAs<RecordType>();
7450 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7451
Chandler Carruth00a38332010-12-13 01:44:01 +00007452 // Flag if we encounter an arithmetic type.
7453 HasArithmeticOrEnumeralTypes =
7454 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7455
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00007456 if (Ty->isObjCIdType() || Ty->isObjCClassType())
7457 PointerTypes.insert(Ty);
7458 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007459 // Insert our type, and its more-qualified variants, into the set
7460 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007461 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00007462 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007463 } else if (Ty->isMemberPointerType()) {
7464 // Member pointers are far easier, since the pointee can't be converted.
7465 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7466 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00007467 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007468 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00007469 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007470 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007471 // We treat vector types as arithmetic types in many contexts as an
7472 // extension.
7473 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007474 VectorTypes.insert(Ty);
Douglas Gregor80af3132011-05-21 23:15:46 +00007475 } else if (Ty->isNullPtrType()) {
7476 HasNullPtrType = true;
Chandler Carruth00a38332010-12-13 01:44:01 +00007477 } else if (AllowUserConversions && TyRec) {
7478 // No conversion functions in incomplete types.
Richard Smithdb0ac552015-12-18 22:40:25 +00007479 if (!SemaRef.isCompleteType(Loc, Ty))
Chandler Carruth00a38332010-12-13 01:44:01 +00007480 return;
Mike Stump11289f42009-09-09 15:08:12 +00007481
Chandler Carruth00a38332010-12-13 01:44:01 +00007482 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00007483 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007484 if (isa<UsingShadowDecl>(D))
7485 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00007486
Chandler Carruth00a38332010-12-13 01:44:01 +00007487 // Skip conversion function templates; they don't tell us anything
7488 // about which builtin types we can convert to.
7489 if (isa<FunctionTemplateDecl>(D))
7490 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00007491
Chandler Carruth00a38332010-12-13 01:44:01 +00007492 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7493 if (AllowExplicitConversions || !Conv->isExplicit()) {
7494 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7495 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00007496 }
7497 }
7498 }
7499}
7500
Douglas Gregor84605ae2009-08-24 13:43:27 +00007501/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
7502/// the volatile- and non-volatile-qualified assignment operators for the
7503/// given type to the candidate set.
7504static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7505 QualType T,
Richard Smithe54c3072013-05-05 15:51:06 +00007506 ArrayRef<Expr *> Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00007507 OverloadCandidateSet &CandidateSet) {
7508 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00007509
Douglas Gregor84605ae2009-08-24 13:43:27 +00007510 // T& operator=(T&, T)
7511 ParamTypes[0] = S.Context.getLValueReferenceType(T);
7512 ParamTypes[1] = T;
George Burgess IVc07c3892017-06-08 18:19:25 +00007513 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Douglas Gregor84605ae2009-08-24 13:43:27 +00007514 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00007515
Douglas Gregor84605ae2009-08-24 13:43:27 +00007516 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7517 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00007518 ParamTypes[0]
7519 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00007520 ParamTypes[1] = T;
George Burgess IVc07c3892017-06-08 18:19:25 +00007521 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00007522 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00007523 }
7524}
Mike Stump11289f42009-09-09 15:08:12 +00007525
Sebastian Redl1054fae2009-10-25 17:03:50 +00007526/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7527/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007528static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7529 Qualifiers VRQuals;
7530 const RecordType *TyRec;
7531 if (const MemberPointerType *RHSMPType =
7532 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00007533 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007534 else
7535 TyRec = ArgExpr->getType()->getAs<RecordType>();
7536 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007537 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007538 VRQuals.addVolatile();
7539 VRQuals.addRestrict();
7540 return VRQuals;
7541 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007542
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007543 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00007544 if (!ClassDecl->hasDefinition())
7545 return VRQuals;
7546
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00007547 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
John McCallda4458e2010-03-31 01:36:47 +00007548 if (isa<UsingShadowDecl>(D))
7549 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7550 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007551 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7552 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7553 CanTy = ResTypeRef->getPointeeType();
7554 // Need to go down the pointer/mempointer chain and add qualifiers
7555 // as see them.
7556 bool done = false;
7557 while (!done) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00007558 if (CanTy.isRestrictQualified())
7559 VRQuals.addRestrict();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007560 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7561 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007562 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007563 CanTy->getAs<MemberPointerType>())
7564 CanTy = ResTypeMPtr->getPointeeType();
7565 else
7566 done = true;
7567 if (CanTy.isVolatileQualified())
7568 VRQuals.addVolatile();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007569 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7570 return VRQuals;
7571 }
7572 }
7573 }
7574 return VRQuals;
7575}
John McCall52872982010-11-13 05:51:15 +00007576
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007577namespace {
John McCall52872982010-11-13 05:51:15 +00007578
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007579/// \brief Helper class to manage the addition of builtin operator overload
7580/// candidates. It provides shared state and utility methods used throughout
7581/// the process, as well as a helper method to add each group of builtin
7582/// operator overloads from the standard to a candidate set.
7583class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007584 // Common instance state available to all overload candidate addition methods.
7585 Sema &S;
Richard Smithe54c3072013-05-05 15:51:06 +00007586 ArrayRef<Expr *> Args;
Chandler Carruthc6586e52010-12-12 10:35:00 +00007587 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00007588 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007589 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruthc6586e52010-12-12 10:35:00 +00007590 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007591
Chandler Carruthc6586e52010-12-12 10:35:00 +00007592 // Define some constants used to index and iterate over the arithemetic types
7593 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00007594 // The "promoted arithmetic types" are the arithmetic
7595 // types are that preserved by promotion (C++ [over.built]p2).
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00007596 static const unsigned FirstIntegralType = 4;
7597 static const unsigned LastIntegralType = 21;
7598 static const unsigned FirstPromotedIntegralType = 4,
7599 LastPromotedIntegralType = 12;
John McCall52872982010-11-13 05:51:15 +00007600 static const unsigned FirstPromotedArithmeticType = 0,
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00007601 LastPromotedArithmeticType = 12;
7602 static const unsigned NumArithmeticTypes = 21;
John McCall52872982010-11-13 05:51:15 +00007603
Chandler Carruthc6586e52010-12-12 10:35:00 +00007604 /// \brief Get the canonical type for a given arithmetic type index.
7605 CanQualType getArithmeticType(unsigned index) {
7606 assert(index < NumArithmeticTypes);
7607 static CanQualType ASTContext::* const
7608 ArithmeticTypes[NumArithmeticTypes] = {
7609 // Start of promoted types.
7610 &ASTContext::FloatTy,
7611 &ASTContext::DoubleTy,
7612 &ASTContext::LongDoubleTy,
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00007613 &ASTContext::Float128Ty,
John McCall52872982010-11-13 05:51:15 +00007614
Chandler Carruthc6586e52010-12-12 10:35:00 +00007615 // Start of integral types.
7616 &ASTContext::IntTy,
7617 &ASTContext::LongTy,
7618 &ASTContext::LongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00007619 &ASTContext::Int128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00007620 &ASTContext::UnsignedIntTy,
7621 &ASTContext::UnsignedLongTy,
7622 &ASTContext::UnsignedLongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00007623 &ASTContext::UnsignedInt128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00007624 // End of promoted types.
7625
7626 &ASTContext::BoolTy,
7627 &ASTContext::CharTy,
7628 &ASTContext::WCharTy,
7629 &ASTContext::Char16Ty,
7630 &ASTContext::Char32Ty,
7631 &ASTContext::SignedCharTy,
7632 &ASTContext::ShortTy,
7633 &ASTContext::UnsignedCharTy,
7634 &ASTContext::UnsignedShortTy,
7635 // End of integral types.
Richard Smith521ecc12012-06-10 08:00:26 +00007636 // FIXME: What about complex? What about half?
Chandler Carruthc6586e52010-12-12 10:35:00 +00007637 };
7638 return S.Context.*ArithmeticTypes[index];
7639 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007640
Chandler Carruth5659c0c2010-12-12 09:22:45 +00007641 /// \brief Helper method to factor out the common pattern of adding overloads
7642 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007643 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007644 bool HasVolatile,
7645 bool HasRestrict) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007646 QualType ParamTypes[2] = {
7647 S.Context.getLValueReferenceType(CandidateTy),
7648 S.Context.IntTy
7649 };
7650
7651 // Non-volatile version.
George Burgess IVc07c3892017-06-08 18:19:25 +00007652 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007653
7654 // Use a heuristic to reduce number of builtin candidates in the set:
7655 // add volatile version only if there are conversions to a volatile type.
7656 if (HasVolatile) {
7657 ParamTypes[0] =
7658 S.Context.getLValueReferenceType(
7659 S.Context.getVolatileType(CandidateTy));
George Burgess IVc07c3892017-06-08 18:19:25 +00007660 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007661 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00007662
Douglas Gregor5bee2582012-06-04 00:15:09 +00007663 // Add restrict version only if there are conversions to a restrict type
7664 // and our candidate type is a non-restrict-qualified pointer.
7665 if (HasRestrict && CandidateTy->isAnyPointerType() &&
7666 !CandidateTy.isRestrictQualified()) {
7667 ParamTypes[0]
7668 = S.Context.getLValueReferenceType(
7669 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
George Burgess IVc07c3892017-06-08 18:19:25 +00007670 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00007671
Douglas Gregor5bee2582012-06-04 00:15:09 +00007672 if (HasVolatile) {
7673 ParamTypes[0]
7674 = S.Context.getLValueReferenceType(
7675 S.Context.getCVRQualifiedType(CandidateTy,
7676 (Qualifiers::Volatile |
7677 Qualifiers::Restrict)));
George Burgess IVc07c3892017-06-08 18:19:25 +00007678 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007679 }
7680 }
7681
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007682 }
7683
7684public:
7685 BuiltinOperatorOverloadBuilder(
Richard Smithe54c3072013-05-05 15:51:06 +00007686 Sema &S, ArrayRef<Expr *> Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007687 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00007688 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007689 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007690 OverloadCandidateSet &CandidateSet)
Richard Smithe54c3072013-05-05 15:51:06 +00007691 : S(S), Args(Args),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007692 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00007693 HasArithmeticOrEnumeralCandidateType(
7694 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007695 CandidateTypes(CandidateTypes),
7696 CandidateSet(CandidateSet) {
7697 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007698 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007699 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007700 assert(getArithmeticType(LastPromotedIntegralType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00007701 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007702 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007703 assert(getArithmeticType(FirstPromotedArithmeticType)
7704 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007705 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007706 assert(getArithmeticType(LastPromotedArithmeticType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00007707 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007708 "Invalid last promoted arithmetic type");
7709 }
7710
7711 // C++ [over.built]p3:
7712 //
7713 // For every pair (T, VQ), where T is an arithmetic type, and VQ
7714 // is either volatile or empty, there exist candidate operator
7715 // functions of the form
7716 //
7717 // VQ T& operator++(VQ T&);
7718 // T operator++(VQ T&, int);
7719 //
7720 // C++ [over.built]p4:
7721 //
7722 // For every pair (T, VQ), where T is an arithmetic type other
7723 // than bool, and VQ is either volatile or empty, there exist
7724 // candidate operator functions of the form
7725 //
7726 // VQ T& operator--(VQ T&);
7727 // T operator--(VQ T&, int);
7728 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007729 if (!HasArithmeticOrEnumeralCandidateType)
7730 return;
7731
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007732 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
7733 Arith < NumArithmeticTypes; ++Arith) {
7734 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00007735 getArithmeticType(Arith),
Douglas Gregor5bee2582012-06-04 00:15:09 +00007736 VisibleTypeConversionsQuals.hasVolatile(),
7737 VisibleTypeConversionsQuals.hasRestrict());
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007738 }
7739 }
7740
7741 // C++ [over.built]p5:
7742 //
7743 // For every pair (T, VQ), where T is a cv-qualified or
7744 // cv-unqualified object type, and VQ is either volatile or
7745 // empty, there exist candidate operator functions of the form
7746 //
7747 // T*VQ& operator++(T*VQ&);
7748 // T*VQ& operator--(T*VQ&);
7749 // T* operator++(T*VQ&, int);
7750 // T* operator--(T*VQ&, int);
7751 void addPlusPlusMinusMinusPointerOverloads() {
7752 for (BuiltinCandidateTypeSet::iterator
7753 Ptr = CandidateTypes[0].pointer_begin(),
7754 PtrEnd = CandidateTypes[0].pointer_end();
7755 Ptr != PtrEnd; ++Ptr) {
7756 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00007757 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007758 continue;
7759
7760 addPlusPlusMinusMinusStyleOverloads(*Ptr,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007761 (!(*Ptr).isVolatileQualified() &&
7762 VisibleTypeConversionsQuals.hasVolatile()),
7763 (!(*Ptr).isRestrictQualified() &&
7764 VisibleTypeConversionsQuals.hasRestrict()));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007765 }
7766 }
7767
7768 // C++ [over.built]p6:
7769 // For every cv-qualified or cv-unqualified object type T, there
7770 // exist candidate operator functions of the form
7771 //
7772 // T& operator*(T*);
7773 //
7774 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007775 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00007776 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007777 // T& operator*(T*);
7778 void addUnaryStarPointerOverloads() {
7779 for (BuiltinCandidateTypeSet::iterator
7780 Ptr = CandidateTypes[0].pointer_begin(),
7781 PtrEnd = CandidateTypes[0].pointer_end();
7782 Ptr != PtrEnd; ++Ptr) {
7783 QualType ParamTy = *Ptr;
7784 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007785 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7786 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007787
Douglas Gregor02824322011-01-26 19:30:28 +00007788 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7789 if (Proto->getTypeQuals() || Proto->getRefQualifier())
7790 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007791
George Burgess IVc07c3892017-06-08 18:19:25 +00007792 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007793 }
7794 }
7795
7796 // C++ [over.built]p9:
7797 // For every promoted arithmetic type T, there exist candidate
7798 // operator functions of the form
7799 //
7800 // T operator+(T);
7801 // T operator-(T);
7802 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007803 if (!HasArithmeticOrEnumeralCandidateType)
7804 return;
7805
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007806 for (unsigned Arith = FirstPromotedArithmeticType;
7807 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007808 QualType ArithTy = getArithmeticType(Arith);
George Burgess IVc07c3892017-06-08 18:19:25 +00007809 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007810 }
7811
7812 // Extension: We also add these operators for vector types.
7813 for (BuiltinCandidateTypeSet::iterator
7814 Vec = CandidateTypes[0].vector_begin(),
7815 VecEnd = CandidateTypes[0].vector_end();
7816 Vec != VecEnd; ++Vec) {
7817 QualType VecTy = *Vec;
George Burgess IVc07c3892017-06-08 18:19:25 +00007818 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007819 }
7820 }
7821
7822 // C++ [over.built]p8:
7823 // For every type T, there exist candidate operator functions of
7824 // the form
7825 //
7826 // T* operator+(T*);
7827 void addUnaryPlusPointerOverloads() {
7828 for (BuiltinCandidateTypeSet::iterator
7829 Ptr = CandidateTypes[0].pointer_begin(),
7830 PtrEnd = CandidateTypes[0].pointer_end();
7831 Ptr != PtrEnd; ++Ptr) {
7832 QualType ParamTy = *Ptr;
George Burgess IVc07c3892017-06-08 18:19:25 +00007833 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007834 }
7835 }
7836
7837 // C++ [over.built]p10:
7838 // For every promoted integral type T, there exist candidate
7839 // operator functions of the form
7840 //
7841 // T operator~(T);
7842 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007843 if (!HasArithmeticOrEnumeralCandidateType)
7844 return;
7845
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007846 for (unsigned Int = FirstPromotedIntegralType;
7847 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007848 QualType IntTy = getArithmeticType(Int);
George Burgess IVc07c3892017-06-08 18:19:25 +00007849 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007850 }
7851
7852 // Extension: We also add this operator for vector types.
7853 for (BuiltinCandidateTypeSet::iterator
7854 Vec = CandidateTypes[0].vector_begin(),
7855 VecEnd = CandidateTypes[0].vector_end();
7856 Vec != VecEnd; ++Vec) {
7857 QualType VecTy = *Vec;
George Burgess IVc07c3892017-06-08 18:19:25 +00007858 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007859 }
7860 }
7861
7862 // C++ [over.match.oper]p16:
Richard Smith5e9746f2016-10-21 22:00:42 +00007863 // For every pointer to member type T or type std::nullptr_t, there
7864 // exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007865 //
7866 // bool operator==(T,T);
7867 // bool operator!=(T,T);
Richard Smith5e9746f2016-10-21 22:00:42 +00007868 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007869 /// Set of (canonical) types that we've already handled.
7870 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7871
Richard Smithe54c3072013-05-05 15:51:06 +00007872 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007873 for (BuiltinCandidateTypeSet::iterator
7874 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7875 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7876 MemPtr != MemPtrEnd;
7877 ++MemPtr) {
7878 // Don't add the same builtin candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007879 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007880 continue;
7881
7882 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
George Burgess IVc07c3892017-06-08 18:19:25 +00007883 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007884 }
Richard Smith5e9746f2016-10-21 22:00:42 +00007885
7886 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7887 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7888 if (AddedTypes.insert(NullPtrTy).second) {
7889 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
George Burgess IVc07c3892017-06-08 18:19:25 +00007890 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Richard Smith5e9746f2016-10-21 22:00:42 +00007891 }
7892 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007893 }
7894 }
7895
7896 // C++ [over.built]p15:
7897 //
Richard Smith5e9746f2016-10-21 22:00:42 +00007898 // For every T, where T is an enumeration type or a pointer type,
7899 // there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007900 //
7901 // bool operator<(T, T);
7902 // bool operator>(T, T);
7903 // bool operator<=(T, T);
7904 // bool operator>=(T, T);
7905 // bool operator==(T, T);
7906 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007907 void addRelationalPointerOrEnumeralOverloads() {
Eli Friedman14f082b2012-09-18 21:52:24 +00007908 // C++ [over.match.oper]p3:
7909 // [...]the built-in candidates include all of the candidate operator
7910 // functions defined in 13.6 that, compared to the given operator, [...]
7911 // do not have the same parameter-type-list as any non-template non-member
7912 // candidate.
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007913 //
Eli Friedman14f082b2012-09-18 21:52:24 +00007914 // Note that in practice, this only affects enumeration types because there
7915 // aren't any built-in candidates of record type, and a user-defined operator
7916 // must have an operand of record or enumeration type. Also, the only other
7917 // overloaded operator with enumeration arguments, operator=,
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007918 // cannot be overloaded for enumeration types, so this is the only place
7919 // where we must suppress candidates like this.
7920 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7921 UserDefinedBinaryOperators;
7922
Richard Smithe54c3072013-05-05 15:51:06 +00007923 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007924 if (CandidateTypes[ArgIdx].enumeration_begin() !=
7925 CandidateTypes[ArgIdx].enumeration_end()) {
7926 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7927 CEnd = CandidateSet.end();
7928 C != CEnd; ++C) {
7929 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7930 continue;
7931
Eli Friedman14f082b2012-09-18 21:52:24 +00007932 if (C->Function->isFunctionTemplateSpecialization())
7933 continue;
7934
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007935 QualType FirstParamType =
7936 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7937 QualType SecondParamType =
7938 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7939
7940 // Skip if either parameter isn't of enumeral type.
7941 if (!FirstParamType->isEnumeralType() ||
7942 !SecondParamType->isEnumeralType())
7943 continue;
7944
7945 // Add this operator to the set of known user-defined operators.
7946 UserDefinedBinaryOperators.insert(
7947 std::make_pair(S.Context.getCanonicalType(FirstParamType),
7948 S.Context.getCanonicalType(SecondParamType)));
7949 }
7950 }
7951 }
7952
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007953 /// Set of (canonical) types that we've already handled.
7954 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7955
Richard Smithe54c3072013-05-05 15:51:06 +00007956 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007957 for (BuiltinCandidateTypeSet::iterator
7958 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7959 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7960 Ptr != PtrEnd; ++Ptr) {
7961 // Don't add the same builtin candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007962 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007963 continue;
7964
7965 QualType ParamTypes[2] = { *Ptr, *Ptr };
George Burgess IVc07c3892017-06-08 18:19:25 +00007966 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007967 }
7968 for (BuiltinCandidateTypeSet::iterator
7969 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7970 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7971 Enum != EnumEnd; ++Enum) {
7972 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
7973
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007974 // Don't add the same builtin candidate twice, or if a user defined
7975 // candidate exists.
David Blaikie82e95a32014-11-19 07:49:47 +00007976 if (!AddedTypes.insert(CanonType).second ||
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007977 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
7978 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007979 continue;
7980
7981 QualType ParamTypes[2] = { *Enum, *Enum };
George Burgess IVc07c3892017-06-08 18:19:25 +00007982 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007983 }
7984 }
7985 }
7986
7987 // C++ [over.built]p13:
7988 //
7989 // For every cv-qualified or cv-unqualified object type T
7990 // there exist candidate operator functions of the form
7991 //
7992 // T* operator+(T*, ptrdiff_t);
7993 // T& operator[](T*, ptrdiff_t); [BELOW]
7994 // T* operator-(T*, ptrdiff_t);
7995 // T* operator+(ptrdiff_t, T*);
7996 // T& operator[](ptrdiff_t, T*); [BELOW]
7997 //
7998 // C++ [over.built]p14:
7999 //
8000 // For every T, where T is a pointer to object type, there
8001 // exist candidate operator functions of the form
8002 //
8003 // ptrdiff_t operator-(T, T);
8004 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
8005 /// Set of (canonical) types that we've already handled.
8006 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8007
8008 for (int Arg = 0; Arg < 2; ++Arg) {
Eric Christopher9207a522015-08-21 16:24:01 +00008009 QualType AsymmetricParamTypes[2] = {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008010 S.Context.getPointerDiffType(),
8011 S.Context.getPointerDiffType(),
8012 };
8013 for (BuiltinCandidateTypeSet::iterator
8014 Ptr = CandidateTypes[Arg].pointer_begin(),
8015 PtrEnd = CandidateTypes[Arg].pointer_end();
8016 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00008017 QualType PointeeTy = (*Ptr)->getPointeeType();
8018 if (!PointeeTy->isObjectType())
8019 continue;
8020
Eric Christopher9207a522015-08-21 16:24:01 +00008021 AsymmetricParamTypes[Arg] = *Ptr;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008022 if (Arg == 0 || Op == OO_Plus) {
8023 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
8024 // T* operator+(ptrdiff_t, T*);
George Burgess IVc07c3892017-06-08 18:19:25 +00008025 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008026 }
8027 if (Op == OO_Minus) {
8028 // ptrdiff_t operator-(T, T);
David Blaikie82e95a32014-11-19 07:49:47 +00008029 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008030 continue;
8031
8032 QualType ParamTypes[2] = { *Ptr, *Ptr };
George Burgess IVc07c3892017-06-08 18:19:25 +00008033 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008034 }
8035 }
8036 }
8037 }
8038
8039 // C++ [over.built]p12:
8040 //
8041 // For every pair of promoted arithmetic types L and R, there
8042 // exist candidate operator functions of the form
8043 //
8044 // LR operator*(L, R);
8045 // LR operator/(L, R);
8046 // LR operator+(L, R);
8047 // LR operator-(L, R);
8048 // bool operator<(L, R);
8049 // bool operator>(L, R);
8050 // bool operator<=(L, R);
8051 // bool operator>=(L, R);
8052 // bool operator==(L, R);
8053 // bool operator!=(L, R);
8054 //
8055 // where LR is the result of the usual arithmetic conversions
8056 // between types L and R.
8057 //
8058 // C++ [over.built]p24:
8059 //
8060 // For every pair of promoted arithmetic types L and R, there exist
8061 // candidate operator functions of the form
8062 //
8063 // LR operator?(bool, L, R);
8064 //
8065 // where LR is the result of the usual arithmetic conversions
8066 // between types L and R.
8067 // Our candidates ignore the first parameter.
George Burgess IVc07c3892017-06-08 18:19:25 +00008068 void addGenericBinaryArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00008069 if (!HasArithmeticOrEnumeralCandidateType)
8070 return;
8071
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008072 for (unsigned Left = FirstPromotedArithmeticType;
8073 Left < LastPromotedArithmeticType; ++Left) {
8074 for (unsigned Right = FirstPromotedArithmeticType;
8075 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00008076 QualType LandR[2] = { getArithmeticType(Left),
8077 getArithmeticType(Right) };
George Burgess IVc07c3892017-06-08 18:19:25 +00008078 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008079 }
8080 }
8081
8082 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
8083 // conditional operator for vector types.
8084 for (BuiltinCandidateTypeSet::iterator
8085 Vec1 = CandidateTypes[0].vector_begin(),
8086 Vec1End = CandidateTypes[0].vector_end();
8087 Vec1 != Vec1End; ++Vec1) {
8088 for (BuiltinCandidateTypeSet::iterator
8089 Vec2 = CandidateTypes[1].vector_begin(),
8090 Vec2End = CandidateTypes[1].vector_end();
8091 Vec2 != Vec2End; ++Vec2) {
8092 QualType LandR[2] = { *Vec1, *Vec2 };
George Burgess IVc07c3892017-06-08 18:19:25 +00008093 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008094 }
8095 }
8096 }
8097
8098 // C++ [over.built]p17:
8099 //
8100 // For every pair of promoted integral types L and R, there
8101 // exist candidate operator functions of the form
8102 //
8103 // LR operator%(L, R);
8104 // LR operator&(L, R);
8105 // LR operator^(L, R);
8106 // LR operator|(L, R);
8107 // L operator<<(L, R);
8108 // L operator>>(L, R);
8109 //
8110 // where LR is the result of the usual arithmetic conversions
8111 // between types L and R.
8112 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00008113 if (!HasArithmeticOrEnumeralCandidateType)
8114 return;
8115
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008116 for (unsigned Left = FirstPromotedIntegralType;
8117 Left < LastPromotedIntegralType; ++Left) {
8118 for (unsigned Right = FirstPromotedIntegralType;
8119 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00008120 QualType LandR[2] = { getArithmeticType(Left),
8121 getArithmeticType(Right) };
George Burgess IVc07c3892017-06-08 18:19:25 +00008122 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008123 }
8124 }
8125 }
8126
8127 // C++ [over.built]p20:
8128 //
8129 // For every pair (T, VQ), where T is an enumeration or
8130 // pointer to member type and VQ is either volatile or
8131 // empty, there exist candidate operator functions of the form
8132 //
8133 // VQ T& operator=(VQ T&, T);
8134 void addAssignmentMemberPointerOrEnumeralOverloads() {
8135 /// Set of (canonical) types that we've already handled.
8136 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8137
8138 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8139 for (BuiltinCandidateTypeSet::iterator
8140 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8141 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8142 Enum != EnumEnd; ++Enum) {
David Blaikie82e95a32014-11-19 07:49:47 +00008143 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008144 continue;
8145
Richard Smithe54c3072013-05-05 15:51:06 +00008146 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008147 }
8148
8149 for (BuiltinCandidateTypeSet::iterator
8150 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8151 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8152 MemPtr != MemPtrEnd; ++MemPtr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008153 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008154 continue;
8155
Richard Smithe54c3072013-05-05 15:51:06 +00008156 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008157 }
8158 }
8159 }
8160
8161 // C++ [over.built]p19:
8162 //
8163 // For every pair (T, VQ), where T is any type and VQ is either
8164 // volatile or empty, there exist candidate operator functions
8165 // of the form
8166 //
8167 // T*VQ& operator=(T*VQ&, T*);
8168 //
8169 // C++ [over.built]p21:
8170 //
8171 // For every pair (T, VQ), where T is a cv-qualified or
8172 // cv-unqualified object type and VQ is either volatile or
8173 // empty, there exist candidate operator functions of the form
8174 //
8175 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
8176 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
8177 void addAssignmentPointerOverloads(bool isEqualOp) {
8178 /// Set of (canonical) types that we've already handled.
8179 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8180
8181 for (BuiltinCandidateTypeSet::iterator
8182 Ptr = CandidateTypes[0].pointer_begin(),
8183 PtrEnd = CandidateTypes[0].pointer_end();
8184 Ptr != PtrEnd; ++Ptr) {
8185 // If this is operator=, keep track of the builtin candidates we added.
8186 if (isEqualOp)
8187 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00008188 else if (!(*Ptr)->getPointeeType()->isObjectType())
8189 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008190
8191 // non-volatile version
8192 QualType ParamTypes[2] = {
8193 S.Context.getLValueReferenceType(*Ptr),
8194 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
8195 };
George Burgess IVc07c3892017-06-08 18:19:25 +00008196 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008197 /*IsAssigmentOperator=*/ isEqualOp);
8198
Douglas Gregor5bee2582012-06-04 00:15:09 +00008199 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8200 VisibleTypeConversionsQuals.hasVolatile();
8201 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008202 // volatile version
8203 ParamTypes[0] =
8204 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
George Burgess IVc07c3892017-06-08 18:19:25 +00008205 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008206 /*IsAssigmentOperator=*/isEqualOp);
8207 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00008208
Douglas Gregor5bee2582012-06-04 00:15:09 +00008209 if (!(*Ptr).isRestrictQualified() &&
8210 VisibleTypeConversionsQuals.hasRestrict()) {
8211 // restrict version
8212 ParamTypes[0]
8213 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
George Burgess IVc07c3892017-06-08 18:19:25 +00008214 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00008215 /*IsAssigmentOperator=*/isEqualOp);
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00008216
Douglas Gregor5bee2582012-06-04 00:15:09 +00008217 if (NeedVolatile) {
8218 // volatile restrict version
8219 ParamTypes[0]
8220 = S.Context.getLValueReferenceType(
8221 S.Context.getCVRQualifiedType(*Ptr,
8222 (Qualifiers::Volatile |
8223 Qualifiers::Restrict)));
George Burgess IVc07c3892017-06-08 18:19:25 +00008224 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00008225 /*IsAssigmentOperator=*/isEqualOp);
8226 }
8227 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008228 }
8229
8230 if (isEqualOp) {
8231 for (BuiltinCandidateTypeSet::iterator
8232 Ptr = CandidateTypes[1].pointer_begin(),
8233 PtrEnd = CandidateTypes[1].pointer_end();
8234 Ptr != PtrEnd; ++Ptr) {
8235 // Make sure we don't add the same candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00008236 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008237 continue;
8238
Chandler Carruth8e543b32010-12-12 08:17:55 +00008239 QualType ParamTypes[2] = {
8240 S.Context.getLValueReferenceType(*Ptr),
8241 *Ptr,
8242 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008243
8244 // non-volatile version
George Burgess IVc07c3892017-06-08 18:19:25 +00008245 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008246 /*IsAssigmentOperator=*/true);
8247
Douglas Gregor5bee2582012-06-04 00:15:09 +00008248 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8249 VisibleTypeConversionsQuals.hasVolatile();
8250 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008251 // volatile version
8252 ParamTypes[0] =
8253 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
George Burgess IVc07c3892017-06-08 18:19:25 +00008254 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Richard Smithe54c3072013-05-05 15:51:06 +00008255 /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008256 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00008257
Douglas Gregor5bee2582012-06-04 00:15:09 +00008258 if (!(*Ptr).isRestrictQualified() &&
8259 VisibleTypeConversionsQuals.hasRestrict()) {
8260 // restrict version
8261 ParamTypes[0]
8262 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
George Burgess IVc07c3892017-06-08 18:19:25 +00008263 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Richard Smithe54c3072013-05-05 15:51:06 +00008264 /*IsAssigmentOperator=*/true);
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00008265
Douglas Gregor5bee2582012-06-04 00:15:09 +00008266 if (NeedVolatile) {
8267 // volatile restrict version
8268 ParamTypes[0]
8269 = S.Context.getLValueReferenceType(
8270 S.Context.getCVRQualifiedType(*Ptr,
8271 (Qualifiers::Volatile |
8272 Qualifiers::Restrict)));
George Burgess IVc07c3892017-06-08 18:19:25 +00008273 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Richard Smithe54c3072013-05-05 15:51:06 +00008274 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00008275 }
8276 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008277 }
8278 }
8279 }
8280
8281 // C++ [over.built]p18:
8282 //
8283 // For every triple (L, VQ, R), where L is an arithmetic type,
8284 // VQ is either volatile or empty, and R is a promoted
8285 // arithmetic type, there exist candidate operator functions of
8286 // the form
8287 //
8288 // VQ L& operator=(VQ L&, R);
8289 // VQ L& operator*=(VQ L&, R);
8290 // VQ L& operator/=(VQ L&, R);
8291 // VQ L& operator+=(VQ L&, R);
8292 // VQ L& operator-=(VQ L&, R);
8293 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00008294 if (!HasArithmeticOrEnumeralCandidateType)
8295 return;
8296
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008297 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
8298 for (unsigned Right = FirstPromotedArithmeticType;
8299 Right < LastPromotedArithmeticType; ++Right) {
8300 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00008301 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008302
8303 // Add this built-in operator as a candidate (VQ is empty).
8304 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00008305 S.Context.getLValueReferenceType(getArithmeticType(Left));
George Burgess IVc07c3892017-06-08 18:19:25 +00008306 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008307 /*IsAssigmentOperator=*/isEqualOp);
8308
8309 // Add this built-in operator as a candidate (VQ is 'volatile').
8310 if (VisibleTypeConversionsQuals.hasVolatile()) {
8311 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00008312 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008313 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
George Burgess IVc07c3892017-06-08 18:19:25 +00008314 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008315 /*IsAssigmentOperator=*/isEqualOp);
8316 }
8317 }
8318 }
8319
8320 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8321 for (BuiltinCandidateTypeSet::iterator
8322 Vec1 = CandidateTypes[0].vector_begin(),
8323 Vec1End = CandidateTypes[0].vector_end();
8324 Vec1 != Vec1End; ++Vec1) {
8325 for (BuiltinCandidateTypeSet::iterator
8326 Vec2 = CandidateTypes[1].vector_begin(),
8327 Vec2End = CandidateTypes[1].vector_end();
8328 Vec2 != Vec2End; ++Vec2) {
8329 QualType ParamTypes[2];
8330 ParamTypes[1] = *Vec2;
8331 // Add this built-in operator as a candidate (VQ is empty).
8332 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
George Burgess IVc07c3892017-06-08 18:19:25 +00008333 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008334 /*IsAssigmentOperator=*/isEqualOp);
8335
8336 // Add this built-in operator as a candidate (VQ is 'volatile').
8337 if (VisibleTypeConversionsQuals.hasVolatile()) {
8338 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
8339 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
George Burgess IVc07c3892017-06-08 18:19:25 +00008340 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008341 /*IsAssigmentOperator=*/isEqualOp);
8342 }
8343 }
8344 }
8345 }
8346
8347 // C++ [over.built]p22:
8348 //
8349 // For every triple (L, VQ, R), where L is an integral type, VQ
8350 // is either volatile or empty, and R is a promoted integral
8351 // type, there exist candidate operator functions of the form
8352 //
8353 // VQ L& operator%=(VQ L&, R);
8354 // VQ L& operator<<=(VQ L&, R);
8355 // VQ L& operator>>=(VQ L&, R);
8356 // VQ L& operator&=(VQ L&, R);
8357 // VQ L& operator^=(VQ L&, R);
8358 // VQ L& operator|=(VQ L&, R);
8359 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00008360 if (!HasArithmeticOrEnumeralCandidateType)
8361 return;
8362
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008363 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8364 for (unsigned Right = FirstPromotedIntegralType;
8365 Right < LastPromotedIntegralType; ++Right) {
8366 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00008367 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008368
8369 // Add this built-in operator as a candidate (VQ is empty).
8370 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00008371 S.Context.getLValueReferenceType(getArithmeticType(Left));
George Burgess IVc07c3892017-06-08 18:19:25 +00008372 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008373 if (VisibleTypeConversionsQuals.hasVolatile()) {
8374 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00008375 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008376 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8377 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
George Burgess IVc07c3892017-06-08 18:19:25 +00008378 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008379 }
8380 }
8381 }
8382 }
8383
8384 // C++ [over.operator]p23:
8385 //
8386 // There also exist candidate operator functions of the form
8387 //
8388 // bool operator!(bool);
8389 // bool operator&&(bool, bool);
8390 // bool operator||(bool, bool);
8391 void addExclaimOverload() {
8392 QualType ParamTy = S.Context.BoolTy;
George Burgess IVc07c3892017-06-08 18:19:25 +00008393 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008394 /*IsAssignmentOperator=*/false,
8395 /*NumContextualBoolArguments=*/1);
8396 }
8397 void addAmpAmpOrPipePipeOverload() {
8398 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
George Burgess IVc07c3892017-06-08 18:19:25 +00008399 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008400 /*IsAssignmentOperator=*/false,
8401 /*NumContextualBoolArguments=*/2);
8402 }
8403
8404 // C++ [over.built]p13:
8405 //
8406 // For every cv-qualified or cv-unqualified object type T there
8407 // exist candidate operator functions of the form
8408 //
8409 // T* operator+(T*, ptrdiff_t); [ABOVE]
8410 // T& operator[](T*, ptrdiff_t);
8411 // T* operator-(T*, ptrdiff_t); [ABOVE]
8412 // T* operator+(ptrdiff_t, T*); [ABOVE]
8413 // T& operator[](ptrdiff_t, T*);
8414 void addSubscriptOverloads() {
8415 for (BuiltinCandidateTypeSet::iterator
8416 Ptr = CandidateTypes[0].pointer_begin(),
8417 PtrEnd = CandidateTypes[0].pointer_end();
8418 Ptr != PtrEnd; ++Ptr) {
8419 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8420 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00008421 if (!PointeeType->isObjectType())
8422 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008423
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008424 // T& operator[](T*, ptrdiff_t)
George Burgess IVc07c3892017-06-08 18:19:25 +00008425 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008426 }
8427
8428 for (BuiltinCandidateTypeSet::iterator
8429 Ptr = CandidateTypes[1].pointer_begin(),
8430 PtrEnd = CandidateTypes[1].pointer_end();
8431 Ptr != PtrEnd; ++Ptr) {
8432 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8433 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00008434 if (!PointeeType->isObjectType())
8435 continue;
8436
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008437 // T& operator[](ptrdiff_t, T*)
George Burgess IVc07c3892017-06-08 18:19:25 +00008438 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008439 }
8440 }
8441
8442 // C++ [over.built]p11:
8443 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8444 // C1 is the same type as C2 or is a derived class of C2, T is an object
8445 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8446 // there exist candidate operator functions of the form
8447 //
8448 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8449 //
8450 // where CV12 is the union of CV1 and CV2.
8451 void addArrowStarOverloads() {
8452 for (BuiltinCandidateTypeSet::iterator
8453 Ptr = CandidateTypes[0].pointer_begin(),
8454 PtrEnd = CandidateTypes[0].pointer_end();
8455 Ptr != PtrEnd; ++Ptr) {
8456 QualType C1Ty = (*Ptr);
8457 QualType C1;
8458 QualifierCollector Q1;
8459 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8460 if (!isa<RecordType>(C1))
8461 continue;
8462 // heuristic to reduce number of builtin candidates in the set.
8463 // Add volatile/restrict version only if there are conversions to a
8464 // volatile/restrict type.
8465 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8466 continue;
8467 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8468 continue;
8469 for (BuiltinCandidateTypeSet::iterator
8470 MemPtr = CandidateTypes[1].member_pointer_begin(),
8471 MemPtrEnd = CandidateTypes[1].member_pointer_end();
8472 MemPtr != MemPtrEnd; ++MemPtr) {
8473 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8474 QualType C2 = QualType(mptr->getClass(), 0);
8475 C2 = C2.getUnqualifiedType();
Richard Smith0f59cb32015-12-18 21:45:41 +00008476 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008477 break;
8478 QualType ParamTypes[2] = { *Ptr, *MemPtr };
8479 // build CV12 T&
8480 QualType T = mptr->getPointeeType();
8481 if (!VisibleTypeConversionsQuals.hasVolatile() &&
8482 T.isVolatileQualified())
8483 continue;
8484 if (!VisibleTypeConversionsQuals.hasRestrict() &&
8485 T.isRestrictQualified())
8486 continue;
8487 T = Q1.apply(S.Context, T);
George Burgess IVc07c3892017-06-08 18:19:25 +00008488 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008489 }
8490 }
8491 }
8492
8493 // Note that we don't consider the first argument, since it has been
8494 // contextually converted to bool long ago. The candidates below are
8495 // therefore added as binary.
8496 //
8497 // C++ [over.built]p25:
8498 // For every type T, where T is a pointer, pointer-to-member, or scoped
8499 // enumeration type, there exist candidate operator functions of the form
8500 //
8501 // T operator?(bool, T, T);
8502 //
8503 void addConditionalOperatorOverloads() {
8504 /// Set of (canonical) types that we've already handled.
8505 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8506
8507 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8508 for (BuiltinCandidateTypeSet::iterator
8509 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8510 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8511 Ptr != PtrEnd; ++Ptr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008512 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008513 continue;
8514
8515 QualType ParamTypes[2] = { *Ptr, *Ptr };
George Burgess IVc07c3892017-06-08 18:19:25 +00008516 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008517 }
8518
8519 for (BuiltinCandidateTypeSet::iterator
8520 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8521 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8522 MemPtr != MemPtrEnd; ++MemPtr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008523 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008524 continue;
8525
8526 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
George Burgess IVc07c3892017-06-08 18:19:25 +00008527 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008528 }
8529
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008530 if (S.getLangOpts().CPlusPlus11) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008531 for (BuiltinCandidateTypeSet::iterator
8532 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8533 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8534 Enum != EnumEnd; ++Enum) {
8535 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8536 continue;
8537
David Blaikie82e95a32014-11-19 07:49:47 +00008538 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008539 continue;
8540
8541 QualType ParamTypes[2] = { *Enum, *Enum };
George Burgess IVc07c3892017-06-08 18:19:25 +00008542 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008543 }
8544 }
8545 }
8546 }
8547};
8548
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008549} // end anonymous namespace
8550
8551/// AddBuiltinOperatorCandidates - Add the appropriate built-in
8552/// operator overloads to the candidate set (C++ [over.built]), based
8553/// on the operator @p Op and the arguments given. For example, if the
8554/// operator is a binary '+', this routine might add "int
8555/// operator+(int, int)" to cover integer addition.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00008556void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8557 SourceLocation OpLoc,
8558 ArrayRef<Expr *> Args,
8559 OverloadCandidateSet &CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00008560 // Find all of the types that the arguments can convert to, but only
8561 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00008562 // that make use of these types. Also record whether we encounter non-record
8563 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00008564 Qualifiers VisibleTypeConversionsQuals;
8565 VisibleTypeConversionsQuals.addConst();
Richard Smithe54c3072013-05-05 15:51:06 +00008566 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00008567 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00008568
8569 bool HasNonRecordCandidateType = false;
8570 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008571 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Richard Smithe54c3072013-05-05 15:51:06 +00008572 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Benjamin Kramer57dddd482015-02-17 21:55:18 +00008573 CandidateTypes.emplace_back(*this);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00008574 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8575 OpLoc,
8576 true,
8577 (Op == OO_Exclaim ||
8578 Op == OO_AmpAmp ||
8579 Op == OO_PipePipe),
8580 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00008581 HasNonRecordCandidateType = HasNonRecordCandidateType ||
8582 CandidateTypes[ArgIdx].hasNonRecordTypes();
8583 HasArithmeticOrEnumeralCandidateType =
8584 HasArithmeticOrEnumeralCandidateType ||
8585 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00008586 }
Douglas Gregora11693b2008-11-12 17:17:38 +00008587
Chandler Carruth00a38332010-12-13 01:44:01 +00008588 // Exit early when no non-record types have been added to the candidate set
8589 // for any of the arguments to the operator.
Douglas Gregor877d4eb2011-10-10 14:05:31 +00008590 //
8591 // We can't exit early for !, ||, or &&, since there we have always have
8592 // 'bool' overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00008593 if (!HasNonRecordCandidateType &&
Douglas Gregor877d4eb2011-10-10 14:05:31 +00008594 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth00a38332010-12-13 01:44:01 +00008595 return;
8596
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008597 // Setup an object to manage the common state for building overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00008598 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008599 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00008600 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008601 CandidateTypes, CandidateSet);
8602
8603 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00008604 switch (Op) {
8605 case OO_None:
8606 case NUM_OVERLOADED_OPERATORS:
David Blaikie83d382b2011-09-23 05:06:16 +00008607 llvm_unreachable("Expected an overloaded operator");
Douglas Gregora11693b2008-11-12 17:17:38 +00008608
Chandler Carruth5184de02010-12-12 08:51:33 +00008609 case OO_New:
8610 case OO_Delete:
8611 case OO_Array_New:
8612 case OO_Array_Delete:
8613 case OO_Call:
David Blaikie83d382b2011-09-23 05:06:16 +00008614 llvm_unreachable(
8615 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruth5184de02010-12-12 08:51:33 +00008616
8617 case OO_Comma:
8618 case OO_Arrow:
Richard Smith9f690bd2015-10-27 06:02:45 +00008619 case OO_Coawait:
Chandler Carruth5184de02010-12-12 08:51:33 +00008620 // C++ [over.match.oper]p3:
Richard Smith9f690bd2015-10-27 06:02:45 +00008621 // -- For the operator ',', the unary operator '&', the
8622 // operator '->', or the operator 'co_await', the
8623 // built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00008624 break;
8625
8626 case OO_Plus: // '+' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008627 if (Args.size() == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008628 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00008629 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00008630
8631 case OO_Minus: // '-' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008632 if (Args.size() == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008633 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008634 } else {
8635 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
George Burgess IVc07c3892017-06-08 18:19:25 +00008636 OpBuilder.addGenericBinaryArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008637 }
Douglas Gregord08452f2008-11-19 15:42:04 +00008638 break;
8639
Chandler Carruth5184de02010-12-12 08:51:33 +00008640 case OO_Star: // '*' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008641 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008642 OpBuilder.addUnaryStarPointerOverloads();
8643 else
George Burgess IVc07c3892017-06-08 18:19:25 +00008644 OpBuilder.addGenericBinaryArithmeticOverloads();
Chandler Carruth5184de02010-12-12 08:51:33 +00008645 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008646
Chandler Carruth5184de02010-12-12 08:51:33 +00008647 case OO_Slash:
George Burgess IVc07c3892017-06-08 18:19:25 +00008648 OpBuilder.addGenericBinaryArithmeticOverloads();
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008649 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008650
8651 case OO_PlusPlus:
8652 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008653 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8654 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00008655 break;
8656
Douglas Gregor84605ae2009-08-24 13:43:27 +00008657 case OO_EqualEqual:
8658 case OO_ExclaimEqual:
Richard Smith5e9746f2016-10-21 22:00:42 +00008659 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00008660 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008661
Douglas Gregora11693b2008-11-12 17:17:38 +00008662 case OO_Less:
8663 case OO_Greater:
8664 case OO_LessEqual:
8665 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00008666 OpBuilder.addRelationalPointerOrEnumeralOverloads();
George Burgess IVc07c3892017-06-08 18:19:25 +00008667 OpBuilder.addGenericBinaryArithmeticOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00008668 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008669
Douglas Gregora11693b2008-11-12 17:17:38 +00008670 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00008671 case OO_Caret:
8672 case OO_Pipe:
8673 case OO_LessLess:
8674 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008675 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00008676 break;
8677
Chandler Carruth5184de02010-12-12 08:51:33 +00008678 case OO_Amp: // '&' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008679 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008680 // C++ [over.match.oper]p3:
8681 // -- For the operator ',', the unary operator '&', or the
8682 // operator '->', the built-in candidates set is empty.
8683 break;
8684
8685 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8686 break;
8687
8688 case OO_Tilde:
8689 OpBuilder.addUnaryTildePromotedIntegralOverloads();
8690 break;
8691
Douglas Gregora11693b2008-11-12 17:17:38 +00008692 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008693 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00008694 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00008695
8696 case OO_PlusEqual:
8697 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008698 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008699 // Fall through.
8700
8701 case OO_StarEqual:
8702 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008703 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008704 break;
8705
8706 case OO_PercentEqual:
8707 case OO_LessLessEqual:
8708 case OO_GreaterGreaterEqual:
8709 case OO_AmpEqual:
8710 case OO_CaretEqual:
8711 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008712 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008713 break;
8714
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008715 case OO_Exclaim:
8716 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00008717 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008718
Douglas Gregora11693b2008-11-12 17:17:38 +00008719 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008720 case OO_PipePipe:
8721 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00008722 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008723
8724 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008725 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008726 break;
8727
8728 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008729 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008730 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00008731
8732 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008733 OpBuilder.addConditionalOperatorOverloads();
George Burgess IVc07c3892017-06-08 18:19:25 +00008734 OpBuilder.addGenericBinaryArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008735 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008736 }
8737}
8738
Douglas Gregore254f902009-02-04 00:32:51 +00008739/// \brief Add function candidates found via argument-dependent lookup
8740/// to the set of overloading candidates.
8741///
8742/// This routine performs argument-dependent name lookup based on the
8743/// given function name (which may also be an operator name) and adds
8744/// all of the overload candidates found by ADL to the overload
8745/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00008746void
Douglas Gregore254f902009-02-04 00:32:51 +00008747Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smith100b24a2014-04-17 01:52:14 +00008748 SourceLocation Loc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008749 ArrayRef<Expr *> Args,
Douglas Gregor739b107a2011-03-03 02:41:12 +00008750 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008751 OverloadCandidateSet& CandidateSet,
Richard Smithb6626742012-10-18 17:56:02 +00008752 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00008753 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00008754
John McCall91f61fc2010-01-26 06:04:06 +00008755 // FIXME: This approach for uniquing ADL results (and removing
8756 // redundant candidates from the set) relies on pointer-equality,
8757 // which means we need to key off the canonical decl. However,
8758 // always going back to the canonical decl might not get us the
8759 // right set of default arguments. What default arguments are
8760 // we supposed to consider on ADL candidates, anyway?
8761
Douglas Gregorcabea402009-09-22 15:41:20 +00008762 // FIXME: Pass in the explicit template arguments?
Richard Smith100b24a2014-04-17 01:52:14 +00008763 ArgumentDependentLookup(Name, Loc, Args, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00008764
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008765 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008766 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8767 CandEnd = CandidateSet.end();
8768 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00008769 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00008770 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00008771 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00008772 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00008773 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008774
8775 // For each of the ADL candidates we found, add it to the overload
8776 // set.
John McCall8fe68082010-01-26 07:16:45 +00008777 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00008778 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00008779 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00008780 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00008781 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008782
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008783 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8784 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00008785 } else
John McCall4c4c1df2010-01-26 03:27:55 +00008786 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00008787 FoundDecl, ExplicitTemplateArgs,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00008788 Args, CandidateSet, PartialOverloading);
Douglas Gregor15448f82009-06-27 21:05:07 +00008789 }
Douglas Gregore254f902009-02-04 00:32:51 +00008790}
8791
George Burgess IV3dc166912016-05-10 01:59:34 +00008792namespace {
8793enum class Comparison { Equal, Better, Worse };
8794}
8795
8796/// Compares the enable_if attributes of two FunctionDecls, for the purposes of
8797/// overload resolution.
8798///
8799/// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
8800/// Cand1's first N enable_if attributes have precisely the same conditions as
8801/// Cand2's first N enable_if attributes (where N = the number of enable_if
8802/// attributes on Cand2), and Cand1 has more than N enable_if attributes.
8803///
8804/// Note that you can have a pair of candidates such that Cand1's enable_if
8805/// attributes are worse than Cand2's, and Cand2's enable_if attributes are
8806/// worse than Cand1's.
8807static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
8808 const FunctionDecl *Cand2) {
8809 // Common case: One (or both) decls don't have enable_if attrs.
8810 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
8811 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
8812 if (!Cand1Attr || !Cand2Attr) {
8813 if (Cand1Attr == Cand2Attr)
8814 return Comparison::Equal;
8815 return Cand1Attr ? Comparison::Better : Comparison::Worse;
8816 }
George Burgess IV2a6150d2015-10-16 01:17:38 +00008817
8818 // FIXME: The next several lines are just
8819 // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8820 // instead of reverse order which is how they're stored in the AST.
8821 auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1);
8822 auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2);
8823
George Burgess IV3dc166912016-05-10 01:59:34 +00008824 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
8825 // has fewer enable_if attributes than Cand2.
8826 if (Cand1Attrs.size() < Cand2Attrs.size())
8827 return Comparison::Worse;
George Burgess IV2a6150d2015-10-16 01:17:38 +00008828
8829 auto Cand1I = Cand1Attrs.begin();
8830 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
8831 for (auto &Cand2A : Cand2Attrs) {
8832 Cand1ID.clear();
8833 Cand2ID.clear();
8834
8835 auto &Cand1A = *Cand1I++;
8836 Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true);
8837 Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true);
8838 if (Cand1ID != Cand2ID)
George Burgess IV3dc166912016-05-10 01:59:34 +00008839 return Comparison::Worse;
George Burgess IV2a6150d2015-10-16 01:17:38 +00008840 }
8841
George Burgess IV3dc166912016-05-10 01:59:34 +00008842 return Cand1I == Cand1Attrs.end() ? Comparison::Equal : Comparison::Better;
George Burgess IV2a6150d2015-10-16 01:17:38 +00008843}
8844
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008845/// isBetterOverloadCandidate - Determines whether the first overload
8846/// candidate is a better candidate than the second (C++ 13.3.3p1).
Richard Smith17c00b42014-11-12 01:24:00 +00008847bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1,
8848 const OverloadCandidate &Cand2,
8849 SourceLocation Loc,
8850 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008851 // Define viable functions to be better candidates than non-viable
8852 // functions.
8853 if (!Cand2.Viable)
8854 return Cand1.Viable;
8855 else if (!Cand1.Viable)
8856 return false;
8857
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008858 // C++ [over.match.best]p1:
8859 //
8860 // -- if F is a static member function, ICS1(F) is defined such
8861 // that ICS1(F) is neither better nor worse than ICS1(G) for
8862 // any function G, and, symmetrically, ICS1(G) is neither
8863 // better nor worse than ICS1(F).
8864 unsigned StartArg = 0;
8865 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8866 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008867
George Burgess IVfbad5b22016-09-07 20:03:19 +00008868 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
8869 // We don't allow incompatible pointer conversions in C++.
8870 if (!S.getLangOpts().CPlusPlus)
8871 return ICS.isStandard() &&
8872 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
8873
8874 // The only ill-formed conversion we allow in C++ is the string literal to
8875 // char* conversion, which is only considered ill-formed after C++11.
8876 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
8877 hasDeprecatedStringLiteralToCharPtrConversion(ICS);
8878 };
8879
8880 // Define functions that don't require ill-formed conversions for a given
8881 // argument to be better candidates than functions that do.
Richard Smith6eedfe72017-01-09 08:01:21 +00008882 unsigned NumArgs = Cand1.Conversions.size();
8883 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
George Burgess IVfbad5b22016-09-07 20:03:19 +00008884 bool HasBetterConversion = false;
8885 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
8886 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
8887 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
8888 if (Cand1Bad != Cand2Bad) {
8889 if (Cand1Bad)
8890 return false;
8891 HasBetterConversion = true;
8892 }
8893 }
8894
8895 if (HasBetterConversion)
8896 return true;
8897
Douglas Gregord3cb3562009-07-07 23:38:56 +00008898 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00008899 // A viable function F1 is defined to be a better function than another
8900 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00008901 // conversion sequence than ICSi(F2), and then...
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008902 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Richard Smith0f59cb32015-12-18 21:45:41 +00008903 switch (CompareImplicitConversionSequences(S, Loc,
John McCall5c32be02010-08-24 20:38:10 +00008904 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008905 Cand2.Conversions[ArgIdx])) {
8906 case ImplicitConversionSequence::Better:
8907 // Cand1 has a better conversion sequence.
8908 HasBetterConversion = true;
8909 break;
8910
8911 case ImplicitConversionSequence::Worse:
8912 // Cand1 can't be better than Cand2.
8913 return false;
8914
8915 case ImplicitConversionSequence::Indistinguishable:
8916 // Do nothing.
8917 break;
8918 }
8919 }
8920
Mike Stump11289f42009-09-09 15:08:12 +00008921 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00008922 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008923 if (HasBetterConversion)
8924 return true;
8925
Douglas Gregora1f013e2008-11-07 22:36:19 +00008926 // -- the context is an initialization by user-defined conversion
8927 // (see 8.5, 13.3.1.5) and the standard conversion sequence
8928 // from the return type of F1 to the destination type (i.e.,
8929 // the type of the entity being initialized) is a better
8930 // conversion sequence than the standard conversion sequence
8931 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00008932 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00008933 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00008934 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregor2837aa22012-02-22 17:32:19 +00008935 // First check whether we prefer one of the conversion functions over the
8936 // other. This only distinguishes the results in non-standard, extension
8937 // cases such as the conversion from a lambda closure type to a function
8938 // pointer or block.
Richard Smithec2748a2014-05-17 04:36:39 +00008939 ImplicitConversionSequence::CompareKind Result =
8940 compareConversionFunctions(S, Cand1.Function, Cand2.Function);
8941 if (Result == ImplicitConversionSequence::Indistinguishable)
Richard Smith0f59cb32015-12-18 21:45:41 +00008942 Result = CompareStandardConversionSequences(S, Loc,
Richard Smithec2748a2014-05-17 04:36:39 +00008943 Cand1.FinalConversion,
8944 Cand2.FinalConversion);
Richard Smith6fdeaab2014-05-17 01:58:45 +00008945
Richard Smithec2748a2014-05-17 04:36:39 +00008946 if (Result != ImplicitConversionSequence::Indistinguishable)
8947 return Result == ImplicitConversionSequence::Better;
Richard Smith6fdeaab2014-05-17 01:58:45 +00008948
8949 // FIXME: Compare kind of reference binding if conversion functions
8950 // convert to a reference type used in direct reference binding, per
8951 // C++14 [over.match.best]p1 section 2 bullet 3.
8952 }
8953
Richard Smith32918772017-02-14 00:25:28 +00008954 // -- F1 is generated from a deduction-guide and F2 is not
Richard Smithbc491202017-02-17 20:05:37 +00008955 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
8956 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
8957 if (Guide1 && Guide2 && Guide1->isImplicit() != Guide2->isImplicit())
8958 return Guide2->isImplicit();
Richard Smith32918772017-02-14 00:25:28 +00008959
Richard Smith6fdeaab2014-05-17 01:58:45 +00008960 // -- F1 is a non-template function and F2 is a function template
8961 // specialization, or, if not that,
8962 bool Cand1IsSpecialization = Cand1.Function &&
8963 Cand1.Function->getPrimaryTemplate();
8964 bool Cand2IsSpecialization = Cand2.Function &&
8965 Cand2.Function->getPrimaryTemplate();
8966 if (Cand1IsSpecialization != Cand2IsSpecialization)
8967 return Cand2IsSpecialization;
8968
8969 // -- F1 and F2 are function template specializations, and the function
8970 // template for F1 is more specialized than the template for F2
8971 // according to the partial ordering rules described in 14.5.5.2, or,
8972 // if not that,
8973 if (Cand1IsSpecialization && Cand2IsSpecialization) {
8974 if (FunctionTemplateDecl *BetterTemplate
8975 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
8976 Cand2.Function->getPrimaryTemplate(),
8977 Loc,
8978 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
8979 : TPOC_Call,
8980 Cand1.ExplicitCallArguments,
8981 Cand2.ExplicitCallArguments))
8982 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregora1f013e2008-11-07 22:36:19 +00008983 }
8984
Richard Smith5179eb72016-06-28 19:03:57 +00008985 // FIXME: Work around a defect in the C++17 inheriting constructor wording.
8986 // A derived-class constructor beats an (inherited) base class constructor.
8987 bool Cand1IsInherited =
8988 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
8989 bool Cand2IsInherited =
8990 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
8991 if (Cand1IsInherited != Cand2IsInherited)
8992 return Cand2IsInherited;
8993 else if (Cand1IsInherited) {
8994 assert(Cand2IsInherited);
8995 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
8996 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
8997 if (Cand1Class->isDerivedFrom(Cand2Class))
8998 return true;
8999 if (Cand2Class->isDerivedFrom(Cand1Class))
9000 return false;
9001 // Inherited from sibling base classes: still ambiguous.
9002 }
9003
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009004 // Check for enable_if value-based overload resolution.
George Burgess IV3dc166912016-05-10 01:59:34 +00009005 if (Cand1.Function && Cand2.Function) {
9006 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
9007 if (Cmp != Comparison::Equal)
9008 return Cmp == Comparison::Better;
9009 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009010
Justin Lebar25c4a812016-03-29 16:24:16 +00009011 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
Artem Belevich94a55e82015-09-22 17:22:59 +00009012 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9013 return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
9014 S.IdentifyCUDAPreference(Caller, Cand2.Function);
9015 }
9016
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009017 bool HasPS1 = Cand1.Function != nullptr &&
9018 functionHasPassObjectSizeParams(Cand1.Function);
9019 bool HasPS2 = Cand2.Function != nullptr &&
9020 functionHasPassObjectSizeParams(Cand2.Function);
9021 return HasPS1 != HasPS2 && HasPS1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009022}
9023
Richard Smith2dbe4042015-11-04 19:26:32 +00009024/// Determine whether two declarations are "equivalent" for the purposes of
Richard Smith26210db2015-11-13 03:52:13 +00009025/// name lookup and overload resolution. This applies when the same internal/no
9026/// linkage entity is defined by two modules (probably by textually including
Richard Smith2dbe4042015-11-04 19:26:32 +00009027/// the same header). In such a case, we don't consider the declarations to
9028/// declare the same entity, but we also don't want lookups with both
9029/// declarations visible to be ambiguous in some cases (this happens when using
9030/// a modularized libstdc++).
9031bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
9032 const NamedDecl *B) {
Richard Smith26210db2015-11-13 03:52:13 +00009033 auto *VA = dyn_cast_or_null<ValueDecl>(A);
9034 auto *VB = dyn_cast_or_null<ValueDecl>(B);
9035 if (!VA || !VB)
9036 return false;
9037
9038 // The declarations must be declaring the same name as an internal linkage
9039 // entity in different modules.
9040 if (!VA->getDeclContext()->getRedeclContext()->Equals(
9041 VB->getDeclContext()->getRedeclContext()) ||
9042 getOwningModule(const_cast<ValueDecl *>(VA)) ==
9043 getOwningModule(const_cast<ValueDecl *>(VB)) ||
9044 VA->isExternallyVisible() || VB->isExternallyVisible())
9045 return false;
9046
9047 // Check that the declarations appear to be equivalent.
9048 //
9049 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
9050 // For constants and functions, we should check the initializer or body is
9051 // the same. For non-constant variables, we shouldn't allow it at all.
9052 if (Context.hasSameType(VA->getType(), VB->getType()))
9053 return true;
9054
9055 // Enum constants within unnamed enumerations will have different types, but
9056 // may still be similar enough to be interchangeable for our purposes.
9057 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
9058 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
9059 // Only handle anonymous enums. If the enumerations were named and
9060 // equivalent, they would have been merged to the same type.
9061 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
9062 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
9063 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
9064 !Context.hasSameType(EnumA->getIntegerType(),
9065 EnumB->getIntegerType()))
9066 return false;
9067 // Allow this only if the value is the same for both enumerators.
9068 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
9069 }
9070 }
9071
9072 // Nothing else is sufficiently similar.
9073 return false;
Richard Smith2dbe4042015-11-04 19:26:32 +00009074}
9075
9076void Sema::diagnoseEquivalentInternalLinkageDeclarations(
9077 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
9078 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
9079
9080 Module *M = getOwningModule(const_cast<NamedDecl*>(D));
9081 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
9082 << !M << (M ? M->getFullModuleName() : "");
9083
9084 for (auto *E : Equiv) {
9085 Module *M = getOwningModule(const_cast<NamedDecl*>(E));
9086 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
9087 << !M << (M ? M->getFullModuleName() : "");
9088 }
Richard Smith896c66e2015-10-21 07:13:52 +00009089}
9090
Mike Stump11289f42009-09-09 15:08:12 +00009091/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009092/// within an overload candidate set.
9093///
James Dennettffad8b72012-06-22 08:10:18 +00009094/// \param Loc The location of the function name (or operator symbol) for
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009095/// which overload resolution occurs.
9096///
James Dennettffad8b72012-06-22 08:10:18 +00009097/// \param Best If overload resolution was successful or found a deleted
9098/// function, \p Best points to the candidate function found.
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009099///
9100/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00009101OverloadingResult
9102OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00009103 iterator &Best,
Chandler Carruth30141632011-02-25 19:41:05 +00009104 bool UserDefinedConversion) {
Artem Belevich18609102016-02-12 18:29:18 +00009105 llvm::SmallVector<OverloadCandidate *, 16> Candidates;
9106 std::transform(begin(), end(), std::back_inserter(Candidates),
9107 [](OverloadCandidate &Cand) { return &Cand; });
9108
Justin Lebar66a2ab92016-08-10 00:40:43 +00009109 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
9110 // are accepted by both clang and NVCC. However, during a particular
Artem Belevich18609102016-02-12 18:29:18 +00009111 // compilation mode only one call variant is viable. We need to
9112 // exclude non-viable overload candidates from consideration based
9113 // only on their host/device attributes. Specifically, if one
9114 // candidate call is WrongSide and the other is SameSide, we ignore
9115 // the WrongSide candidate.
Justin Lebar25c4a812016-03-29 16:24:16 +00009116 if (S.getLangOpts().CUDA) {
Artem Belevich18609102016-02-12 18:29:18 +00009117 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9118 bool ContainsSameSideCandidate =
9119 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
9120 return Cand->Function &&
9121 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9122 Sema::CFP_SameSide;
9123 });
9124 if (ContainsSameSideCandidate) {
9125 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
9126 return Cand->Function &&
9127 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9128 Sema::CFP_WrongSide;
9129 };
George Burgess IV8684b032017-01-04 19:16:29 +00009130 llvm::erase_if(Candidates, IsWrongSideCandidate);
Artem Belevich18609102016-02-12 18:29:18 +00009131 }
9132 }
9133
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009134 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00009135 Best = end();
Artem Belevich18609102016-02-12 18:29:18 +00009136 for (auto *Cand : Candidates)
John McCall5c32be02010-08-24 20:38:10 +00009137 if (Cand->Viable)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009138 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00009139 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009140 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009141
9142 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00009143 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009144 return OR_No_Viable_Function;
9145
Richard Smith2dbe4042015-11-04 19:26:32 +00009146 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
Richard Smith896c66e2015-10-21 07:13:52 +00009147
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009148 // Make sure that this function is better than every other viable
9149 // function. If not, we have an ambiguity.
Artem Belevich18609102016-02-12 18:29:18 +00009150 for (auto *Cand : Candidates) {
Mike Stump11289f42009-09-09 15:08:12 +00009151 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009152 Cand != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009153 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00009154 UserDefinedConversion)) {
Richard Smith2dbe4042015-11-04 19:26:32 +00009155 if (S.isEquivalentInternalLinkageDeclaration(Best->Function,
9156 Cand->Function)) {
9157 EquivalentCands.push_back(Cand->Function);
Richard Smith896c66e2015-10-21 07:13:52 +00009158 continue;
9159 }
9160
John McCall5c32be02010-08-24 20:38:10 +00009161 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009162 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00009163 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009164 }
Mike Stump11289f42009-09-09 15:08:12 +00009165
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009166 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00009167 if (Best->Function &&
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00009168 (Best->Function->isDeleted() ||
George Burgess IVce6284b2017-01-28 02:19:40 +00009169 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor171c45a2009-02-18 21:56:37 +00009170 return OR_Deleted;
9171
Richard Smith2dbe4042015-11-04 19:26:32 +00009172 if (!EquivalentCands.empty())
9173 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
9174 EquivalentCands);
Richard Smith896c66e2015-10-21 07:13:52 +00009175
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009176 return OR_Success;
9177}
9178
John McCall53262c92010-01-12 02:15:36 +00009179namespace {
9180
9181enum OverloadCandidateKind {
9182 oc_function,
9183 oc_method,
9184 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00009185 oc_function_template,
9186 oc_method_template,
9187 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00009188 oc_implicit_default_constructor,
9189 oc_implicit_copy_constructor,
Alexis Hunt119c10e2011-05-25 23:16:36 +00009190 oc_implicit_move_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00009191 oc_implicit_copy_assignment,
Alexis Hunt119c10e2011-05-25 23:16:36 +00009192 oc_implicit_move_assignment,
Richard Smith5179eb72016-06-28 19:03:57 +00009193 oc_inherited_constructor,
9194 oc_inherited_constructor_template
John McCall53262c92010-01-12 02:15:36 +00009195};
9196
George Burgess IVd66d37c2016-10-28 21:42:06 +00009197static OverloadCandidateKind
9198ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
9199 std::string &Description) {
John McCalle1ac8d12010-01-13 00:25:19 +00009200 bool isTemplate = false;
9201
9202 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
9203 isTemplate = true;
9204 Description = S.getTemplateArgumentBindingsText(
9205 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
9206 }
John McCallfd0b2f82010-01-06 09:43:14 +00009207
9208 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
Richard Smith5179eb72016-06-28 19:03:57 +00009209 if (!Ctor->isImplicit()) {
9210 if (isa<ConstructorUsingShadowDecl>(Found))
9211 return isTemplate ? oc_inherited_constructor_template
9212 : oc_inherited_constructor;
9213 else
9214 return isTemplate ? oc_constructor_template : oc_constructor;
9215 }
Sebastian Redl08905022011-02-05 19:23:19 +00009216
Alexis Hunt119c10e2011-05-25 23:16:36 +00009217 if (Ctor->isDefaultConstructor())
9218 return oc_implicit_default_constructor;
9219
9220 if (Ctor->isMoveConstructor())
9221 return oc_implicit_move_constructor;
9222
9223 assert(Ctor->isCopyConstructor() &&
9224 "unexpected sort of implicit constructor");
9225 return oc_implicit_copy_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00009226 }
9227
9228 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
9229 // This actually gets spelled 'candidate function' for now, but
9230 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00009231 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00009232 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00009233
Alexis Hunt119c10e2011-05-25 23:16:36 +00009234 if (Meth->isMoveAssignmentOperator())
9235 return oc_implicit_move_assignment;
9236
Douglas Gregor12695102012-02-10 08:36:38 +00009237 if (Meth->isCopyAssignmentOperator())
9238 return oc_implicit_copy_assignment;
9239
9240 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
9241 return oc_method;
John McCall53262c92010-01-12 02:15:36 +00009242 }
9243
John McCalle1ac8d12010-01-13 00:25:19 +00009244 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00009245}
9246
Richard Smith5179eb72016-06-28 19:03:57 +00009247void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
9248 // FIXME: It'd be nice to only emit a note once per using-decl per overload
9249 // set.
9250 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
9251 S.Diag(FoundDecl->getLocation(),
9252 diag::note_ovl_candidate_inherited_constructor)
9253 << Shadow->getNominatedBaseClass();
Sebastian Redl08905022011-02-05 19:23:19 +00009254}
9255
John McCall53262c92010-01-12 02:15:36 +00009256} // end anonymous namespace
9257
George Burgess IV5f21c712015-10-12 19:57:04 +00009258static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
9259 const FunctionDecl *FD) {
9260 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
9261 bool AlwaysTrue;
9262 if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
9263 return false;
9264 if (!AlwaysTrue)
9265 return false;
9266 }
9267 return true;
9268}
9269
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009270/// \brief Returns true if we can take the address of the function.
9271///
9272/// \param Complain - If true, we'll emit a diagnostic
9273/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
9274/// we in overload resolution?
9275/// \param Loc - The location of the statement we're complaining about. Ignored
9276/// if we're not complaining, or if we're in overload resolution.
9277static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
9278 bool Complain,
9279 bool InOverloadResolution,
9280 SourceLocation Loc) {
9281 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
9282 if (Complain) {
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009283 if (InOverloadResolution)
9284 S.Diag(FD->getLocStart(),
9285 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
9286 else
9287 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
9288 }
9289 return false;
9290 }
9291
George Burgess IV21081362016-07-24 23:12:40 +00009292 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
9293 return P->hasAttr<PassObjectSizeAttr>();
9294 });
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009295 if (I == FD->param_end())
9296 return true;
9297
9298 if (Complain) {
9299 // Add one to ParamNo because it's user-facing
9300 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
9301 if (InOverloadResolution)
9302 S.Diag(FD->getLocation(),
9303 diag::note_ovl_candidate_has_pass_object_size_params)
9304 << ParamNo;
9305 else
9306 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
9307 << FD << ParamNo;
9308 }
9309 return false;
9310}
9311
9312static bool checkAddressOfCandidateIsAvailable(Sema &S,
9313 const FunctionDecl *FD) {
9314 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
9315 /*InOverloadResolution=*/true,
9316 /*Loc=*/SourceLocation());
9317}
9318
9319bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
9320 bool Complain,
9321 SourceLocation Loc) {
9322 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
9323 /*InOverloadResolution=*/false,
9324 Loc);
9325}
9326
John McCall53262c92010-01-12 02:15:36 +00009327// Notes the location of an overload candidate.
Richard Smithc2bebe92016-05-11 20:37:46 +00009328void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
9329 QualType DestType, bool TakingAddress) {
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009330 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
9331 return;
9332
John McCalle1ac8d12010-01-13 00:25:19 +00009333 std::string FnDesc;
Richard Smithc2bebe92016-05-11 20:37:46 +00009334 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Found, Fn, FnDesc);
Richard Trieucaff2472011-11-23 22:32:32 +00009335 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
Saleem Abdulrasool78704fb2016-12-22 04:26:57 +00009336 << (unsigned) K << Fn << FnDesc;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009337
9338 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
Richard Trieucaff2472011-11-23 22:32:32 +00009339 Diag(Fn->getLocation(), PD);
Richard Smith5179eb72016-06-28 19:03:57 +00009340 MaybeEmitInheritedConstructorNote(*this, Found);
John McCallfd0b2f82010-01-06 09:43:14 +00009341}
9342
Nick Lewyckyed4265c2013-09-22 10:06:01 +00009343// Notes the location of all overload candidates designated through
Douglas Gregorb491ed32011-02-19 21:32:49 +00009344// OverloadedExpr
George Burgess IV5f21c712015-10-12 19:57:04 +00009345void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
9346 bool TakingAddress) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009347 assert(OverloadedExpr->getType() == Context.OverloadTy);
9348
9349 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
9350 OverloadExpr *OvlExpr = Ovl.Expression;
9351
9352 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00009353 IEnd = OvlExpr->decls_end();
Douglas Gregorb491ed32011-02-19 21:32:49 +00009354 I != IEnd; ++I) {
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00009355 if (FunctionTemplateDecl *FunTmpl =
Douglas Gregorb491ed32011-02-19 21:32:49 +00009356 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Smithc2bebe92016-05-11 20:37:46 +00009357 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType,
George Burgess IV5f21c712015-10-12 19:57:04 +00009358 TakingAddress);
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00009359 } else if (FunctionDecl *Fun
Douglas Gregorb491ed32011-02-19 21:32:49 +00009360 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Smithc2bebe92016-05-11 20:37:46 +00009361 NoteOverloadCandidate(*I, Fun, DestType, TakingAddress);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009362 }
9363 }
9364}
9365
John McCall0d1da222010-01-12 00:44:57 +00009366/// Diagnoses an ambiguous conversion. The partial diagnostic is the
9367/// "lead" diagnostic; it will be given two arguments, the source and
9368/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00009369void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
9370 Sema &S,
9371 SourceLocation CaretLoc,
9372 const PartialDiagnostic &PDiag) const {
9373 S.Diag(CaretLoc, PDiag)
9374 << Ambiguous.getFromType() << Ambiguous.getToType();
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00009375 // FIXME: The note limiting machinery is borrowed from
9376 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
9377 // refactoring here.
9378 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9379 unsigned CandsShown = 0;
9380 AmbiguousConversionSequence::const_iterator I, E;
9381 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
9382 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9383 break;
9384 ++CandsShown;
Richard Smithc2bebe92016-05-11 20:37:46 +00009385 S.NoteOverloadCandidate(I->first, I->second);
John McCall0d1da222010-01-12 00:44:57 +00009386 }
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00009387 if (I != E)
9388 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
John McCall12f97bc2010-01-08 04:41:39 +00009389}
9390
Richard Smith17c00b42014-11-12 01:24:00 +00009391static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009392 unsigned I, bool TakingCandidateAddress) {
John McCall6a61b522010-01-13 09:16:55 +00009393 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
9394 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00009395 assert(Cand->Function && "for now, candidate must be a function");
9396 FunctionDecl *Fn = Cand->Function;
9397
9398 // There's a conversion slot for the object argument if this is a
9399 // non-constructor method. Note that 'I' corresponds the
9400 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00009401 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00009402 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00009403 if (I == 0)
9404 isObjectArgument = true;
9405 else
9406 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00009407 }
9408
John McCalle1ac8d12010-01-13 00:25:19 +00009409 std::string FnDesc;
Richard Smithc2bebe92016-05-11 20:37:46 +00009410 OverloadCandidateKind FnKind =
9411 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
John McCalle1ac8d12010-01-13 00:25:19 +00009412
John McCall6a61b522010-01-13 09:16:55 +00009413 Expr *FromExpr = Conv.Bad.FromExpr;
9414 QualType FromTy = Conv.Bad.getFromType();
9415 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00009416
John McCallfb7ad0f2010-02-02 02:42:52 +00009417 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00009418 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00009419 Expr *E = FromExpr->IgnoreParens();
9420 if (isa<UnaryOperator>(E))
9421 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00009422 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00009423
9424 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
9425 << (unsigned) FnKind << FnDesc
9426 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9427 << ToTy << Name << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009428 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCallfb7ad0f2010-02-02 02:42:52 +00009429 return;
9430 }
9431
John McCall6d174642010-01-23 08:10:49 +00009432 // Do some hand-waving analysis to see if the non-viability is due
9433 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00009434 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
9435 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
9436 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
9437 CToTy = RT->getPointeeType();
9438 else {
9439 // TODO: detect and diagnose the full richness of const mismatches.
9440 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
Richard Trieucc3949d2016-02-18 22:34:54 +00009441 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
9442 CFromTy = FromPT->getPointeeType();
9443 CToTy = ToPT->getPointeeType();
9444 }
John McCall47000992010-01-14 03:28:57 +00009445 }
9446
9447 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
9448 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall47000992010-01-14 03:28:57 +00009449 Qualifiers FromQs = CFromTy.getQualifiers();
9450 Qualifiers ToQs = CToTy.getQualifiers();
9451
9452 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
9453 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
9454 << (unsigned) FnKind << FnDesc
9455 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9456 << FromTy
Yaxun Liub34ec822017-04-11 17:24:23 +00009457 << FromQs.getAddressSpaceAttributePrintValue()
9458 << ToQs.getAddressSpaceAttributePrintValue()
John McCall47000992010-01-14 03:28:57 +00009459 << (unsigned) isObjectArgument << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009460 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall47000992010-01-14 03:28:57 +00009461 return;
9462 }
9463
John McCall31168b02011-06-15 23:02:42 +00009464 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00009465 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCall31168b02011-06-15 23:02:42 +00009466 << (unsigned) FnKind << FnDesc
9467 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9468 << FromTy
9469 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
9470 << (unsigned) isObjectArgument << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009471 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall31168b02011-06-15 23:02:42 +00009472 return;
9473 }
9474
Douglas Gregoraec25842011-04-26 23:16:46 +00009475 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
9476 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
9477 << (unsigned) FnKind << FnDesc
9478 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9479 << FromTy
9480 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
9481 << (unsigned) isObjectArgument << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009482 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Douglas Gregoraec25842011-04-26 23:16:46 +00009483 return;
9484 }
9485
Andrey Bokhanko45d41322016-05-11 18:38:21 +00009486 if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
9487 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
9488 << (unsigned) FnKind << FnDesc
9489 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9490 << FromTy << FromQs.hasUnaligned() << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009491 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Andrey Bokhanko45d41322016-05-11 18:38:21 +00009492 return;
9493 }
9494
John McCall47000992010-01-14 03:28:57 +00009495 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
9496 assert(CVR && "unexpected qualifiers mismatch");
9497
9498 if (isObjectArgument) {
9499 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
9500 << (unsigned) FnKind << FnDesc
9501 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9502 << FromTy << (CVR - 1);
9503 } else {
9504 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
9505 << (unsigned) FnKind << FnDesc
9506 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9507 << FromTy << (CVR - 1) << I+1;
9508 }
Richard Smith5179eb72016-06-28 19:03:57 +00009509 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall47000992010-01-14 03:28:57 +00009510 return;
9511 }
9512
Sebastian Redla72462c2011-09-24 17:48:32 +00009513 // Special diagnostic for failure to convert an initializer list, since
9514 // telling the user that it has type void is not useful.
9515 if (FromExpr && isa<InitListExpr>(FromExpr)) {
9516 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
9517 << (unsigned) FnKind << FnDesc
9518 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9519 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009520 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Sebastian Redla72462c2011-09-24 17:48:32 +00009521 return;
9522 }
9523
John McCall6d174642010-01-23 08:10:49 +00009524 // Diagnose references or pointers to incomplete types differently,
9525 // since it's far from impossible that the incompleteness triggered
9526 // the failure.
9527 QualType TempFromTy = FromTy.getNonReferenceType();
9528 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
9529 TempFromTy = PTy->getPointeeType();
9530 if (TempFromTy->isIncompleteType()) {
David Blaikieac928932016-03-04 22:29:11 +00009531 // Emit the generic diagnostic and, optionally, add the hints to it.
John McCall6d174642010-01-23 08:10:49 +00009532 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
9533 << (unsigned) FnKind << FnDesc
9534 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
David Blaikieac928932016-03-04 22:29:11 +00009535 << FromTy << ToTy << (unsigned) isObjectArgument << I+1
9536 << (unsigned) (Cand->Fix.Kind);
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00009537
Richard Smith5179eb72016-06-28 19:03:57 +00009538 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall6d174642010-01-23 08:10:49 +00009539 return;
9540 }
9541
Douglas Gregor56f2e342010-06-30 23:01:39 +00009542 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009543 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00009544 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
9545 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
9546 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9547 FromPtrTy->getPointeeType()) &&
9548 !FromPtrTy->getPointeeType()->isIncompleteType() &&
9549 !ToPtrTy->getPointeeType()->isIncompleteType() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00009550 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00009551 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009552 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00009553 }
9554 } else if (const ObjCObjectPointerType *FromPtrTy
9555 = FromTy->getAs<ObjCObjectPointerType>()) {
9556 if (const ObjCObjectPointerType *ToPtrTy
9557 = ToTy->getAs<ObjCObjectPointerType>())
9558 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
9559 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
9560 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9561 FromPtrTy->getPointeeType()) &&
9562 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009563 BaseToDerivedConversion = 2;
9564 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009565 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
9566 !FromTy->isIncompleteType() &&
9567 !ToRefTy->getPointeeType()->isIncompleteType() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00009568 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009569 BaseToDerivedConversion = 3;
9570 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
9571 ToTy.getNonReferenceType().getCanonicalType() ==
9572 FromTy.getNonReferenceType().getCanonicalType()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009573 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
9574 << (unsigned) FnKind << FnDesc
9575 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9576 << (unsigned) isObjectArgument << I + 1;
Richard Smith5179eb72016-06-28 19:03:57 +00009577 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009578 return;
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009579 }
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009580 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009581
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009582 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009583 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009584 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00009585 << (unsigned) FnKind << FnDesc
9586 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009587 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009588 << FromTy << ToTy << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009589 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Douglas Gregor56f2e342010-06-30 23:01:39 +00009590 return;
9591 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009592
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00009593 if (isa<ObjCObjectPointerType>(CFromTy) &&
9594 isa<PointerType>(CToTy)) {
9595 Qualifiers FromQs = CFromTy.getQualifiers();
9596 Qualifiers ToQs = CToTy.getQualifiers();
9597 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9598 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
9599 << (unsigned) FnKind << FnDesc
9600 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9601 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009602 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00009603 return;
9604 }
9605 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009606
9607 if (TakingCandidateAddress &&
9608 !checkAddressOfCandidateIsAvailable(S, Cand->Function))
9609 return;
9610
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009611 // Emit the generic diagnostic and, optionally, add the hints to it.
9612 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
9613 FDiag << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00009614 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009615 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
9616 << (unsigned) (Cand->Fix.Kind);
9617
9618 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer490afa62012-01-14 21:05:10 +00009619 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
9620 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009621 FDiag << *HI;
9622 S.Diag(Fn->getLocation(), FDiag);
9623
Richard Smith5179eb72016-06-28 19:03:57 +00009624 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall6a61b522010-01-13 09:16:55 +00009625}
9626
Larisse Voufo98b20f12013-07-19 23:00:19 +00009627/// Additional arity mismatch diagnosis specific to a function overload
9628/// candidates. This is not covered by the more general DiagnoseArityMismatch()
9629/// over a candidate in any candidate set.
Richard Smith17c00b42014-11-12 01:24:00 +00009630static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
9631 unsigned NumArgs) {
John McCall6a61b522010-01-13 09:16:55 +00009632 FunctionDecl *Fn = Cand->Function;
John McCall6a61b522010-01-13 09:16:55 +00009633 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009634
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009635 // With invalid overloaded operators, it's possible that we think we
Larisse Voufo98b20f12013-07-19 23:00:19 +00009636 // have an arity mismatch when in fact it looks like we have the
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009637 // right number of arguments, because only overloaded operators have
9638 // the weird behavior of overloading member and non-member functions.
9639 // Just don't report anything.
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00009640 if (Fn->isInvalidDecl() &&
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009641 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009642 return true;
9643
9644 if (NumArgs < MinParams) {
9645 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
9646 (Cand->FailureKind == ovl_fail_bad_deduction &&
9647 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
9648 } else {
9649 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
9650 (Cand->FailureKind == ovl_fail_bad_deduction &&
9651 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
9652 }
9653
9654 return false;
9655}
9656
9657/// General arity mismatch diagnosis over a candidate in a candidate set.
Richard Smithc2bebe92016-05-11 20:37:46 +00009658static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
9659 unsigned NumFormalArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009660 assert(isa<FunctionDecl>(D) &&
9661 "The templated declaration should at least be a function"
9662 " when diagnosing bad template argument deduction due to too many"
9663 " or too few arguments");
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00009664
Larisse Voufo98b20f12013-07-19 23:00:19 +00009665 FunctionDecl *Fn = cast<FunctionDecl>(D);
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00009666
Larisse Voufo98b20f12013-07-19 23:00:19 +00009667 // TODO: treat calls to a missing default constructor as a special case
9668 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
9669 unsigned MinParams = Fn->getMinRequiredArguments();
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009670
John McCall6a61b522010-01-13 09:16:55 +00009671 // at least / at most / exactly
9672 unsigned mode, modeCount;
9673 if (NumFormalArgs < MinParams) {
Alp Toker9cacbab2014-01-20 20:26:09 +00009674 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
9675 FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00009676 mode = 0; // "at least"
9677 else
9678 mode = 2; // "exactly"
9679 modeCount = MinParams;
9680 } else {
Alp Toker9cacbab2014-01-20 20:26:09 +00009681 if (MinParams != FnTy->getNumParams())
John McCall6a61b522010-01-13 09:16:55 +00009682 mode = 1; // "at most"
9683 else
9684 mode = 2; // "exactly"
Alp Toker9cacbab2014-01-20 20:26:09 +00009685 modeCount = FnTy->getNumParams();
John McCall6a61b522010-01-13 09:16:55 +00009686 }
9687
9688 std::string Description;
Richard Smithc2bebe92016-05-11 20:37:46 +00009689 OverloadCandidateKind FnKind =
9690 ClassifyOverloadCandidate(S, Found, Fn, Description);
John McCall6a61b522010-01-13 09:16:55 +00009691
Richard Smith10ff50d2012-05-11 05:16:41 +00009692 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
9693 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
Craig Topperc3ec1492014-05-26 06:22:03 +00009694 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9695 << mode << Fn->getParamDecl(0) << NumFormalArgs;
Richard Smith10ff50d2012-05-11 05:16:41 +00009696 else
9697 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Craig Topperc3ec1492014-05-26 06:22:03 +00009698 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9699 << mode << modeCount << NumFormalArgs;
Richard Smith5179eb72016-06-28 19:03:57 +00009700 MaybeEmitInheritedConstructorNote(S, Found);
John McCalle1ac8d12010-01-13 00:25:19 +00009701}
9702
Larisse Voufo98b20f12013-07-19 23:00:19 +00009703/// Arity mismatch diagnosis specific to a function overload candidate.
Richard Smith17c00b42014-11-12 01:24:00 +00009704static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
9705 unsigned NumFormalArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009706 if (!CheckArityMismatch(S, Cand, NumFormalArgs))
Richard Smithc2bebe92016-05-11 20:37:46 +00009707 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
Larisse Voufo98b20f12013-07-19 23:00:19 +00009708}
Larisse Voufo47c08452013-07-19 22:53:23 +00009709
Richard Smith17c00b42014-11-12 01:24:00 +00009710static TemplateDecl *getDescribedTemplate(Decl *Templated) {
Serge Pavlov7dcc97e2016-04-19 06:19:52 +00009711 if (TemplateDecl *TD = Templated->getDescribedTemplate())
9712 return TD;
Larisse Voufo98b20f12013-07-19 23:00:19 +00009713 llvm_unreachable("Unsupported: Getting the described template declaration"
9714 " for bad deduction diagnosis");
9715}
9716
9717/// Diagnose a failed template-argument deduction.
Richard Smithc2bebe92016-05-11 20:37:46 +00009718static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
Richard Smith17c00b42014-11-12 01:24:00 +00009719 DeductionFailureInfo &DeductionFailure,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009720 unsigned NumArgs,
9721 bool TakingCandidateAddress) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009722 TemplateParameter Param = DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009723 NamedDecl *ParamD;
9724 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
9725 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
9726 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
Larisse Voufo98b20f12013-07-19 23:00:19 +00009727 switch (DeductionFailure.Result) {
John McCall8b9ed552010-02-01 18:53:26 +00009728 case Sema::TDK_Success:
9729 llvm_unreachable("TDK_success while diagnosing bad deduction");
9730
9731 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00009732 assert(ParamD && "no parameter found for incomplete deduction result");
Larisse Voufo98b20f12013-07-19 23:00:19 +00009733 S.Diag(Templated->getLocation(),
9734 diag::note_ovl_candidate_incomplete_deduction)
9735 << ParamD->getDeclName();
Richard Smith5179eb72016-06-28 19:03:57 +00009736 MaybeEmitInheritedConstructorNote(S, Found);
John McCall8b9ed552010-02-01 18:53:26 +00009737 return;
9738 }
9739
John McCall42d7d192010-08-05 09:05:08 +00009740 case Sema::TDK_Underqualified: {
9741 assert(ParamD && "no parameter found for bad qualifiers deduction result");
9742 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
9743
Larisse Voufo98b20f12013-07-19 23:00:19 +00009744 QualType Param = DeductionFailure.getFirstArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00009745
9746 // Param will have been canonicalized, but it should just be a
9747 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00009748 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00009749 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00009750 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00009751 assert(S.Context.hasSameType(Param, NonCanonParam));
9752
9753 // Arg has also been canonicalized, but there's nothing we can do
9754 // about that. It also doesn't matter as much, because it won't
9755 // have any template parameters in it (because deduction isn't
9756 // done on dependent types).
Larisse Voufo98b20f12013-07-19 23:00:19 +00009757 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00009758
Larisse Voufo98b20f12013-07-19 23:00:19 +00009759 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
9760 << ParamD->getDeclName() << Arg << NonCanonParam;
Richard Smith5179eb72016-06-28 19:03:57 +00009761 MaybeEmitInheritedConstructorNote(S, Found);
John McCall42d7d192010-08-05 09:05:08 +00009762 return;
9763 }
9764
9765 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00009766 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009767 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009768 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009769 which = 0;
Richard Smith593d6a12016-12-23 01:30:39 +00009770 else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
9771 // Deduction might have failed because we deduced arguments of two
9772 // different types for a non-type template parameter.
9773 // FIXME: Use a different TDK value for this.
9774 QualType T1 =
9775 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
9776 QualType T2 =
9777 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
9778 if (!S.Context.hasSameType(T1, T2)) {
9779 S.Diag(Templated->getLocation(),
9780 diag::note_ovl_candidate_inconsistent_deduction_types)
9781 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
9782 << *DeductionFailure.getSecondArg() << T2;
9783 MaybeEmitInheritedConstructorNote(S, Found);
9784 return;
9785 }
9786
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009787 which = 1;
Richard Smith593d6a12016-12-23 01:30:39 +00009788 } else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009789 which = 2;
9790 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009791
Larisse Voufo98b20f12013-07-19 23:00:19 +00009792 S.Diag(Templated->getLocation(),
9793 diag::note_ovl_candidate_inconsistent_deduction)
9794 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
9795 << *DeductionFailure.getSecondArg();
Richard Smith5179eb72016-06-28 19:03:57 +00009796 MaybeEmitInheritedConstructorNote(S, Found);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009797 return;
9798 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00009799
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009800 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009801 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009802 if (ParamD->getDeclName())
Larisse Voufo98b20f12013-07-19 23:00:19 +00009803 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009804 diag::note_ovl_candidate_explicit_arg_mismatch_named)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009805 << ParamD->getDeclName();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009806 else {
9807 int index = 0;
9808 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
9809 index = TTP->getIndex();
9810 else if (NonTypeTemplateParmDecl *NTTP
9811 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
9812 index = NTTP->getIndex();
9813 else
9814 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
Larisse Voufo98b20f12013-07-19 23:00:19 +00009815 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009816 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009817 << (index + 1);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009818 }
Richard Smith5179eb72016-06-28 19:03:57 +00009819 MaybeEmitInheritedConstructorNote(S, Found);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009820 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009821
Douglas Gregor02eb4832010-05-08 18:13:28 +00009822 case Sema::TDK_TooManyArguments:
9823 case Sema::TDK_TooFewArguments:
Richard Smithc2bebe92016-05-11 20:37:46 +00009824 DiagnoseArityMismatch(S, Found, Templated, NumArgs);
Douglas Gregor02eb4832010-05-08 18:13:28 +00009825 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00009826
9827 case Sema::TDK_InstantiationDepth:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009828 S.Diag(Templated->getLocation(),
9829 diag::note_ovl_candidate_instantiation_depth);
Richard Smith5179eb72016-06-28 19:03:57 +00009830 MaybeEmitInheritedConstructorNote(S, Found);
Douglas Gregord09efd42010-05-08 20:07:26 +00009831 return;
9832
9833 case Sema::TDK_SubstitutionFailure: {
Richard Smith9ca64612012-05-07 09:03:25 +00009834 // Format the template argument list into the argument string.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009835 SmallString<128> TemplateArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00009836 if (TemplateArgumentList *Args =
Larisse Voufo98b20f12013-07-19 23:00:19 +00009837 DeductionFailure.getTemplateArgumentList()) {
Richard Smith9ca64612012-05-07 09:03:25 +00009838 TemplateArgString = " ";
9839 TemplateArgString += S.getTemplateArgumentBindingsText(
Larisse Voufo98b20f12013-07-19 23:00:19 +00009840 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
Richard Smith9ca64612012-05-07 09:03:25 +00009841 }
9842
Richard Smith6f8d2c62012-05-09 05:17:00 +00009843 // If this candidate was disabled by enable_if, say so.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009844 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
Richard Smith6f8d2c62012-05-09 05:17:00 +00009845 if (PDiag && PDiag->second.getDiagID() ==
9846 diag::err_typename_nested_not_found_enable_if) {
9847 // FIXME: Use the source range of the condition, and the fully-qualified
9848 // name of the enable_if template. These are both present in PDiag.
9849 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
9850 << "'enable_if'" << TemplateArgString;
9851 return;
9852 }
9853
Douglas Gregor00fa10b2017-07-05 20:20:14 +00009854 // We found a specific requirement that disabled the enable_if.
9855 if (PDiag && PDiag->second.getDiagID() ==
9856 diag::err_typename_nested_not_found_requirement) {
9857 S.Diag(Templated->getLocation(),
9858 diag::note_ovl_candidate_disabled_by_requirement)
9859 << PDiag->second.getStringArg(0) << TemplateArgString;
9860 return;
9861 }
9862
Richard Smith9ca64612012-05-07 09:03:25 +00009863 // Format the SFINAE diagnostic into the argument string.
9864 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
9865 // formatted message in another diagnostic.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009866 SmallString<128> SFINAEArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00009867 SourceRange R;
Richard Smith6f8d2c62012-05-09 05:17:00 +00009868 if (PDiag) {
Richard Smith9ca64612012-05-07 09:03:25 +00009869 SFINAEArgString = ": ";
9870 R = SourceRange(PDiag->first, PDiag->first);
9871 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
9872 }
9873
Larisse Voufo98b20f12013-07-19 23:00:19 +00009874 S.Diag(Templated->getLocation(),
9875 diag::note_ovl_candidate_substitution_failure)
9876 << TemplateArgString << SFINAEArgString << R;
Richard Smith5179eb72016-06-28 19:03:57 +00009877 MaybeEmitInheritedConstructorNote(S, Found);
Douglas Gregord09efd42010-05-08 20:07:26 +00009878 return;
9879 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009880
Richard Smithc92d2062017-01-05 23:02:44 +00009881 case Sema::TDK_DeducedMismatch:
9882 case Sema::TDK_DeducedMismatchNested: {
Richard Smith9b534542015-12-31 02:02:54 +00009883 // Format the template argument list into the argument string.
9884 SmallString<128> TemplateArgString;
9885 if (TemplateArgumentList *Args =
9886 DeductionFailure.getTemplateArgumentList()) {
9887 TemplateArgString = " ";
9888 TemplateArgString += S.getTemplateArgumentBindingsText(
9889 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9890 }
9891
9892 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
9893 << (*DeductionFailure.getCallArgIndex() + 1)
9894 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
Richard Smithc92d2062017-01-05 23:02:44 +00009895 << TemplateArgString
9896 << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
Richard Smith9b534542015-12-31 02:02:54 +00009897 break;
9898 }
9899
Richard Trieue3732352013-04-08 21:11:40 +00009900 case Sema::TDK_NonDeducedMismatch: {
Richard Smith44ecdbd2013-01-31 05:19:49 +00009901 // FIXME: Provide a source location to indicate what we couldn't match.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009902 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
9903 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
Richard Trieue3732352013-04-08 21:11:40 +00009904 if (FirstTA.getKind() == TemplateArgument::Template &&
9905 SecondTA.getKind() == TemplateArgument::Template) {
9906 TemplateName FirstTN = FirstTA.getAsTemplate();
9907 TemplateName SecondTN = SecondTA.getAsTemplate();
9908 if (FirstTN.getKind() == TemplateName::Template &&
9909 SecondTN.getKind() == TemplateName::Template) {
9910 if (FirstTN.getAsTemplateDecl()->getName() ==
9911 SecondTN.getAsTemplateDecl()->getName()) {
9912 // FIXME: This fixes a bad diagnostic where both templates are named
9913 // the same. This particular case is a bit difficult since:
9914 // 1) It is passed as a string to the diagnostic printer.
9915 // 2) The diagnostic printer only attempts to find a better
9916 // name for types, not decls.
9917 // Ideally, this should folded into the diagnostic printer.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009918 S.Diag(Templated->getLocation(),
Richard Trieue3732352013-04-08 21:11:40 +00009919 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
9920 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
9921 return;
9922 }
9923 }
9924 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009925
9926 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
9927 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
9928 return;
9929
Faisal Vali2b391ab2013-09-26 19:54:12 +00009930 // FIXME: For generic lambda parameters, check if the function is a lambda
Simon Pilgrimfb9662a2017-06-01 18:17:18 +00009931 // call operator, and if so, emit a prettier and more informative
9932 // diagnostic that mentions 'auto' and lambda in addition to
Faisal Vali2b391ab2013-09-26 19:54:12 +00009933 // (or instead of?) the canonical template type parameters.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009934 S.Diag(Templated->getLocation(),
9935 diag::note_ovl_candidate_non_deduced_mismatch)
9936 << FirstTA << SecondTA;
Richard Smith44ecdbd2013-01-31 05:19:49 +00009937 return;
Richard Trieue3732352013-04-08 21:11:40 +00009938 }
John McCall8b9ed552010-02-01 18:53:26 +00009939 // TODO: diagnose these individually, then kill off
9940 // note_ovl_candidate_bad_deduction, which is uselessly vague.
Richard Smith44ecdbd2013-01-31 05:19:49 +00009941 case Sema::TDK_MiscellaneousDeductionFailure:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009942 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
Richard Smith5179eb72016-06-28 19:03:57 +00009943 MaybeEmitInheritedConstructorNote(S, Found);
John McCall8b9ed552010-02-01 18:53:26 +00009944 return;
Artem Belevich13e9b4d2016-12-07 19:27:16 +00009945 case Sema::TDK_CUDATargetMismatch:
9946 S.Diag(Templated->getLocation(),
9947 diag::note_cuda_ovl_candidate_target_mismatch);
9948 return;
John McCall8b9ed552010-02-01 18:53:26 +00009949 }
9950}
9951
Larisse Voufo98b20f12013-07-19 23:00:19 +00009952/// Diagnose a failed template-argument deduction, for function calls.
Richard Smith17c00b42014-11-12 01:24:00 +00009953static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009954 unsigned NumArgs,
9955 bool TakingCandidateAddress) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009956 unsigned TDK = Cand->DeductionFailure.Result;
9957 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
9958 if (CheckArityMismatch(S, Cand, NumArgs))
9959 return;
9960 }
Richard Smithc2bebe92016-05-11 20:37:46 +00009961 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009962 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
Larisse Voufo98b20f12013-07-19 23:00:19 +00009963}
9964
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009965/// CUDA: diagnose an invalid call across targets.
Richard Smith17c00b42014-11-12 01:24:00 +00009966static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009967 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
9968 FunctionDecl *Callee = Cand->Function;
9969
9970 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
9971 CalleeTarget = S.IdentifyCUDATarget(Callee);
9972
9973 std::string FnDesc;
Richard Smithc2bebe92016-05-11 20:37:46 +00009974 OverloadCandidateKind FnKind =
9975 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc);
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009976
9977 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
Eli Bendersky9a220fc2014-09-29 20:38:29 +00009978 << (unsigned)FnKind << CalleeTarget << CallerTarget;
9979
9980 // This could be an implicit constructor for which we could not infer the
9981 // target due to a collsion. Diagnose that case.
9982 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
9983 if (Meth != nullptr && Meth->isImplicit()) {
9984 CXXRecordDecl *ParentClass = Meth->getParent();
9985 Sema::CXXSpecialMember CSM;
9986
9987 switch (FnKind) {
9988 default:
9989 return;
9990 case oc_implicit_default_constructor:
9991 CSM = Sema::CXXDefaultConstructor;
9992 break;
9993 case oc_implicit_copy_constructor:
9994 CSM = Sema::CXXCopyConstructor;
9995 break;
9996 case oc_implicit_move_constructor:
9997 CSM = Sema::CXXMoveConstructor;
9998 break;
9999 case oc_implicit_copy_assignment:
10000 CSM = Sema::CXXCopyAssignment;
10001 break;
10002 case oc_implicit_move_assignment:
10003 CSM = Sema::CXXMoveAssignment;
10004 break;
10005 };
10006
10007 bool ConstRHS = false;
10008 if (Meth->getNumParams()) {
10009 if (const ReferenceType *RT =
10010 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
10011 ConstRHS = RT->getPointeeType().isConstQualified();
10012 }
10013 }
10014
10015 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
10016 /* ConstRHS */ ConstRHS,
10017 /* Diagnose */ true);
10018 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010019}
10020
Richard Smith17c00b42014-11-12 01:24:00 +000010021static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010022 FunctionDecl *Callee = Cand->Function;
10023 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
10024
10025 S.Diag(Callee->getLocation(),
George Burgess IV177399e2017-01-09 04:12:14 +000010026 diag::note_ovl_candidate_disabled_by_function_cond_attr)
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010027 << Attr->getCond()->getSourceRange() << Attr->getMessage();
10028}
10029
Yaxun Liu5b746652016-12-18 05:18:55 +000010030static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) {
10031 FunctionDecl *Callee = Cand->Function;
10032
10033 S.Diag(Callee->getLocation(),
10034 diag::note_ovl_candidate_disabled_by_extension);
10035}
10036
John McCall8b9ed552010-02-01 18:53:26 +000010037/// Generates a 'note' diagnostic for an overload candidate. We've
10038/// already generated a primary error at the call site.
10039///
10040/// It really does need to be a single diagnostic with its caret
10041/// pointed at the candidate declaration. Yes, this creates some
10042/// major challenges of technical writing. Yes, this makes pointing
10043/// out problems with specific arguments quite awkward. It's still
10044/// better than generating twenty screens of text for every failed
10045/// overload.
10046///
10047/// It would be great to be able to express per-candidate problems
10048/// more richly for those diagnostic clients that cared, but we'd
10049/// still have to be just as careful with the default diagnostics.
Richard Smith17c00b42014-11-12 01:24:00 +000010050static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010051 unsigned NumArgs,
10052 bool TakingCandidateAddress) {
John McCall53262c92010-01-12 02:15:36 +000010053 FunctionDecl *Fn = Cand->Function;
10054
John McCall12f97bc2010-01-08 04:41:39 +000010055 // Note deleted candidates, but only if they're viable.
George Burgess IV177399e2017-01-09 04:12:14 +000010056 if (Cand->Viable) {
10057 if (Fn->isDeleted() || S.isFunctionConsideredUnavailable(Fn)) {
10058 std::string FnDesc;
10059 OverloadCandidateKind FnKind =
Richard Smithc2bebe92016-05-11 20:37:46 +000010060 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +000010061
George Burgess IV177399e2017-01-09 04:12:14 +000010062 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
10063 << FnKind << FnDesc
10064 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
10065 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10066 return;
10067 }
John McCall12f97bc2010-01-08 04:41:39 +000010068
George Burgess IV177399e2017-01-09 04:12:14 +000010069 // We don't really have anything else to say about viable candidates.
Richard Smithc2bebe92016-05-11 20:37:46 +000010070 S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +000010071 return;
10072 }
John McCall0d1da222010-01-12 00:44:57 +000010073
John McCall6a61b522010-01-13 09:16:55 +000010074 switch (Cand->FailureKind) {
10075 case ovl_fail_too_many_arguments:
10076 case ovl_fail_too_few_arguments:
10077 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +000010078
John McCall6a61b522010-01-13 09:16:55 +000010079 case ovl_fail_bad_deduction:
Richard Smithc2bebe92016-05-11 20:37:46 +000010080 return DiagnoseBadDeduction(S, Cand, NumArgs,
10081 TakingCandidateAddress);
John McCall8b9ed552010-02-01 18:53:26 +000010082
John McCall578a1f82014-12-14 01:46:53 +000010083 case ovl_fail_illegal_constructor: {
10084 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
10085 << (Fn->getPrimaryTemplate() ? 1 : 0);
Richard Smith5179eb72016-06-28 19:03:57 +000010086 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall578a1f82014-12-14 01:46:53 +000010087 return;
10088 }
10089
John McCallfe796dd2010-01-23 05:17:32 +000010090 case ovl_fail_trivial_conversion:
10091 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +000010092 case ovl_fail_final_conversion_not_exact:
Richard Smithc2bebe92016-05-11 20:37:46 +000010093 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +000010094
John McCall65eb8792010-02-25 01:37:24 +000010095 case ovl_fail_bad_conversion: {
10096 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Richard Smith6eedfe72017-01-09 08:01:21 +000010097 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +000010098 if (Cand->Conversions[I].isBad())
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010099 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010100
John McCall6a61b522010-01-13 09:16:55 +000010101 // FIXME: this currently happens when we're called from SemaInit
10102 // when user-conversion overload fails. Figure out how to handle
10103 // those conditions and diagnose them well.
Richard Smithc2bebe92016-05-11 20:37:46 +000010104 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +000010105 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010106
10107 case ovl_fail_bad_target:
10108 return DiagnoseBadTarget(S, Cand);
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010109
10110 case ovl_fail_enable_if:
10111 return DiagnoseFailedEnableIfAttr(S, Cand);
George Burgess IV7204ed92016-01-07 02:26:57 +000010112
Yaxun Liu5b746652016-12-18 05:18:55 +000010113 case ovl_fail_ext_disabled:
10114 return DiagnoseOpenCLExtensionDisabled(S, Cand);
10115
Richard Smithf9c59b72017-01-08 21:45:44 +000010116 case ovl_fail_inhctor_slice:
Richard Smith836a3b42017-01-13 20:46:54 +000010117 // It's generally not interesting to note copy/move constructors here.
10118 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
10119 return;
Richard Smithf9c59b72017-01-08 21:45:44 +000010120 S.Diag(Fn->getLocation(),
Richard Smith836a3b42017-01-13 20:46:54 +000010121 diag::note_ovl_candidate_inherited_constructor_slice)
10122 << (Fn->getPrimaryTemplate() ? 1 : 0)
10123 << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
Richard Smithf9c59b72017-01-08 21:45:44 +000010124 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10125 return;
10126
George Burgess IV7204ed92016-01-07 02:26:57 +000010127 case ovl_fail_addr_not_available: {
10128 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
10129 (void)Available;
10130 assert(!Available);
10131 break;
10132 }
John McCall65eb8792010-02-25 01:37:24 +000010133 }
John McCalld3224162010-01-08 00:58:21 +000010134}
10135
Richard Smith17c00b42014-11-12 01:24:00 +000010136static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
John McCalld3224162010-01-08 00:58:21 +000010137 // Desugar the type of the surrogate down to a function type,
10138 // retaining as many typedefs as possible while still showing
10139 // the function type (and, therefore, its parameter types).
10140 QualType FnType = Cand->Surrogate->getConversionType();
10141 bool isLValueReference = false;
10142 bool isRValueReference = false;
10143 bool isPointer = false;
10144 if (const LValueReferenceType *FnTypeRef =
10145 FnType->getAs<LValueReferenceType>()) {
10146 FnType = FnTypeRef->getPointeeType();
10147 isLValueReference = true;
10148 } else if (const RValueReferenceType *FnTypeRef =
10149 FnType->getAs<RValueReferenceType>()) {
10150 FnType = FnTypeRef->getPointeeType();
10151 isRValueReference = true;
10152 }
10153 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
10154 FnType = FnTypePtr->getPointeeType();
10155 isPointer = true;
10156 }
10157 // Desugar down to a function type.
10158 FnType = QualType(FnType->getAs<FunctionType>(), 0);
10159 // Reconstruct the pointer/reference as appropriate.
10160 if (isPointer) FnType = S.Context.getPointerType(FnType);
10161 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
10162 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
10163
10164 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
10165 << FnType;
10166}
10167
Richard Smith17c00b42014-11-12 01:24:00 +000010168static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
10169 SourceLocation OpLoc,
10170 OverloadCandidate *Cand) {
Richard Smith6eedfe72017-01-09 08:01:21 +000010171 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
John McCalld3224162010-01-08 00:58:21 +000010172 std::string TypeStr("operator");
10173 TypeStr += Opc;
10174 TypeStr += "(";
George Burgess IV5f6ab9a2017-06-08 20:55:21 +000010175 TypeStr += Cand->BuiltinParamTypes[0].getAsString();
Richard Smith6eedfe72017-01-09 08:01:21 +000010176 if (Cand->Conversions.size() == 1) {
John McCalld3224162010-01-08 00:58:21 +000010177 TypeStr += ")";
10178 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
10179 } else {
10180 TypeStr += ", ";
George Burgess IV5f6ab9a2017-06-08 20:55:21 +000010181 TypeStr += Cand->BuiltinParamTypes[1].getAsString();
John McCalld3224162010-01-08 00:58:21 +000010182 TypeStr += ")";
10183 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
10184 }
10185}
10186
Richard Smith17c00b42014-11-12 01:24:00 +000010187static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
10188 OverloadCandidate *Cand) {
Richard Smith6eedfe72017-01-09 08:01:21 +000010189 for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
John McCall0d1da222010-01-12 00:44:57 +000010190 if (ICS.isBad()) break; // all meaningless after first invalid
10191 if (!ICS.isAmbiguous()) continue;
10192
Richard Smithc2bebe92016-05-11 20:37:46 +000010193 ICS.DiagnoseAmbiguousConversion(
10194 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +000010195 }
10196}
10197
Larisse Voufo98b20f12013-07-19 23:00:19 +000010198static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
John McCall3712d9e2010-01-15 23:32:50 +000010199 if (Cand->Function)
10200 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +000010201 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +000010202 return Cand->Surrogate->getLocation();
10203 return SourceLocation();
10204}
10205
Larisse Voufo98b20f12013-07-19 23:00:19 +000010206static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
Chandler Carruth73fddfe2011-09-10 00:51:24 +000010207 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010208 case Sema::TDK_Success:
Richard Smith6eedfe72017-01-09 08:01:21 +000010209 case Sema::TDK_NonDependentConversionFailure:
10210 llvm_unreachable("non-deduction failure while diagnosing bad deduction");
Benjamin Kramer8a8051f2011-09-10 21:52:04 +000010211
Douglas Gregorc5c01a62012-09-13 21:01:57 +000010212 case Sema::TDK_Invalid:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010213 case Sema::TDK_Incomplete:
10214 return 1;
10215
10216 case Sema::TDK_Underqualified:
10217 case Sema::TDK_Inconsistent:
10218 return 2;
10219
10220 case Sema::TDK_SubstitutionFailure:
Richard Smith9b534542015-12-31 02:02:54 +000010221 case Sema::TDK_DeducedMismatch:
Richard Smithc92d2062017-01-05 23:02:44 +000010222 case Sema::TDK_DeducedMismatchNested:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010223 case Sema::TDK_NonDeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +000010224 case Sema::TDK_MiscellaneousDeductionFailure:
Artem Belevich13e9b4d2016-12-07 19:27:16 +000010225 case Sema::TDK_CUDATargetMismatch:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010226 return 3;
10227
10228 case Sema::TDK_InstantiationDepth:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010229 return 4;
10230
10231 case Sema::TDK_InvalidExplicitArguments:
10232 return 5;
10233
10234 case Sema::TDK_TooManyArguments:
10235 case Sema::TDK_TooFewArguments:
10236 return 6;
10237 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +000010238 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010239}
10240
Richard Smith17c00b42014-11-12 01:24:00 +000010241namespace {
John McCallad2587a2010-01-12 00:48:53 +000010242struct CompareOverloadCandidatesForDisplay {
10243 Sema &S;
Richard Smith0f59cb32015-12-18 21:45:41 +000010244 SourceLocation Loc;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +000010245 size_t NumArgs;
10246
Richard Smith0f59cb32015-12-18 21:45:41 +000010247 CompareOverloadCandidatesForDisplay(Sema &S, SourceLocation Loc, size_t nArgs)
Kaelyn Takatab96b3be2014-05-01 21:15:24 +000010248 : S(S), NumArgs(nArgs) {}
John McCall12f97bc2010-01-08 04:41:39 +000010249
10250 bool operator()(const OverloadCandidate *L,
10251 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +000010252 // Fast-path this check.
10253 if (L == R) return false;
10254
John McCall12f97bc2010-01-08 04:41:39 +000010255 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +000010256 if (L->Viable) {
10257 if (!R->Viable) return true;
10258
10259 // TODO: introduce a tri-valued comparison for overload
10260 // candidates. Would be more worthwhile if we had a sort
10261 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +000010262 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
10263 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +000010264 } else if (R->Viable)
10265 return false;
John McCall12f97bc2010-01-08 04:41:39 +000010266
John McCall3712d9e2010-01-15 23:32:50 +000010267 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +000010268
John McCall3712d9e2010-01-15 23:32:50 +000010269 // Criteria by which we can sort non-viable candidates:
10270 if (!L->Viable) {
10271 // 1. Arity mismatches come after other candidates.
10272 if (L->FailureKind == ovl_fail_too_many_arguments ||
Kaelyn Takatab96b3be2014-05-01 21:15:24 +000010273 L->FailureKind == ovl_fail_too_few_arguments) {
10274 if (R->FailureKind == ovl_fail_too_many_arguments ||
10275 R->FailureKind == ovl_fail_too_few_arguments) {
Kaelyn Takata50c4ffc2014-05-07 00:43:38 +000010276 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
10277 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
10278 if (LDist == RDist) {
10279 if (L->FailureKind == R->FailureKind)
10280 // Sort non-surrogates before surrogates.
10281 return !L->IsSurrogate && R->IsSurrogate;
10282 // Sort candidates requiring fewer parameters than there were
10283 // arguments given after candidates requiring more parameters
10284 // than there were arguments given.
10285 return L->FailureKind == ovl_fail_too_many_arguments;
10286 }
Kaelyn Takatab96b3be2014-05-01 21:15:24 +000010287 return LDist < RDist;
10288 }
John McCall3712d9e2010-01-15 23:32:50 +000010289 return false;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +000010290 }
John McCall3712d9e2010-01-15 23:32:50 +000010291 if (R->FailureKind == ovl_fail_too_many_arguments ||
10292 R->FailureKind == ovl_fail_too_few_arguments)
10293 return true;
John McCall12f97bc2010-01-08 04:41:39 +000010294
John McCallfe796dd2010-01-23 05:17:32 +000010295 // 2. Bad conversions come first and are ordered by the number
10296 // of bad conversions and quality of good conversions.
10297 if (L->FailureKind == ovl_fail_bad_conversion) {
10298 if (R->FailureKind != ovl_fail_bad_conversion)
10299 return true;
10300
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010301 // The conversion that can be fixed with a smaller number of changes,
10302 // comes first.
10303 unsigned numLFixes = L->Fix.NumConversionsFixed;
10304 unsigned numRFixes = R->Fix.NumConversionsFixed;
10305 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
10306 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +000010307 if (numLFixes != numRFixes) {
David Blaikie7a3cbb22015-03-09 02:02:07 +000010308 return numLFixes < numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +000010309 }
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010310
John McCallfe796dd2010-01-23 05:17:32 +000010311 // If there's any ordering between the defined conversions...
10312 // FIXME: this might not be transitive.
Richard Smith6eedfe72017-01-09 08:01:21 +000010313 assert(L->Conversions.size() == R->Conversions.size());
John McCallfe796dd2010-01-23 05:17:32 +000010314
10315 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +000010316 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Richard Smith6eedfe72017-01-09 08:01:21 +000010317 for (unsigned E = L->Conversions.size(); I != E; ++I) {
Richard Smith0f59cb32015-12-18 21:45:41 +000010318 switch (CompareImplicitConversionSequences(S, Loc,
John McCall5c32be02010-08-24 20:38:10 +000010319 L->Conversions[I],
10320 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +000010321 case ImplicitConversionSequence::Better:
10322 leftBetter++;
10323 break;
10324
10325 case ImplicitConversionSequence::Worse:
10326 leftBetter--;
10327 break;
10328
10329 case ImplicitConversionSequence::Indistinguishable:
10330 break;
10331 }
10332 }
10333 if (leftBetter > 0) return true;
10334 if (leftBetter < 0) return false;
10335
10336 } else if (R->FailureKind == ovl_fail_bad_conversion)
10337 return false;
10338
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010339 if (L->FailureKind == ovl_fail_bad_deduction) {
10340 if (R->FailureKind != ovl_fail_bad_deduction)
10341 return true;
10342
10343 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10344 return RankDeductionFailure(L->DeductionFailure)
Eli Friedman1e7a0c62011-10-14 23:10:30 +000010345 < RankDeductionFailure(R->DeductionFailure);
Eli Friedmane2c600c2011-10-14 21:52:24 +000010346 } else if (R->FailureKind == ovl_fail_bad_deduction)
10347 return false;
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010348
John McCall3712d9e2010-01-15 23:32:50 +000010349 // TODO: others?
10350 }
10351
10352 // Sort everything else by location.
10353 SourceLocation LLoc = GetLocationForCandidate(L);
10354 SourceLocation RLoc = GetLocationForCandidate(R);
10355
10356 // Put candidates without locations (e.g. builtins) at the end.
10357 if (LLoc.isInvalid()) return false;
10358 if (RLoc.isInvalid()) return true;
10359
10360 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +000010361 }
10362};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010363}
John McCall12f97bc2010-01-08 04:41:39 +000010364
John McCallfe796dd2010-01-23 05:17:32 +000010365/// CompleteNonViableCandidate - Normally, overload resolution only
Richard Smith6eedfe72017-01-09 08:01:21 +000010366/// computes up to the first bad conversion. Produces the FixIt set if
10367/// possible.
Richard Smith17c00b42014-11-12 01:24:00 +000010368static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
10369 ArrayRef<Expr *> Args) {
John McCallfe796dd2010-01-23 05:17:32 +000010370 assert(!Cand->Viable);
10371
10372 // Don't do anything on failures other than bad conversion.
10373 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
10374
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010375 // We only want the FixIts if all the arguments can be corrected.
10376 bool Unfixable = false;
Anna Zaks1b068122011-07-28 19:46:48 +000010377 // Use a implicit copy initialization to check conversion fixes.
10378 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010379
Richard Smith6eedfe72017-01-09 08:01:21 +000010380 // Attempt to fix the bad conversion.
10381 unsigned ConvCount = Cand->Conversions.size();
10382 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
10383 ++ConvIdx) {
John McCallfe796dd2010-01-23 05:17:32 +000010384 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
Richard Smith6eedfe72017-01-09 08:01:21 +000010385 if (Cand->Conversions[ConvIdx].isInitialized() &&
10386 Cand->Conversions[ConvIdx].isBad()) {
10387 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
John McCallfe796dd2010-01-23 05:17:32 +000010388 break;
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010389 }
John McCallfe796dd2010-01-23 05:17:32 +000010390 }
10391
Douglas Gregoradc7a702010-04-16 17:45:54 +000010392 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +000010393 // operation somehow.
10394 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +000010395
Richard Smith14ead302017-01-10 20:19:21 +000010396 unsigned ConvIdx = 0;
10397 ArrayRef<QualType> ParamTypes;
John McCallfe796dd2010-01-23 05:17:32 +000010398
10399 if (Cand->IsSurrogate) {
10400 QualType ConvType
10401 = Cand->Surrogate->getConversionType().getNonReferenceType();
10402 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10403 ConvType = ConvPtrType->getPointeeType();
Richard Smith14ead302017-01-10 20:19:21 +000010404 ParamTypes = ConvType->getAs<FunctionProtoType>()->getParamTypes();
10405 // Conversion 0 is 'this', which doesn't have a corresponding argument.
10406 ConvIdx = 1;
John McCallfe796dd2010-01-23 05:17:32 +000010407 } else if (Cand->Function) {
Richard Smith14ead302017-01-10 20:19:21 +000010408 ParamTypes =
10409 Cand->Function->getType()->getAs<FunctionProtoType>()->getParamTypes();
John McCallfe796dd2010-01-23 05:17:32 +000010410 if (isa<CXXMethodDecl>(Cand->Function) &&
Richard Smith14ead302017-01-10 20:19:21 +000010411 !isa<CXXConstructorDecl>(Cand->Function)) {
10412 // Conversion 0 is 'this', which doesn't have a corresponding argument.
10413 ConvIdx = 1;
Richard Smith6eedfe72017-01-09 08:01:21 +000010414 }
Richard Smith14ead302017-01-10 20:19:21 +000010415 } else {
10416 // Builtin operator.
10417 assert(ConvCount <= 3);
George Burgess IV5f6ab9a2017-06-08 20:55:21 +000010418 ParamTypes = Cand->BuiltinParamTypes;
John McCallfe796dd2010-01-23 05:17:32 +000010419 }
10420
10421 // Fill in the rest of the conversions.
Richard Smith14ead302017-01-10 20:19:21 +000010422 for (unsigned ArgIdx = 0; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Richard Smith6eedfe72017-01-09 08:01:21 +000010423 if (Cand->Conversions[ConvIdx].isInitialized()) {
Richard Smith14ead302017-01-10 20:19:21 +000010424 // We've already checked this conversion.
10425 } else if (ArgIdx < ParamTypes.size()) {
10426 if (ParamTypes[ArgIdx]->isDependentType())
Richard Smith6eedfe72017-01-09 08:01:21 +000010427 Cand->Conversions[ConvIdx].setAsIdentityConversion(
10428 Args[ArgIdx]->getType());
10429 else {
10430 Cand->Conversions[ConvIdx] =
Richard Smith14ead302017-01-10 20:19:21 +000010431 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ArgIdx],
Richard Smith6eedfe72017-01-09 08:01:21 +000010432 SuppressUserConversions,
10433 /*InOverloadResolution=*/true,
10434 /*AllowObjCWritebackConversion=*/
10435 S.getLangOpts().ObjCAutoRefCount);
10436 // Store the FixIt in the candidate if it exists.
10437 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
10438 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10439 }
10440 } else
John McCallfe796dd2010-01-23 05:17:32 +000010441 Cand->Conversions[ConvIdx].setEllipsis();
10442 }
10443}
10444
Douglas Gregor5251f1b2008-10-21 16:13:35 +000010445/// PrintOverloadCandidates - When overload resolution fails, prints
10446/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +000010447/// set.
Richard Smithb2f0f052016-10-10 18:54:32 +000010448void OverloadCandidateSet::NoteCandidates(
10449 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
10450 StringRef Opc, SourceLocation OpLoc,
10451 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
John McCall12f97bc2010-01-08 04:41:39 +000010452 // Sort the candidates by viability and position. Sorting directly would
10453 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010454 SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +000010455 if (OCD == OCD_AllCandidates) Cands.reserve(size());
10456 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
Richard Smithb2f0f052016-10-10 18:54:32 +000010457 if (!Filter(*Cand))
10458 continue;
John McCallfe796dd2010-01-23 05:17:32 +000010459 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +000010460 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +000010461 else if (OCD == OCD_AllCandidates) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010462 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010463 if (Cand->Function || Cand->IsSurrogate)
10464 Cands.push_back(Cand);
10465 // Otherwise, this a non-viable builtin candidate. We do not, in general,
10466 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +000010467 }
10468 }
10469
John McCallad2587a2010-01-12 00:48:53 +000010470 std::sort(Cands.begin(), Cands.end(),
Richard Smith0f59cb32015-12-18 21:45:41 +000010471 CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size()));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010472
John McCall0d1da222010-01-12 00:44:57 +000010473 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +000010474
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010475 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Douglas Gregor79591782012-10-23 23:11:23 +000010476 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010477 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +000010478 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10479 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +000010480
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010481 // Set an arbitrary limit on the number of candidate functions we'll spam
10482 // the user with. FIXME: This limit should depend on details of the
10483 // candidate list.
Douglas Gregor79591782012-10-23 23:11:23 +000010484 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010485 break;
10486 }
10487 ++CandsShown;
10488
John McCalld3224162010-01-08 00:58:21 +000010489 if (Cand->Function)
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010490 NoteFunctionCandidate(S, Cand, Args.size(),
10491 /*TakingCandidateAddress=*/false);
John McCalld3224162010-01-08 00:58:21 +000010492 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +000010493 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010494 else {
10495 assert(Cand->Viable &&
10496 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +000010497 // Generally we only see ambiguities including viable builtin
10498 // operators if overload resolution got screwed up by an
10499 // ambiguous user-defined conversion.
10500 //
10501 // FIXME: It's quite possible for different conversions to see
10502 // different ambiguities, though.
10503 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +000010504 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +000010505 ReportedAmbiguousConversions = true;
10506 }
John McCalld3224162010-01-08 00:58:21 +000010507
John McCall0d1da222010-01-12 00:44:57 +000010508 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +000010509 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +000010510 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +000010511 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010512
10513 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +000010514 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +000010515}
10516
Larisse Voufo98b20f12013-07-19 23:00:19 +000010517static SourceLocation
10518GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
10519 return Cand->Specialization ? Cand->Specialization->getLocation()
10520 : SourceLocation();
10521}
10522
Richard Smith17c00b42014-11-12 01:24:00 +000010523namespace {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010524struct CompareTemplateSpecCandidatesForDisplay {
10525 Sema &S;
10526 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
10527
10528 bool operator()(const TemplateSpecCandidate *L,
10529 const TemplateSpecCandidate *R) {
10530 // Fast-path this check.
10531 if (L == R)
10532 return false;
10533
10534 // Assuming that both candidates are not matches...
10535
10536 // Sort by the ranking of deduction failures.
10537 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10538 return RankDeductionFailure(L->DeductionFailure) <
10539 RankDeductionFailure(R->DeductionFailure);
10540
10541 // Sort everything else by location.
10542 SourceLocation LLoc = GetLocationForCandidate(L);
10543 SourceLocation RLoc = GetLocationForCandidate(R);
10544
10545 // Put candidates without locations (e.g. builtins) at the end.
10546 if (LLoc.isInvalid())
10547 return false;
10548 if (RLoc.isInvalid())
10549 return true;
10550
10551 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10552 }
10553};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010554}
Larisse Voufo98b20f12013-07-19 23:00:19 +000010555
10556/// Diagnose a template argument deduction failure.
10557/// We are treating these failures as overload failures due to bad
10558/// deductions.
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010559void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
10560 bool ForTakingAddress) {
Richard Smithc2bebe92016-05-11 20:37:46 +000010561 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010562 DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010563}
10564
10565void TemplateSpecCandidateSet::destroyCandidates() {
10566 for (iterator i = begin(), e = end(); i != e; ++i) {
10567 i->DeductionFailure.Destroy();
10568 }
10569}
10570
10571void TemplateSpecCandidateSet::clear() {
10572 destroyCandidates();
10573 Candidates.clear();
10574}
10575
10576/// NoteCandidates - When no template specialization match is found, prints
10577/// diagnostic messages containing the non-matching specializations that form
10578/// the candidate set.
10579/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
10580/// OCD == OCD_AllCandidates and Cand->Viable == false.
10581void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
10582 // Sort the candidates by position (assuming no candidate is a match).
10583 // Sorting directly would be prohibitive, so we make a set of pointers
10584 // and sort those.
10585 SmallVector<TemplateSpecCandidate *, 32> Cands;
10586 Cands.reserve(size());
10587 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10588 if (Cand->Specialization)
10589 Cands.push_back(Cand);
Alp Tokerd4733632013-12-05 04:47:09 +000010590 // Otherwise, this is a non-matching builtin candidate. We do not,
Larisse Voufo98b20f12013-07-19 23:00:19 +000010591 // in general, want to list every possible builtin candidate.
10592 }
10593
10594 std::sort(Cands.begin(), Cands.end(),
10595 CompareTemplateSpecCandidatesForDisplay(S));
10596
10597 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
10598 // for generalization purposes (?).
10599 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10600
10601 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
10602 unsigned CandsShown = 0;
10603 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10604 TemplateSpecCandidate *Cand = *I;
10605
10606 // Set an arbitrary limit on the number of candidates we'll spam
10607 // the user with. FIXME: This limit should depend on details of the
10608 // candidate list.
10609 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10610 break;
10611 ++CandsShown;
10612
10613 assert(Cand->Specialization &&
10614 "Non-matching built-in candidates are not added to Cands.");
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010615 Cand->NoteDeductionFailure(S, ForTakingAddress);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010616 }
10617
10618 if (I != E)
10619 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
10620}
10621
Douglas Gregorb491ed32011-02-19 21:32:49 +000010622// [PossiblyAFunctionType] --> [Return]
10623// NonFunctionType --> NonFunctionType
10624// R (A) --> R(A)
10625// R (*)(A) --> R (A)
10626// R (&)(A) --> R (A)
10627// R (S::*)(A) --> R (A)
10628QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
10629 QualType Ret = PossiblyAFunctionType;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010630 if (const PointerType *ToTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +000010631 PossiblyAFunctionType->getAs<PointerType>())
10632 Ret = ToTypePtr->getPointeeType();
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010633 else if (const ReferenceType *ToTypeRef =
Douglas Gregorb491ed32011-02-19 21:32:49 +000010634 PossiblyAFunctionType->getAs<ReferenceType>())
10635 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +000010636 else if (const MemberPointerType *MemTypePtr =
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010637 PossiblyAFunctionType->getAs<MemberPointerType>())
10638 Ret = MemTypePtr->getPointeeType();
10639 Ret =
Douglas Gregorb491ed32011-02-19 21:32:49 +000010640 Context.getCanonicalType(Ret).getUnqualifiedType();
10641 return Ret;
10642}
Douglas Gregorcd695e52008-11-10 20:40:00 +000010643
Richard Smith9095e5b2016-11-01 01:31:23 +000010644static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
10645 bool Complain = true) {
10646 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
10647 S.DeduceReturnType(FD, Loc, Complain))
10648 return true;
10649
10650 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
10651 if (S.getLangOpts().CPlusPlus1z &&
10652 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
10653 !S.ResolveExceptionSpec(Loc, FPT))
10654 return true;
10655
10656 return false;
10657}
10658
Richard Smith17c00b42014-11-12 01:24:00 +000010659namespace {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010660// A helper class to help with address of function resolution
10661// - allows us to avoid passing around all those ugly parameters
Richard Smith17c00b42014-11-12 01:24:00 +000010662class AddressOfFunctionResolver {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010663 Sema& S;
10664 Expr* SourceExpr;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010665 const QualType& TargetType;
10666 QualType TargetFunctionType; // Extracted function type from target type
10667
Douglas Gregorb491ed32011-02-19 21:32:49 +000010668 bool Complain;
10669 //DeclAccessPair& ResultFunctionAccessPair;
10670 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010671
Douglas Gregorb491ed32011-02-19 21:32:49 +000010672 bool TargetTypeIsNonStaticMemberFunction;
10673 bool FoundNonTemplateFunction;
David Majnemera4f7c7a2013-08-01 06:13:59 +000010674 bool StaticMemberFunctionFromBoundPointer;
George Burgess IV5f2ef452015-10-12 18:40:58 +000010675 bool HasComplained;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010676
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010677 OverloadExpr::FindResult OvlExprInfo;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010678 OverloadExpr *OvlExpr;
10679 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010680 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Larisse Voufo98b20f12013-07-19 23:00:19 +000010681 TemplateSpecCandidateSet FailedCandidates;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010682
Douglas Gregorb491ed32011-02-19 21:32:49 +000010683public:
Larisse Voufo98b20f12013-07-19 23:00:19 +000010684 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
10685 const QualType &TargetType, bool Complain)
10686 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
10687 Complain(Complain), Context(S.getASTContext()),
10688 TargetTypeIsNonStaticMemberFunction(
10689 !!TargetType->getAs<MemberPointerType>()),
10690 FoundNonTemplateFunction(false),
David Majnemera4f7c7a2013-08-01 06:13:59 +000010691 StaticMemberFunctionFromBoundPointer(false),
George Burgess IV5f2ef452015-10-12 18:40:58 +000010692 HasComplained(false),
Larisse Voufo98b20f12013-07-19 23:00:19 +000010693 OvlExprInfo(OverloadExpr::find(SourceExpr)),
10694 OvlExpr(OvlExprInfo.Expression),
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010695 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010696 ExtractUnqualifiedFunctionTypeFromTargetType();
Chandler Carruthffce2452011-03-29 08:08:18 +000010697
David Majnemera4f7c7a2013-08-01 06:13:59 +000010698 if (TargetFunctionType->isFunctionType()) {
10699 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
10700 if (!UME->isImplicitAccess() &&
10701 !S.ResolveSingleFunctionTemplateSpecialization(UME))
10702 StaticMemberFunctionFromBoundPointer = true;
10703 } else if (OvlExpr->hasExplicitTemplateArgs()) {
10704 DeclAccessPair dap;
10705 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
10706 OvlExpr, false, &dap)) {
10707 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
10708 if (!Method->isStatic()) {
10709 // If the target type is a non-function type and the function found
10710 // is a non-static member function, pretend as if that was the
10711 // target, it's the only possible type to end up with.
10712 TargetTypeIsNonStaticMemberFunction = true;
Chandler Carruthffce2452011-03-29 08:08:18 +000010713
David Majnemera4f7c7a2013-08-01 06:13:59 +000010714 // And skip adding the function if its not in the proper form.
10715 // We'll diagnose this due to an empty set of functions.
10716 if (!OvlExprInfo.HasFormOfMemberPointer)
10717 return;
Chandler Carruthffce2452011-03-29 08:08:18 +000010718 }
10719
David Majnemera4f7c7a2013-08-01 06:13:59 +000010720 Matches.push_back(std::make_pair(dap, Fn));
Douglas Gregor9b146582009-07-08 20:55:45 +000010721 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010722 return;
Douglas Gregor9b146582009-07-08 20:55:45 +000010723 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010724
Douglas Gregorb491ed32011-02-19 21:32:49 +000010725 if (OvlExpr->hasExplicitTemplateArgs())
James Y Knight04ec5bf2015-12-24 02:59:37 +000010726 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +000010727
Douglas Gregorb491ed32011-02-19 21:32:49 +000010728 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
10729 // C++ [over.over]p4:
10730 // If more than one function is selected, [...]
George Burgess IV2a6150d2015-10-16 01:17:38 +000010731 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010732 if (FoundNonTemplateFunction)
10733 EliminateAllTemplateMatches();
10734 else
10735 EliminateAllExceptMostSpecializedTemplate();
10736 }
10737 }
Artem Belevich94a55e82015-09-22 17:22:59 +000010738
Justin Lebar25c4a812016-03-29 16:24:16 +000010739 if (S.getLangOpts().CUDA && Matches.size() > 1)
Artem Belevich94a55e82015-09-22 17:22:59 +000010740 EliminateSuboptimalCudaMatches();
Douglas Gregorb491ed32011-02-19 21:32:49 +000010741 }
George Burgess IV5f2ef452015-10-12 18:40:58 +000010742
10743 bool hasComplained() const { return HasComplained; }
10744
Douglas Gregorb491ed32011-02-19 21:32:49 +000010745private:
George Burgess IV6da4c202016-03-23 02:33:58 +000010746 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
10747 QualType Discard;
10748 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
Richard Smith3c4f8d22016-10-16 17:54:23 +000010749 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
George Burgess IV2a6150d2015-10-16 01:17:38 +000010750 }
10751
George Burgess IV6da4c202016-03-23 02:33:58 +000010752 /// \return true if A is considered a better overload candidate for the
10753 /// desired type than B.
10754 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
10755 // If A doesn't have exactly the correct type, we don't want to classify it
10756 // as "better" than anything else. This way, the user is required to
10757 // disambiguate for us if there are multiple candidates and no exact match.
10758 return candidateHasExactlyCorrectType(A) &&
10759 (!candidateHasExactlyCorrectType(B) ||
George Burgess IV3dc166912016-05-10 01:59:34 +000010760 compareEnableIfAttrs(S, A, B) == Comparison::Better);
George Burgess IV6da4c202016-03-23 02:33:58 +000010761 }
10762
10763 /// \return true if we were able to eliminate all but one overload candidate,
10764 /// false otherwise.
George Burgess IV2a6150d2015-10-16 01:17:38 +000010765 bool eliminiateSuboptimalOverloadCandidates() {
10766 // Same algorithm as overload resolution -- one pass to pick the "best",
10767 // another pass to be sure that nothing is better than the best.
10768 auto Best = Matches.begin();
10769 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
10770 if (isBetterCandidate(I->second, Best->second))
10771 Best = I;
10772
10773 const FunctionDecl *BestFn = Best->second;
10774 auto IsBestOrInferiorToBest = [this, BestFn](
10775 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
10776 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
10777 };
10778
10779 // Note: We explicitly leave Matches unmodified if there isn't a clear best
10780 // option, so we can potentially give the user a better error
10781 if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest))
10782 return false;
10783 Matches[0] = *Best;
10784 Matches.resize(1);
10785 return true;
10786 }
10787
Douglas Gregorb491ed32011-02-19 21:32:49 +000010788 bool isTargetTypeAFunction() const {
10789 return TargetFunctionType->isFunctionType();
10790 }
10791
10792 // [ToType] [Return]
10793
10794 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
10795 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
10796 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
10797 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
10798 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
10799 }
10800
10801 // return true if any matching specializations were found
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010802 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
Douglas Gregorb491ed32011-02-19 21:32:49 +000010803 const DeclAccessPair& CurAccessFunPair) {
10804 if (CXXMethodDecl *Method
10805 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
10806 // Skip non-static function templates when converting to pointer, and
10807 // static when converting to member pointer.
10808 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10809 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010810 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010811 else if (TargetTypeIsNonStaticMemberFunction)
10812 return false;
10813
10814 // C++ [over.over]p2:
10815 // If the name is a function template, template argument deduction is
10816 // done (14.8.2.2), and if the argument deduction succeeds, the
10817 // resulting template argument list is used to generate a single
10818 // function template specialization, which is added to the set of
10819 // overloaded functions considered.
Craig Topperc3ec1492014-05-26 06:22:03 +000010820 FunctionDecl *Specialization = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +000010821 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregorb491ed32011-02-19 21:32:49 +000010822 if (Sema::TemplateDeductionResult Result
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010823 = S.DeduceTemplateArguments(FunctionTemplate,
Douglas Gregorb491ed32011-02-19 21:32:49 +000010824 &OvlExplicitTemplateArgs,
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010825 TargetFunctionType, Specialization,
Richard Smithbaa47832016-12-01 02:11:49 +000010826 Info, /*IsAddressOfFunction*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010827 // Make a note of the failed deduction for diagnostics.
10828 FailedCandidates.addCandidate()
Richard Smithc2bebe92016-05-11 20:37:46 +000010829 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
Larisse Voufo98b20f12013-07-19 23:00:19 +000010830 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregorb491ed32011-02-19 21:32:49 +000010831 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010832 }
10833
Douglas Gregor19a41f12013-04-17 08:45:07 +000010834 // Template argument deduction ensures that we have an exact match or
10835 // compatible pointer-to-function arguments that would be adjusted by ICS.
Douglas Gregorb491ed32011-02-19 21:32:49 +000010836 // This function template specicalization works.
Douglas Gregor19a41f12013-04-17 08:45:07 +000010837 assert(S.isSameOrCompatibleFunctionType(
10838 Context.getCanonicalType(Specialization->getType()),
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010839 Context.getCanonicalType(TargetFunctionType)));
George Burgess IV5f21c712015-10-12 19:57:04 +000010840
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010841 if (!S.checkAddressOfFunctionIsAvailable(Specialization))
George Burgess IV5f21c712015-10-12 19:57:04 +000010842 return false;
10843
Douglas Gregorb491ed32011-02-19 21:32:49 +000010844 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
10845 return true;
10846 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010847
10848 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
Douglas Gregorb491ed32011-02-19 21:32:49 +000010849 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +000010850 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +000010851 // Skip non-static functions when converting to pointer, and static
10852 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +000010853 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10854 return false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010855 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010856 else if (TargetTypeIsNonStaticMemberFunction)
10857 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010858
Chandler Carruthc25c6ee2009-12-29 06:17:27 +000010859 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000010860 if (S.getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010861 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
Justin Lebarb0080032016-08-10 01:09:11 +000010862 if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010863 return false;
10864
Richard Smith2a7d4812013-05-04 07:00:32 +000010865 // If any candidate has a placeholder return type, trigger its deduction
10866 // now.
Richard Smith9095e5b2016-11-01 01:31:23 +000010867 if (completeFunctionType(S, FunDecl, SourceExpr->getLocStart(),
10868 Complain)) {
George Burgess IV5f2ef452015-10-12 18:40:58 +000010869 HasComplained |= Complain;
Richard Smith2a7d4812013-05-04 07:00:32 +000010870 return false;
George Burgess IV5f2ef452015-10-12 18:40:58 +000010871 }
Richard Smith2a7d4812013-05-04 07:00:32 +000010872
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010873 if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
George Burgess IV5f21c712015-10-12 19:57:04 +000010874 return false;
10875
George Burgess IV6da4c202016-03-23 02:33:58 +000010876 // If we're in C, we need to support types that aren't exactly identical.
10877 if (!S.getLangOpts().CPlusPlus ||
10878 candidateHasExactlyCorrectType(FunDecl)) {
George Burgess IV5f21c712015-10-12 19:57:04 +000010879 Matches.push_back(std::make_pair(
10880 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +000010881 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010882 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +000010883 }
Mike Stump11289f42009-09-09 15:08:12 +000010884 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010885
Douglas Gregorb491ed32011-02-19 21:32:49 +000010886 return false;
10887 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010888
Douglas Gregorb491ed32011-02-19 21:32:49 +000010889 bool FindAllFunctionsThatMatchTargetTypeExactly() {
10890 bool Ret = false;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010891
Douglas Gregorb491ed32011-02-19 21:32:49 +000010892 // If the overload expression doesn't have the form of a pointer to
10893 // member, don't try to convert it to a pointer-to-member type.
10894 if (IsInvalidFormOfPointerToMemberFunction())
10895 return false;
10896
10897 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000010898 E = OvlExpr->decls_end();
Douglas Gregorb491ed32011-02-19 21:32:49 +000010899 I != E; ++I) {
10900 // Look through any using declarations to find the underlying function.
10901 NamedDecl *Fn = (*I)->getUnderlyingDecl();
10902
10903 // C++ [over.over]p3:
10904 // Non-member functions and static member functions match
10905 // targets of type "pointer-to-function" or "reference-to-function."
10906 // Nonstatic member functions match targets of
10907 // type "pointer-to-member-function."
10908 // Note that according to DR 247, the containing class does not matter.
10909 if (FunctionTemplateDecl *FunctionTemplate
10910 = dyn_cast<FunctionTemplateDecl>(Fn)) {
10911 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
10912 Ret = true;
10913 }
10914 // If we have explicit template arguments supplied, skip non-templates.
10915 else if (!OvlExpr->hasExplicitTemplateArgs() &&
10916 AddMatchingNonTemplateFunction(Fn, I.getPair()))
10917 Ret = true;
10918 }
10919 assert(Ret || Matches.empty());
10920 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010921 }
10922
Douglas Gregorb491ed32011-02-19 21:32:49 +000010923 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +000010924 // [...] and any given function template specialization F1 is
10925 // eliminated if the set contains a second function template
10926 // specialization whose function template is more specialized
10927 // than the function template of F1 according to the partial
10928 // ordering rules of 14.5.5.2.
10929
10930 // The algorithm specified above is quadratic. We instead use a
10931 // two-pass algorithm (similar to the one used to identify the
10932 // best viable function in an overload set) that identifies the
10933 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +000010934
10935 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
10936 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
10937 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010938
Larisse Voufo98b20f12013-07-19 23:00:19 +000010939 // TODO: It looks like FailedCandidates does not serve much purpose
10940 // here, since the no_viable diagnostic has index 0.
10941 UnresolvedSetIterator Result = S.getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +000010942 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +000010943 SourceExpr->getLocStart(), S.PDiag(),
Richard Smith5179eb72016-06-28 19:03:57 +000010944 S.PDiag(diag::err_addr_ovl_ambiguous)
10945 << Matches[0].second->getDeclName(),
10946 S.PDiag(diag::note_ovl_candidate)
10947 << (unsigned)oc_function_template,
Larisse Voufo98b20f12013-07-19 23:00:19 +000010948 Complain, TargetFunctionType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010949
Douglas Gregorb491ed32011-02-19 21:32:49 +000010950 if (Result != MatchesCopy.end()) {
10951 // Make it the first and only element
10952 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
10953 Matches[0].second = cast<FunctionDecl>(*Result);
10954 Matches.resize(1);
George Burgess IV5f2ef452015-10-12 18:40:58 +000010955 } else
10956 HasComplained |= Complain;
John McCall58cc69d2010-01-27 01:50:18 +000010957 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010958
Douglas Gregorb491ed32011-02-19 21:32:49 +000010959 void EliminateAllTemplateMatches() {
10960 // [...] any function template specializations in the set are
10961 // eliminated if the set also contains a non-template function, [...]
10962 for (unsigned I = 0, N = Matches.size(); I != N; ) {
Craig Topperc3ec1492014-05-26 06:22:03 +000010963 if (Matches[I].second->getPrimaryTemplate() == nullptr)
Douglas Gregorb491ed32011-02-19 21:32:49 +000010964 ++I;
10965 else {
10966 Matches[I] = Matches[--N];
Artem Belevich94a55e82015-09-22 17:22:59 +000010967 Matches.resize(N);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010968 }
10969 }
10970 }
10971
Artem Belevich94a55e82015-09-22 17:22:59 +000010972 void EliminateSuboptimalCudaMatches() {
10973 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
10974 }
10975
Douglas Gregorb491ed32011-02-19 21:32:49 +000010976public:
10977 void ComplainNoMatchesFound() const {
10978 assert(Matches.empty());
10979 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
10980 << OvlExpr->getName() << TargetFunctionType
10981 << OvlExpr->getSourceRange();
Richard Smith0d905472013-08-14 00:00:44 +000010982 if (FailedCandidates.empty())
George Burgess IV5f21c712015-10-12 19:57:04 +000010983 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
10984 /*TakingAddress=*/true);
Richard Smith0d905472013-08-14 00:00:44 +000010985 else {
10986 // We have some deduction failure messages. Use them to diagnose
10987 // the function templates, and diagnose the non-template candidates
10988 // normally.
10989 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10990 IEnd = OvlExpr->decls_end();
10991 I != IEnd; ++I)
10992 if (FunctionDecl *Fun =
10993 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010994 if (!functionHasPassObjectSizeParams(Fun))
Richard Smithc2bebe92016-05-11 20:37:46 +000010995 S.NoteOverloadCandidate(*I, Fun, TargetFunctionType,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010996 /*TakingAddress=*/true);
Richard Smith0d905472013-08-14 00:00:44 +000010997 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
10998 }
10999 }
11000
Douglas Gregorb491ed32011-02-19 21:32:49 +000011001 bool IsInvalidFormOfPointerToMemberFunction() const {
11002 return TargetTypeIsNonStaticMemberFunction &&
11003 !OvlExprInfo.HasFormOfMemberPointer;
11004 }
David Majnemera4f7c7a2013-08-01 06:13:59 +000011005
Douglas Gregorb491ed32011-02-19 21:32:49 +000011006 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
11007 // TODO: Should we condition this on whether any functions might
11008 // have matched, or is it more appropriate to do that in callers?
11009 // TODO: a fixit wouldn't hurt.
11010 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
11011 << TargetType << OvlExpr->getSourceRange();
11012 }
David Majnemera4f7c7a2013-08-01 06:13:59 +000011013
11014 bool IsStaticMemberFunctionFromBoundPointer() const {
11015 return StaticMemberFunctionFromBoundPointer;
11016 }
11017
11018 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
11019 S.Diag(OvlExpr->getLocStart(),
11020 diag::err_invalid_form_pointer_member_function)
11021 << OvlExpr->getSourceRange();
11022 }
11023
Douglas Gregorb491ed32011-02-19 21:32:49 +000011024 void ComplainOfInvalidConversion() const {
11025 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
11026 << OvlExpr->getName() << TargetType;
11027 }
11028
11029 void ComplainMultipleMatchesFound() const {
11030 assert(Matches.size() > 1);
11031 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
11032 << OvlExpr->getName()
11033 << OvlExpr->getSourceRange();
George Burgess IV5f21c712015-10-12 19:57:04 +000011034 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11035 /*TakingAddress=*/true);
Douglas Gregorb491ed32011-02-19 21:32:49 +000011036 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +000011037
11038 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
11039
Douglas Gregorb491ed32011-02-19 21:32:49 +000011040 int getNumMatches() const { return Matches.size(); }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011041
Douglas Gregorb491ed32011-02-19 21:32:49 +000011042 FunctionDecl* getMatchingFunctionDecl() const {
Craig Topperc3ec1492014-05-26 06:22:03 +000011043 if (Matches.size() != 1) return nullptr;
Douglas Gregorb491ed32011-02-19 21:32:49 +000011044 return Matches[0].second;
11045 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011046
Douglas Gregorb491ed32011-02-19 21:32:49 +000011047 const DeclAccessPair* getMatchingFunctionAccessPair() const {
Craig Topperc3ec1492014-05-26 06:22:03 +000011048 if (Matches.size() != 1) return nullptr;
Douglas Gregorb491ed32011-02-19 21:32:49 +000011049 return &Matches[0].first;
11050 }
11051};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000011052}
Richard Smith17c00b42014-11-12 01:24:00 +000011053
Douglas Gregorb491ed32011-02-19 21:32:49 +000011054/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
11055/// an overloaded function (C++ [over.over]), where @p From is an
11056/// expression with overloaded function type and @p ToType is the type
11057/// we're trying to resolve to. For example:
11058///
11059/// @code
11060/// int f(double);
11061/// int f(int);
11062///
11063/// int (*pfd)(double) = f; // selects f(double)
11064/// @endcode
11065///
11066/// This routine returns the resulting FunctionDecl if it could be
11067/// resolved, and NULL otherwise. When @p Complain is true, this
11068/// routine will emit diagnostics if there is an error.
11069FunctionDecl *
Abramo Bagnara5001caa2011-11-19 11:44:21 +000011070Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
11071 QualType TargetType,
11072 bool Complain,
11073 DeclAccessPair &FoundResult,
11074 bool *pHadMultipleCandidates) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000011075 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara5001caa2011-11-19 11:44:21 +000011076
11077 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
11078 Complain);
Douglas Gregorb491ed32011-02-19 21:32:49 +000011079 int NumMatches = Resolver.getNumMatches();
Craig Topperc3ec1492014-05-26 06:22:03 +000011080 FunctionDecl *Fn = nullptr;
George Burgess IV5f2ef452015-10-12 18:40:58 +000011081 bool ShouldComplain = Complain && !Resolver.hasComplained();
11082 if (NumMatches == 0 && ShouldComplain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000011083 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
11084 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
11085 else
11086 Resolver.ComplainNoMatchesFound();
11087 }
George Burgess IV5f2ef452015-10-12 18:40:58 +000011088 else if (NumMatches > 1 && ShouldComplain)
Douglas Gregorb491ed32011-02-19 21:32:49 +000011089 Resolver.ComplainMultipleMatchesFound();
11090 else if (NumMatches == 1) {
11091 Fn = Resolver.getMatchingFunctionDecl();
11092 assert(Fn);
Richard Smith9095e5b2016-11-01 01:31:23 +000011093 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
11094 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
Douglas Gregorb491ed32011-02-19 21:32:49 +000011095 FoundResult = *Resolver.getMatchingFunctionAccessPair();
David Majnemera4f7c7a2013-08-01 06:13:59 +000011096 if (Complain) {
11097 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
11098 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
11099 else
11100 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
11101 }
Sebastian Redldf4b80e2009-10-17 21:12:09 +000011102 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +000011103
11104 if (pHadMultipleCandidates)
11105 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregorb491ed32011-02-19 21:32:49 +000011106 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +000011107}
11108
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011109/// \brief Given an expression that refers to an overloaded function, try to
George Burgess IV3cde9bf2016-03-19 21:36:10 +000011110/// resolve that function to a single function that can have its address taken.
11111/// This will modify `Pair` iff it returns non-null.
11112///
11113/// This routine can only realistically succeed if all but one candidates in the
11114/// overload set for SrcExpr cannot have their addresses taken.
11115FunctionDecl *
11116Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
11117 DeclAccessPair &Pair) {
11118 OverloadExpr::FindResult R = OverloadExpr::find(E);
11119 OverloadExpr *Ovl = R.Expression;
11120 FunctionDecl *Result = nullptr;
11121 DeclAccessPair DAP;
11122 // Don't use the AddressOfResolver because we're specifically looking for
11123 // cases where we have one overload candidate that lacks
11124 // enable_if/pass_object_size/...
11125 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
11126 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
11127 if (!FD)
11128 return nullptr;
11129
11130 if (!checkAddressOfFunctionIsAvailable(FD))
11131 continue;
11132
11133 // We have more than one result; quit.
11134 if (Result)
11135 return nullptr;
11136 DAP = I.getPair();
11137 Result = FD;
11138 }
11139
11140 if (Result)
11141 Pair = DAP;
11142 return Result;
11143}
11144
George Burgess IVbeca4a32016-06-08 00:34:22 +000011145/// \brief Given an overloaded function, tries to turn it into a non-overloaded
11146/// function reference using resolveAddressOfOnlyViableOverloadCandidate. This
11147/// will perform access checks, diagnose the use of the resultant decl, and, if
George Burgess IV1dbfa852017-05-09 04:06:24 +000011148/// requested, potentially perform a function-to-pointer decay.
George Burgess IVbeca4a32016-06-08 00:34:22 +000011149///
11150/// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails.
11151/// Otherwise, returns true. This may emit diagnostics and return true.
11152bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate(
George Burgess IV1dbfa852017-05-09 04:06:24 +000011153 ExprResult &SrcExpr, bool DoFunctionPointerConverion) {
George Burgess IVbeca4a32016-06-08 00:34:22 +000011154 Expr *E = SrcExpr.get();
11155 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
11156
11157 DeclAccessPair DAP;
11158 FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP);
11159 if (!Found)
11160 return false;
11161
11162 // Emitting multiple diagnostics for a function that is both inaccessible and
11163 // unavailable is consistent with our behavior elsewhere. So, always check
11164 // for both.
11165 DiagnoseUseOfDecl(Found, E->getExprLoc());
11166 CheckAddressOfMemberAccess(E, DAP);
11167 Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
George Burgess IV1dbfa852017-05-09 04:06:24 +000011168 if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType())
George Burgess IVbeca4a32016-06-08 00:34:22 +000011169 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
11170 else
11171 SrcExpr = Fixed;
11172 return true;
11173}
11174
George Burgess IV3cde9bf2016-03-19 21:36:10 +000011175/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011176/// resolve that overloaded function expression down to a single function.
11177///
11178/// This routine can only resolve template-ids that refer to a single function
11179/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011180/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011181/// as described in C++0x [temp.arg.explicit]p3.
Alp Toker67b47ac2013-10-20 18:48:56 +000011182///
11183/// If no template-ids are found, no diagnostics are emitted and NULL is
11184/// returned.
John McCall0009fcc2011-04-26 20:42:42 +000011185FunctionDecl *
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011186Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
John McCall0009fcc2011-04-26 20:42:42 +000011187 bool Complain,
11188 DeclAccessPair *FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011189 // C++ [over.over]p1:
11190 // [...] [Note: any redundant set of parentheses surrounding the
11191 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011192 // C++ [over.over]p1:
11193 // [...] The overloaded function name can be preceded by the &
11194 // operator.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011195
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011196 // If we didn't actually find any template-ids, we're done.
John McCall0009fcc2011-04-26 20:42:42 +000011197 if (!ovl->hasExplicitTemplateArgs())
Craig Topperc3ec1492014-05-26 06:22:03 +000011198 return nullptr;
John McCall1acbbb52010-02-02 06:20:04 +000011199
11200 TemplateArgumentListInfo ExplicitTemplateArgs;
James Y Knight04ec5bf2015-12-24 02:59:37 +000011201 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
Larisse Voufo98b20f12013-07-19 23:00:19 +000011202 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011203
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011204 // Look through all of the overloaded functions, searching for one
11205 // whose type matches exactly.
Craig Topperc3ec1492014-05-26 06:22:03 +000011206 FunctionDecl *Matched = nullptr;
John McCall0009fcc2011-04-26 20:42:42 +000011207 for (UnresolvedSetIterator I = ovl->decls_begin(),
11208 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011209 // C++0x [temp.arg.explicit]p3:
11210 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011211 // where deduction is not done, if a template argument list is
11212 // specified and it, along with any default template arguments,
11213 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011214 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +000011215 FunctionTemplateDecl *FunctionTemplate
11216 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011217
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011218 // C++ [over.over]p2:
11219 // If the name is a function template, template argument deduction is
11220 // done (14.8.2.2), and if the argument deduction succeeds, the
11221 // resulting template argument list is used to generate a single
11222 // function template specialization, which is added to the set of
11223 // overloaded functions considered.
Craig Topperc3ec1492014-05-26 06:22:03 +000011224 FunctionDecl *Specialization = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +000011225 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011226 if (TemplateDeductionResult Result
11227 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
Douglas Gregor19a41f12013-04-17 08:45:07 +000011228 Specialization, Info,
Richard Smithbaa47832016-12-01 02:11:49 +000011229 /*IsAddressOfFunction*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000011230 // Make a note of the failed deduction for diagnostics.
11231 // TODO: Actually use the failed-deduction info?
11232 FailedCandidates.addCandidate()
Richard Smithc2bebe92016-05-11 20:37:46 +000011233 .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
Larisse Voufo98b20f12013-07-19 23:00:19 +000011234 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011235 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011236 }
11237
John McCall0009fcc2011-04-26 20:42:42 +000011238 assert(Specialization && "no specialization and no error?");
11239
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011240 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +000011241 if (Matched) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000011242 if (Complain) {
John McCall0009fcc2011-04-26 20:42:42 +000011243 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
11244 << ovl->getName();
11245 NoteAllOverloadCandidates(ovl);
Douglas Gregorb491ed32011-02-19 21:32:49 +000011246 }
Craig Topperc3ec1492014-05-26 06:22:03 +000011247 return nullptr;
John McCall0009fcc2011-04-26 20:42:42 +000011248 }
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011249
John McCall0009fcc2011-04-26 20:42:42 +000011250 Matched = Specialization;
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011251 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011252 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011253
Richard Smith9095e5b2016-11-01 01:31:23 +000011254 if (Matched &&
11255 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
Craig Topperc3ec1492014-05-26 06:22:03 +000011256 return nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +000011257
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011258 return Matched;
11259}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011260
Douglas Gregor1beec452011-03-12 01:48:56 +000011261
11262
11263
John McCall50a2c2c2011-10-11 23:14:30 +000011264// Resolve and fix an overloaded expression that can be resolved
11265// because it identifies a single function template specialization.
11266//
Douglas Gregor1beec452011-03-12 01:48:56 +000011267// Last three arguments should only be supplied if Complain = true
John McCall50a2c2c2011-10-11 23:14:30 +000011268//
11269// Return true if it was logically possible to so resolve the
11270// expression, regardless of whether or not it succeeded. Always
11271// returns true if 'complain' is set.
11272bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
11273 ExprResult &SrcExpr, bool doFunctionPointerConverion,
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011274 bool complain, SourceRange OpRangeForComplaining,
11275 QualType DestTypeForComplaining,
John McCall0009fcc2011-04-26 20:42:42 +000011276 unsigned DiagIDForComplaining) {
John McCall50a2c2c2011-10-11 23:14:30 +000011277 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregor1beec452011-03-12 01:48:56 +000011278
John McCall50a2c2c2011-10-11 23:14:30 +000011279 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregor1beec452011-03-12 01:48:56 +000011280
John McCall0009fcc2011-04-26 20:42:42 +000011281 DeclAccessPair found;
11282 ExprResult SingleFunctionExpression;
11283 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
11284 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011285 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall50a2c2c2011-10-11 23:14:30 +000011286 SrcExpr = ExprError();
11287 return true;
11288 }
John McCall0009fcc2011-04-26 20:42:42 +000011289
11290 // It is only correct to resolve to an instance method if we're
11291 // resolving a form that's permitted to be a pointer to member.
11292 // Otherwise we'll end up making a bound member expression, which
11293 // is illegal in all the contexts we resolve like this.
11294 if (!ovl.HasFormOfMemberPointer &&
11295 isa<CXXMethodDecl>(fn) &&
11296 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall50a2c2c2011-10-11 23:14:30 +000011297 if (!complain) return false;
11298
11299 Diag(ovl.Expression->getExprLoc(),
11300 diag::err_bound_member_function)
11301 << 0 << ovl.Expression->getSourceRange();
11302
11303 // TODO: I believe we only end up here if there's a mix of
11304 // static and non-static candidates (otherwise the expression
11305 // would have 'bound member' type, not 'overload' type).
11306 // Ideally we would note which candidate was chosen and why
11307 // the static candidates were rejected.
11308 SrcExpr = ExprError();
11309 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000011310 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +000011311
Sylvestre Ledrua5202662012-07-31 06:56:50 +000011312 // Fix the expression to refer to 'fn'.
John McCall0009fcc2011-04-26 20:42:42 +000011313 SingleFunctionExpression =
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011314 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
John McCall0009fcc2011-04-26 20:42:42 +000011315
11316 // If desired, do function-to-pointer decay.
John McCall50a2c2c2011-10-11 23:14:30 +000011317 if (doFunctionPointerConverion) {
John McCall0009fcc2011-04-26 20:42:42 +000011318 SingleFunctionExpression =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011319 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
John McCall50a2c2c2011-10-11 23:14:30 +000011320 if (SingleFunctionExpression.isInvalid()) {
11321 SrcExpr = ExprError();
11322 return true;
11323 }
11324 }
John McCall0009fcc2011-04-26 20:42:42 +000011325 }
11326
11327 if (!SingleFunctionExpression.isUsable()) {
11328 if (complain) {
11329 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
11330 << ovl.Expression->getName()
11331 << DestTypeForComplaining
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000011332 << OpRangeForComplaining
John McCall0009fcc2011-04-26 20:42:42 +000011333 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall50a2c2c2011-10-11 23:14:30 +000011334 NoteAllOverloadCandidates(SrcExpr.get());
11335
11336 SrcExpr = ExprError();
11337 return true;
11338 }
11339
11340 return false;
John McCall0009fcc2011-04-26 20:42:42 +000011341 }
11342
John McCall50a2c2c2011-10-11 23:14:30 +000011343 SrcExpr = SingleFunctionExpression;
11344 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000011345}
11346
Douglas Gregorcabea402009-09-22 15:41:20 +000011347/// \brief Add a single candidate to the overload set.
11348static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +000011349 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +000011350 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011351 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000011352 OverloadCandidateSet &CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +000011353 bool PartialOverloading,
11354 bool KnownValid) {
John McCalla0296f72010-03-19 07:35:19 +000011355 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +000011356 if (isa<UsingShadowDecl>(Callee))
11357 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
11358
Douglas Gregorcabea402009-09-22 15:41:20 +000011359 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith95ce4f62011-06-26 22:19:54 +000011360 if (ExplicitTemplateArgs) {
11361 assert(!KnownValid && "Explicit template arguments?");
11362 return;
11363 }
Bruno Cardoso Lopes37029632017-04-26 20:13:45 +000011364 // Prevent ill-formed function decls to be added as overload candidates.
11365 if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
11366 return;
11367
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011368 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
11369 /*SuppressUsedConversions=*/false,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011370 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000011371 return;
John McCalld14a8642009-11-21 08:51:07 +000011372 }
11373
11374 if (FunctionTemplateDecl *FuncTemplate
11375 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +000011376 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011377 ExplicitTemplateArgs, Args, CandidateSet,
11378 /*SuppressUsedConversions=*/false,
11379 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +000011380 return;
11381 }
11382
Richard Smith95ce4f62011-06-26 22:19:54 +000011383 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregorcabea402009-09-22 15:41:20 +000011384}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011385
Douglas Gregorcabea402009-09-22 15:41:20 +000011386/// \brief Add the overload candidates named by callee and/or found by argument
11387/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +000011388void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011389 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000011390 OverloadCandidateSet &CandidateSet,
11391 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +000011392
11393#ifndef NDEBUG
11394 // Verify that ArgumentDependentLookup is consistent with the rules
11395 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +000011396 //
Douglas Gregorcabea402009-09-22 15:41:20 +000011397 // Let X be the lookup set produced by unqualified lookup (3.4.1)
11398 // and let Y be the lookup set produced by argument dependent
11399 // lookup (defined as follows). If X contains
11400 //
11401 // -- a declaration of a class member, or
11402 //
11403 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +000011404 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +000011405 //
11406 // -- a declaration that is neither a function or a function
11407 // template
11408 //
11409 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +000011410
John McCall57500772009-12-16 12:17:52 +000011411 if (ULE->requiresADL()) {
11412 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11413 E = ULE->decls_end(); I != E; ++I) {
11414 assert(!(*I)->getDeclContext()->isRecord());
11415 assert(isa<UsingShadowDecl>(*I) ||
11416 !(*I)->getDeclContext()->isFunctionOrMethod());
11417 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +000011418 }
11419 }
11420#endif
11421
John McCall57500772009-12-16 12:17:52 +000011422 // It would be nice to avoid this copy.
11423 TemplateArgumentListInfo TABuffer;
Craig Topperc3ec1492014-05-26 06:22:03 +000011424 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
John McCall57500772009-12-16 12:17:52 +000011425 if (ULE->hasExplicitTemplateArgs()) {
11426 ULE->copyTemplateArgumentsInto(TABuffer);
11427 ExplicitTemplateArgs = &TABuffer;
11428 }
11429
11430 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11431 E = ULE->decls_end(); I != E; ++I)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011432 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
11433 CandidateSet, PartialOverloading,
11434 /*KnownValid*/ true);
John McCalld14a8642009-11-21 08:51:07 +000011435
John McCall57500772009-12-16 12:17:52 +000011436 if (ULE->requiresADL())
Richard Smith100b24a2014-04-17 01:52:14 +000011437 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011438 Args, ExplicitTemplateArgs,
Richard Smithb6626742012-10-18 17:56:02 +000011439 CandidateSet, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000011440}
John McCalld681c392009-12-16 08:11:27 +000011441
Richard Smith0603bbb2013-06-12 22:56:54 +000011442/// Determine whether a declaration with the specified name could be moved into
11443/// a different namespace.
11444static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
11445 switch (Name.getCXXOverloadedOperator()) {
11446 case OO_New: case OO_Array_New:
11447 case OO_Delete: case OO_Array_Delete:
11448 return false;
11449
11450 default:
11451 return true;
11452 }
11453}
11454
Richard Smith998a5912011-06-05 22:42:48 +000011455/// Attempt to recover from an ill-formed use of a non-dependent name in a
11456/// template, where the non-dependent name was declared after the template
11457/// was defined. This is common in code written for a compilers which do not
11458/// correctly implement two-stage name lookup.
11459///
11460/// Returns true if a viable candidate was found and a diagnostic was issued.
11461static bool
11462DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
11463 const CXXScopeSpec &SS, LookupResult &R,
Richard Smith100b24a2014-04-17 01:52:14 +000011464 OverloadCandidateSet::CandidateSetKind CSK,
Richard Smith998a5912011-06-05 22:42:48 +000011465 TemplateArgumentListInfo *ExplicitTemplateArgs,
Hans Wennborg64937c62015-06-11 21:21:57 +000011466 ArrayRef<Expr *> Args,
11467 bool *DoDiagnoseEmptyLookup = nullptr) {
Richard Smith51ec0cf2017-02-21 01:17:38 +000011468 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
Richard Smith998a5912011-06-05 22:42:48 +000011469 return false;
11470
11471 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewyckyfcd5e7a2012-03-14 20:41:00 +000011472 if (DC->isTransparentContext())
11473 continue;
11474
Richard Smith998a5912011-06-05 22:42:48 +000011475 SemaRef.LookupQualifiedName(R, DC);
11476
11477 if (!R.empty()) {
11478 R.suppressDiagnostics();
11479
11480 if (isa<CXXRecordDecl>(DC)) {
11481 // Don't diagnose names we find in classes; we get much better
11482 // diagnostics for these from DiagnoseEmptyLookup.
11483 R.clear();
Hans Wennborg64937c62015-06-11 21:21:57 +000011484 if (DoDiagnoseEmptyLookup)
11485 *DoDiagnoseEmptyLookup = true;
Richard Smith998a5912011-06-05 22:42:48 +000011486 return false;
11487 }
11488
Richard Smith100b24a2014-04-17 01:52:14 +000011489 OverloadCandidateSet Candidates(FnLoc, CSK);
Richard Smith998a5912011-06-05 22:42:48 +000011490 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
11491 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011492 ExplicitTemplateArgs, Args,
Richard Smith95ce4f62011-06-26 22:19:54 +000011493 Candidates, false, /*KnownValid*/ false);
Richard Smith998a5912011-06-05 22:42:48 +000011494
11495 OverloadCandidateSet::iterator Best;
Richard Smith95ce4f62011-06-26 22:19:54 +000011496 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smith998a5912011-06-05 22:42:48 +000011497 // No viable functions. Don't bother the user with notes for functions
11498 // which don't work and shouldn't be found anyway.
Richard Smith95ce4f62011-06-26 22:19:54 +000011499 R.clear();
Richard Smith998a5912011-06-05 22:42:48 +000011500 return false;
Richard Smith95ce4f62011-06-26 22:19:54 +000011501 }
Richard Smith998a5912011-06-05 22:42:48 +000011502
11503 // Find the namespaces where ADL would have looked, and suggest
11504 // declaring the function there instead.
11505 Sema::AssociatedNamespaceSet AssociatedNamespaces;
11506 Sema::AssociatedClassSet AssociatedClasses;
John McCall7d8b0412012-08-24 20:38:34 +000011507 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
Richard Smith998a5912011-06-05 22:42:48 +000011508 AssociatedNamespaces,
11509 AssociatedClasses);
Chandler Carruthd50f1692011-06-05 23:36:55 +000011510 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smith0603bbb2013-06-12 22:56:54 +000011511 if (canBeDeclaredInNamespace(R.getLookupName())) {
11512 DeclContext *Std = SemaRef.getStdNamespace();
11513 for (Sema::AssociatedNamespaceSet::iterator
11514 it = AssociatedNamespaces.begin(),
11515 end = AssociatedNamespaces.end(); it != end; ++it) {
11516 // Never suggest declaring a function within namespace 'std'.
11517 if (Std && Std->Encloses(*it))
11518 continue;
Richard Smith21bae432012-12-22 02:46:14 +000011519
Richard Smith0603bbb2013-06-12 22:56:54 +000011520 // Never suggest declaring a function within a namespace with a
11521 // reserved name, like __gnu_cxx.
11522 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
11523 if (NS &&
11524 NS->getQualifiedNameAsString().find("__") != std::string::npos)
11525 continue;
11526
11527 SuggestedNamespaces.insert(*it);
11528 }
Richard Smith998a5912011-06-05 22:42:48 +000011529 }
11530
11531 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
11532 << R.getLookupName();
Chandler Carruthd50f1692011-06-05 23:36:55 +000011533 if (SuggestedNamespaces.empty()) {
Richard Smith998a5912011-06-05 22:42:48 +000011534 SemaRef.Diag(Best->Function->getLocation(),
11535 diag::note_not_found_by_two_phase_lookup)
11536 << R.getLookupName() << 0;
Chandler Carruthd50f1692011-06-05 23:36:55 +000011537 } else if (SuggestedNamespaces.size() == 1) {
Richard Smith998a5912011-06-05 22:42:48 +000011538 SemaRef.Diag(Best->Function->getLocation(),
11539 diag::note_not_found_by_two_phase_lookup)
Chandler Carruthd50f1692011-06-05 23:36:55 +000011540 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smith998a5912011-06-05 22:42:48 +000011541 } else {
11542 // FIXME: It would be useful to list the associated namespaces here,
11543 // but the diagnostics infrastructure doesn't provide a way to produce
11544 // a localized representation of a list of items.
11545 SemaRef.Diag(Best->Function->getLocation(),
11546 diag::note_not_found_by_two_phase_lookup)
11547 << R.getLookupName() << 2;
11548 }
11549
11550 // Try to recover by calling this function.
11551 return true;
11552 }
11553
11554 R.clear();
11555 }
11556
11557 return false;
11558}
11559
11560/// Attempt to recover from ill-formed use of a non-dependent operator in a
11561/// template, where the non-dependent operator was declared after the template
11562/// was defined.
11563///
11564/// Returns true if a viable candidate was found and a diagnostic was issued.
11565static bool
11566DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
11567 SourceLocation OpLoc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011568 ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +000011569 DeclarationName OpName =
11570 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
11571 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
11572 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Richard Smith100b24a2014-04-17 01:52:14 +000011573 OverloadCandidateSet::CSK_Operator,
Craig Topperc3ec1492014-05-26 06:22:03 +000011574 /*ExplicitTemplateArgs=*/nullptr, Args);
Richard Smith998a5912011-06-05 22:42:48 +000011575}
11576
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000011577namespace {
Richard Smith88d67f32012-09-25 04:46:05 +000011578class BuildRecoveryCallExprRAII {
11579 Sema &SemaRef;
11580public:
11581 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
11582 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
11583 SemaRef.IsBuildingRecoveryCallExpr = true;
11584 }
11585
11586 ~BuildRecoveryCallExprRAII() {
11587 SemaRef.IsBuildingRecoveryCallExpr = false;
11588 }
11589};
11590
Alexander Kornienkoab9db512015-06-22 23:07:51 +000011591}
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000011592
Kaelyn Takata89c881b2014-10-27 18:07:29 +000011593static std::unique_ptr<CorrectionCandidateCallback>
11594MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
11595 bool HasTemplateArgs, bool AllowTypoCorrection) {
11596 if (!AllowTypoCorrection)
11597 return llvm::make_unique<NoTypoCorrectionCCC>();
11598 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
11599 HasTemplateArgs, ME);
11600}
11601
John McCalld681c392009-12-16 08:11:27 +000011602/// Attempts to recover from a call where no functions were found.
11603///
11604/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +000011605static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +000011606BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +000011607 UnresolvedLookupExpr *ULE,
11608 SourceLocation LParenLoc,
Craig Toppere3d2ecbe2014-06-28 23:22:33 +000011609 MutableArrayRef<Expr *> Args,
Richard Smith998a5912011-06-05 22:42:48 +000011610 SourceLocation RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000011611 bool EmptyLookup, bool AllowTypoCorrection) {
Richard Smith88d67f32012-09-25 04:46:05 +000011612 // Do not try to recover if it is already building a recovery call.
11613 // This stops infinite loops for template instantiations like
11614 //
11615 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
11616 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
11617 //
11618 if (SemaRef.IsBuildingRecoveryCallExpr)
11619 return ExprError();
11620 BuildRecoveryCallExprRAII RCE(SemaRef);
John McCalld681c392009-12-16 08:11:27 +000011621
11622 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +000011623 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +000011624 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCalld681c392009-12-16 08:11:27 +000011625
John McCall57500772009-12-16 12:17:52 +000011626 TemplateArgumentListInfo TABuffer;
Craig Topperc3ec1492014-05-26 06:22:03 +000011627 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
John McCall57500772009-12-16 12:17:52 +000011628 if (ULE->hasExplicitTemplateArgs()) {
11629 ULE->copyTemplateArgumentsInto(TABuffer);
11630 ExplicitTemplateArgs = &TABuffer;
11631 }
11632
John McCalld681c392009-12-16 08:11:27 +000011633 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
11634 Sema::LookupOrdinaryName);
Hans Wennborg64937c62015-06-11 21:21:57 +000011635 bool DoDiagnoseEmptyLookup = EmptyLookup;
Richard Smith998a5912011-06-05 22:42:48 +000011636 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Richard Smith100b24a2014-04-17 01:52:14 +000011637 OverloadCandidateSet::CSK_Normal,
Hans Wennborg64937c62015-06-11 21:21:57 +000011638 ExplicitTemplateArgs, Args,
11639 &DoDiagnoseEmptyLookup) &&
11640 (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup(
11641 S, SS, R,
11642 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
11643 ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
11644 ExplicitTemplateArgs, Args)))
John McCallfaf5fb42010-08-26 23:41:50 +000011645 return ExprError();
John McCalld681c392009-12-16 08:11:27 +000011646
John McCall57500772009-12-16 12:17:52 +000011647 assert(!R.empty() && "lookup results empty despite recovery");
11648
Richard Smith151c4562016-12-20 21:35:28 +000011649 // If recovery created an ambiguity, just bail out.
11650 if (R.isAmbiguous()) {
11651 R.suppressDiagnostics();
11652 return ExprError();
11653 }
11654
John McCall57500772009-12-16 12:17:52 +000011655 // Build an implicit member call if appropriate. Just drop the
11656 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +000011657 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +000011658 if ((*R.begin())->isCXXClassMember())
Aaron Ballman6924dcd2015-09-01 14:49:24 +000011659 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
11660 ExplicitTemplateArgs, S);
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000011661 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnara7945c982012-01-27 09:46:47 +000011662 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000011663 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +000011664 else
11665 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
11666
11667 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +000011668 return ExprError();
John McCall57500772009-12-16 12:17:52 +000011669
11670 // This shouldn't cause an infinite loop because we're giving it
Richard Smith998a5912011-06-05 22:42:48 +000011671 // an expression with viable lookup results, which should never
John McCall57500772009-12-16 12:17:52 +000011672 // end up here.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011673 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011674 MultiExprArg(Args.data(), Args.size()),
11675 RParenLoc);
John McCalld681c392009-12-16 08:11:27 +000011676}
Douglas Gregor4038cf42010-06-08 17:35:15 +000011677
Sam Panzer0f384432012-08-21 00:52:01 +000011678/// \brief Constructs and populates an OverloadedCandidateSet from
11679/// the given function.
11680/// \returns true when an the ExprResult output parameter has been set.
11681bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
11682 UnresolvedLookupExpr *ULE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011683 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011684 SourceLocation RParenLoc,
11685 OverloadCandidateSet *CandidateSet,
11686 ExprResult *Result) {
John McCall57500772009-12-16 12:17:52 +000011687#ifndef NDEBUG
11688 if (ULE->requiresADL()) {
11689 // To do ADL, we must have found an unqualified name.
11690 assert(!ULE->getQualifier() && "qualified name with ADL");
11691
11692 // We don't perform ADL for implicit declarations of builtins.
11693 // Verify that this was correctly set up.
11694 FunctionDecl *F;
11695 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
11696 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
11697 F->getBuiltinID() && F->isImplicit())
David Blaikie83d382b2011-09-23 05:06:16 +000011698 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011699
John McCall57500772009-12-16 12:17:52 +000011700 // We don't perform ADL in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011701 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smithb6626742012-10-18 17:56:02 +000011702 }
John McCall57500772009-12-16 12:17:52 +000011703#endif
11704
John McCall4124c492011-10-17 18:40:02 +000011705 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011706 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
Sam Panzer0f384432012-08-21 00:52:01 +000011707 *Result = ExprError();
11708 return true;
11709 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +000011710
John McCall57500772009-12-16 12:17:52 +000011711 // Add the functions denoted by the callee to the set of candidate
11712 // functions, including those from argument-dependent lookup.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011713 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
John McCalld681c392009-12-16 08:11:27 +000011714
Hans Wennborgb2747382015-06-12 21:23:23 +000011715 if (getLangOpts().MSVCCompat &&
11716 CurContext->isDependentContext() && !isSFINAEContext() &&
Hans Wennborg64937c62015-06-11 21:21:57 +000011717 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
11718
11719 OverloadCandidateSet::iterator Best;
11720 if (CandidateSet->empty() ||
11721 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) ==
11722 OR_No_Viable_Function) {
11723 // In Microsoft mode, if we are inside a template class member function then
11724 // create a type dependent CallExpr. The goal is to postpone name lookup
11725 // to instantiation time to be able to search into type dependent base
11726 // classes.
11727 CallExpr *CE = new (Context) CallExpr(
11728 Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc);
Sebastian Redlb49c46c2011-09-24 17:48:00 +000011729 CE->setTypeDependent(true);
Richard Smithed9b8f02015-09-23 21:30:47 +000011730 CE->setValueDependent(true);
11731 CE->setInstantiationDependent(true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011732 *Result = CE;
Sam Panzer0f384432012-08-21 00:52:01 +000011733 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +000011734 }
Francois Pichetbcf64712011-09-07 00:14:57 +000011735 }
John McCalld681c392009-12-16 08:11:27 +000011736
Hans Wennborg64937c62015-06-11 21:21:57 +000011737 if (CandidateSet->empty())
11738 return false;
11739
John McCall4124c492011-10-17 18:40:02 +000011740 UnbridgedCasts.restore();
Sam Panzer0f384432012-08-21 00:52:01 +000011741 return false;
11742}
John McCall4124c492011-10-17 18:40:02 +000011743
Sam Panzer0f384432012-08-21 00:52:01 +000011744/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
11745/// the completed call expression. If overload resolution fails, emits
11746/// diagnostics and returns ExprError()
11747static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11748 UnresolvedLookupExpr *ULE,
11749 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011750 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011751 SourceLocation RParenLoc,
11752 Expr *ExecConfig,
11753 OverloadCandidateSet *CandidateSet,
11754 OverloadCandidateSet::iterator *Best,
11755 OverloadingResult OverloadResult,
11756 bool AllowTypoCorrection) {
11757 if (CandidateSet->empty())
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011758 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011759 RParenLoc, /*EmptyLookup=*/true,
11760 AllowTypoCorrection);
11761
11762 switch (OverloadResult) {
John McCall57500772009-12-16 12:17:52 +000011763 case OR_Success: {
Sam Panzer0f384432012-08-21 00:52:01 +000011764 FunctionDecl *FDecl = (*Best)->Function;
Sam Panzer0f384432012-08-21 00:52:01 +000011765 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000011766 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
11767 return ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000011768 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011769 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11770 ExecConfig);
John McCall57500772009-12-16 12:17:52 +000011771 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011772
Richard Smith998a5912011-06-05 22:42:48 +000011773 case OR_No_Viable_Function: {
11774 // Try to recover by looking for viable functions which the user might
11775 // have meant to call.
Sam Panzer0f384432012-08-21 00:52:01 +000011776 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011777 Args, RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000011778 /*EmptyLookup=*/false,
11779 AllowTypoCorrection);
Richard Smith998a5912011-06-05 22:42:48 +000011780 if (!Recovery.isInvalid())
11781 return Recovery;
11782
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011783 // If the user passes in a function that we can't take the address of, we
11784 // generally end up emitting really bad error messages. Here, we attempt to
11785 // emit better ones.
11786 for (const Expr *Arg : Args) {
11787 if (!Arg->getType()->isFunctionType())
11788 continue;
11789 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
11790 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
11791 if (FD &&
11792 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
11793 Arg->getExprLoc()))
11794 return ExprError();
11795 }
11796 }
11797
11798 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_no_viable_function_in_call)
11799 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011800 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011801 break;
Richard Smith998a5912011-06-05 22:42:48 +000011802 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011803
11804 case OR_Ambiguous:
Sam Panzer0f384432012-08-21 00:52:01 +000011805 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +000011806 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011807 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011808 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000011809
Sam Panzer0f384432012-08-21 00:52:01 +000011810 case OR_Deleted: {
11811 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
11812 << (*Best)->Function->isDeleted()
11813 << ULE->getName()
11814 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
11815 << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011816 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Argyrios Kyrtzidis3eaa22a2011-11-04 15:58:13 +000011817
Sam Panzer0f384432012-08-21 00:52:01 +000011818 // We emitted an error for the unvailable/deleted function call but keep
11819 // the call in the AST.
11820 FunctionDecl *FDecl = (*Best)->Function;
11821 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011822 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11823 ExecConfig);
Sam Panzer0f384432012-08-21 00:52:01 +000011824 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011825 }
11826
Douglas Gregorb412e172010-07-25 18:17:45 +000011827 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +000011828 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011829}
11830
George Burgess IV7204ed92016-01-07 02:26:57 +000011831static void markUnaddressableCandidatesUnviable(Sema &S,
11832 OverloadCandidateSet &CS) {
11833 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
11834 if (I->Viable &&
11835 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
11836 I->Viable = false;
11837 I->FailureKind = ovl_fail_addr_not_available;
11838 }
11839 }
11840}
11841
Sam Panzer0f384432012-08-21 00:52:01 +000011842/// BuildOverloadedCallExpr - Given the call expression that calls Fn
11843/// (which eventually refers to the declaration Func) and the call
11844/// arguments Args/NumArgs, attempt to resolve the function call down
11845/// to a specific function. If overload resolution succeeds, returns
11846/// the call expression produced by overload resolution.
11847/// Otherwise, emits diagnostics and returns ExprError.
11848ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
11849 UnresolvedLookupExpr *ULE,
11850 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011851 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011852 SourceLocation RParenLoc,
11853 Expr *ExecConfig,
George Burgess IV7204ed92016-01-07 02:26:57 +000011854 bool AllowTypoCorrection,
11855 bool CalleesAddressIsTaken) {
Richard Smith100b24a2014-04-17 01:52:14 +000011856 OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
11857 OverloadCandidateSet::CSK_Normal);
Sam Panzer0f384432012-08-21 00:52:01 +000011858 ExprResult result;
11859
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011860 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
11861 &result))
Sam Panzer0f384432012-08-21 00:52:01 +000011862 return result;
11863
George Burgess IV7204ed92016-01-07 02:26:57 +000011864 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
11865 // functions that aren't addressible are considered unviable.
11866 if (CalleesAddressIsTaken)
11867 markUnaddressableCandidatesUnviable(*this, CandidateSet);
11868
Sam Panzer0f384432012-08-21 00:52:01 +000011869 OverloadCandidateSet::iterator Best;
11870 OverloadingResult OverloadResult =
11871 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
11872
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011873 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011874 RParenLoc, ExecConfig, &CandidateSet,
11875 &Best, OverloadResult,
11876 AllowTypoCorrection);
11877}
11878
John McCall4c4c1df2010-01-26 03:27:55 +000011879static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +000011880 return Functions.size() > 1 ||
11881 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
11882}
11883
Douglas Gregor084d8552009-03-13 23:49:33 +000011884/// \brief Create a unary operation that may resolve to an overloaded
11885/// operator.
11886///
11887/// \param OpLoc The location of the operator itself (e.g., '*').
11888///
Craig Toppera92ffb02015-12-10 08:51:49 +000011889/// \param Opc The UnaryOperatorKind that describes this operator.
Douglas Gregor084d8552009-03-13 23:49:33 +000011890///
James Dennett18348b62012-06-22 08:52:37 +000011891/// \param Fns The set of non-member functions that will be
Douglas Gregor084d8552009-03-13 23:49:33 +000011892/// considered by overload resolution. The caller needs to build this
11893/// set based on the context using, e.g.,
11894/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11895/// set should not contain any member functions; those will be added
11896/// by CreateOverloadedUnaryOp().
11897///
James Dennett91738ff2012-06-22 10:32:46 +000011898/// \param Input The input argument.
John McCalldadc5752010-08-24 06:29:42 +000011899ExprResult
Craig Toppera92ffb02015-12-10 08:51:49 +000011900Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
John McCall4c4c1df2010-01-26 03:27:55 +000011901 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +000011902 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +000011903 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
11904 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
11905 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011906 // TODO: provide better source location info.
11907 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +000011908
John McCall4124c492011-10-17 18:40:02 +000011909 if (checkPlaceholderForOverload(*this, Input))
11910 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011911
Craig Topperc3ec1492014-05-26 06:22:03 +000011912 Expr *Args[2] = { Input, nullptr };
Douglas Gregor084d8552009-03-13 23:49:33 +000011913 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +000011914
Douglas Gregor084d8552009-03-13 23:49:33 +000011915 // For post-increment and post-decrement, add the implicit '0' as
11916 // the second argument, so that we know this is a post-increment or
11917 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +000011918 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +000011919 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +000011920 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
11921 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +000011922 NumArgs = 2;
11923 }
11924
Richard Smithe54c3072013-05-05 15:51:06 +000011925 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
11926
Douglas Gregor084d8552009-03-13 23:49:33 +000011927 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +000011928 if (Fns.empty())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011929 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
11930 VK_RValue, OK_Ordinary, OpLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011931
Craig Topperc3ec1492014-05-26 06:22:03 +000011932 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +000011933 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000011934 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000011935 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000011936 /*ADL*/ true, IsOverloaded(Fns),
11937 Fns.begin(), Fns.end());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011938 return new (Context)
11939 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
Adam Nemet484aa452017-03-27 19:17:25 +000011940 VK_RValue, OpLoc, FPOptions());
Douglas Gregor084d8552009-03-13 23:49:33 +000011941 }
11942
11943 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000011944 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
Douglas Gregor084d8552009-03-13 23:49:33 +000011945
11946 // Add the candidates from the given function set.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011947 AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000011948
11949 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000011950 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000011951
John McCall4c4c1df2010-01-26 03:27:55 +000011952 // Add candidates from ADL.
Richard Smith100b24a2014-04-17 01:52:14 +000011953 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
Craig Topperc3ec1492014-05-26 06:22:03 +000011954 /*ExplicitTemplateArgs*/nullptr,
11955 CandidateSet);
John McCall4c4c1df2010-01-26 03:27:55 +000011956
Douglas Gregor084d8552009-03-13 23:49:33 +000011957 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011958 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000011959
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011960 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11961
Douglas Gregor084d8552009-03-13 23:49:33 +000011962 // Perform overload resolution.
11963 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011964 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +000011965 case OR_Success: {
11966 // We found a built-in operator or an overloaded operator.
11967 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +000011968
Douglas Gregor084d8552009-03-13 23:49:33 +000011969 if (FnDecl) {
Akira Hatanaka22461672017-07-13 06:08:27 +000011970 Expr *Base = nullptr;
Douglas Gregor084d8552009-03-13 23:49:33 +000011971 // We matched an overloaded operator. Build a call to that
11972 // operator.
Mike Stump11289f42009-09-09 15:08:12 +000011973
Douglas Gregor084d8552009-03-13 23:49:33 +000011974 // Convert the arguments.
11975 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Craig Topperc3ec1492014-05-26 06:22:03 +000011976 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000011977
John Wiegley01296292011-04-08 18:41:53 +000011978 ExprResult InputRes =
Craig Topperc3ec1492014-05-26 06:22:03 +000011979 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000011980 Best->FoundDecl, Method);
11981 if (InputRes.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000011982 return ExprError();
Akira Hatanaka22461672017-07-13 06:08:27 +000011983 Base = Input = InputRes.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000011984 } else {
11985 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000011986 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +000011987 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000011988 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +000011989 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011990 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +000011991 Input);
Douglas Gregore6600372009-12-23 17:40:29 +000011992 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000011993 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011994 Input = InputInit.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000011995 }
11996
Douglas Gregor084d8552009-03-13 23:49:33 +000011997 // Build the actual expression node.
Nick Lewycky134af912013-02-07 05:08:22 +000011998 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
Akira Hatanaka22461672017-07-13 06:08:27 +000011999 Base, HadMultipleCandidates,
12000 OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000012001 if (FnExpr.isInvalid())
12002 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +000012003
Richard Smithc1564702013-11-15 02:58:23 +000012004 // Determine the result type.
Alp Toker314cc812014-01-25 16:55:45 +000012005 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000012006 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12007 ResultTy = ResultTy.getNonLValueExprType(Context);
12008
Eli Friedman030eee42009-11-18 03:58:17 +000012009 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +000012010 CallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012011 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
Adam Nemet484aa452017-03-27 19:17:25 +000012012 ResultTy, VK, OpLoc, FPOptions());
John McCall4fa0d5f2010-05-06 18:15:07 +000012013
Alp Toker314cc812014-01-25 16:55:45 +000012014 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
Anders Carlssonf64a3da2009-10-13 21:19:37 +000012015 return ExprError();
12016
George Burgess IVce6284b2017-01-28 02:19:40 +000012017 if (CheckFunctionCall(FnDecl, TheCall,
12018 FnDecl->getType()->castAs<FunctionProtoType>()))
12019 return ExprError();
12020
John McCallb268a282010-08-23 23:25:46 +000012021 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +000012022 } else {
12023 // We matched a built-in operator. Convert the arguments, then
12024 // break out so that we will build the appropriate built-in
12025 // operator node.
George Burgess IV5f6ab9a2017-06-08 20:55:21 +000012026 ExprResult InputRes = PerformImplicitConversion(
12027 Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing);
John Wiegley01296292011-04-08 18:41:53 +000012028 if (InputRes.isInvalid())
12029 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012030 Input = InputRes.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000012031 break;
Douglas Gregor084d8552009-03-13 23:49:33 +000012032 }
John Wiegley01296292011-04-08 18:41:53 +000012033 }
12034
12035 case OR_No_Viable_Function:
Richard Smith998a5912011-06-05 22:42:48 +000012036 // This is an erroneous use of an operator which can be overloaded by
12037 // a non-member function. Check for non-member operators which were
12038 // defined too late to be candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000012039 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
Richard Smith998a5912011-06-05 22:42:48 +000012040 // FIXME: Recover by calling the found function.
12041 return ExprError();
12042
John Wiegley01296292011-04-08 18:41:53 +000012043 // No viable function; fall through to handling this as a
12044 // built-in operator, which will produce an error message for us.
12045 break;
12046
12047 case OR_Ambiguous:
12048 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
12049 << UnaryOperator::getOpcodeStr(Opc)
12050 << Input->getType()
12051 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000012052 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
John Wiegley01296292011-04-08 18:41:53 +000012053 UnaryOperator::getOpcodeStr(Opc), OpLoc);
12054 return ExprError();
12055
12056 case OR_Deleted:
12057 Diag(OpLoc, diag::err_ovl_deleted_oper)
12058 << Best->Function->isDeleted()
12059 << UnaryOperator::getOpcodeStr(Opc)
12060 << getDeletedOrUnavailableSuffix(Best->Function)
12061 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000012062 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000012063 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000012064 return ExprError();
12065 }
Douglas Gregor084d8552009-03-13 23:49:33 +000012066
12067 // Either we found no viable overloaded operator or we matched a
12068 // built-in operator. In either case, fall through to trying to
12069 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +000012070 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +000012071}
12072
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012073/// \brief Create a binary operation that may resolve to an overloaded
12074/// operator.
12075///
12076/// \param OpLoc The location of the operator itself (e.g., '+').
12077///
Craig Toppera92ffb02015-12-10 08:51:49 +000012078/// \param Opc The BinaryOperatorKind that describes this operator.
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012079///
James Dennett18348b62012-06-22 08:52:37 +000012080/// \param Fns The set of non-member functions that will be
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012081/// considered by overload resolution. The caller needs to build this
12082/// set based on the context using, e.g.,
12083/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12084/// set should not contain any member functions; those will be added
12085/// by CreateOverloadedBinOp().
12086///
12087/// \param LHS Left-hand argument.
12088/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +000012089ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012090Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Craig Toppera92ffb02015-12-10 08:51:49 +000012091 BinaryOperatorKind Opc,
John McCall4c4c1df2010-01-26 03:27:55 +000012092 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012093 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012094 Expr *Args[2] = { LHS, RHS };
Craig Topperc3ec1492014-05-26 06:22:03 +000012095 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012096
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012097 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
12098 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12099
12100 // If either side is type-dependent, create an appropriate dependent
12101 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +000012102 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +000012103 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012104 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +000012105 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +000012106 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012107 return new (Context) BinaryOperator(
12108 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
Adam Nemet484aa452017-03-27 19:17:25 +000012109 OpLoc, FPFeatures);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012110
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012111 return new (Context) CompoundAssignOperator(
12112 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
12113 Context.DependentTy, Context.DependentTy, OpLoc,
Adam Nemet484aa452017-03-27 19:17:25 +000012114 FPFeatures);
Douglas Gregor5287f092009-11-05 00:51:44 +000012115 }
John McCall4c4c1df2010-01-26 03:27:55 +000012116
12117 // FIXME: save results of ADL from here?
Craig Topperc3ec1492014-05-26 06:22:03 +000012118 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000012119 // TODO: provide better source location info in DNLoc component.
12120 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +000012121 UnresolvedLookupExpr *Fn
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000012122 = UnresolvedLookupExpr::Create(Context, NamingClass,
12123 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor0da1d432011-02-28 20:01:57 +000012124 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000012125 Fns.begin(), Fns.end());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012126 return new (Context)
12127 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
Adam Nemet484aa452017-03-27 19:17:25 +000012128 VK_RValue, OpLoc, FPFeatures);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012129 }
12130
John McCall4124c492011-10-17 18:40:02 +000012131 // Always do placeholder-like conversions on the RHS.
12132 if (checkPlaceholderForOverload(*this, Args[1]))
12133 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012134
John McCall526ab472011-10-25 17:37:35 +000012135 // Do placeholder-like conversion on the LHS; note that we should
12136 // not get here with a PseudoObject LHS.
12137 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall4124c492011-10-17 18:40:02 +000012138 if (checkPlaceholderForOverload(*this, Args[0]))
12139 return ExprError();
12140
Sebastian Redl6a96bf72009-11-18 23:10:33 +000012141 // If this is the assignment operator, we only perform overload resolution
12142 // if the left-hand side is a class or enumeration type. This is actually
12143 // a hack. The standard requires that we do overload resolution between the
12144 // various built-in candidates, but as DR507 points out, this can lead to
12145 // problems. So we do it this way, which pretty much follows what GCC does.
12146 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +000012147 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +000012148 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012149
John McCalle26a8722010-12-04 08:14:53 +000012150 // If this is the .* operator, which is not overloadable, just
12151 // create a built-in binary operator.
12152 if (Opc == BO_PtrMemD)
12153 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12154
Douglas Gregor084d8552009-03-13 23:49:33 +000012155 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000012156 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012157
12158 // Add the candidates from the given function set.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000012159 AddFunctionCandidates(Fns, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012160
12161 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000012162 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012163
Richard Smith0daabd72014-09-23 20:31:39 +000012164 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
12165 // performed for an assignment operator (nor for operator[] nor operator->,
12166 // which don't get here).
12167 if (Opc != BO_Assign)
12168 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
12169 /*ExplicitTemplateArgs*/ nullptr,
12170 CandidateSet);
John McCall4c4c1df2010-01-26 03:27:55 +000012171
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012172 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000012173 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012174
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012175 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12176
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012177 // Perform overload resolution.
12178 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012179 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +000012180 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012181 // We found a built-in operator or an overloaded operator.
12182 FunctionDecl *FnDecl = Best->Function;
12183
12184 if (FnDecl) {
Akira Hatanaka22461672017-07-13 06:08:27 +000012185 Expr *Base = nullptr;
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012186 // We matched an overloaded operator. Build a call to that
12187 // operator.
12188
12189 // Convert the arguments.
12190 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +000012191 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +000012192 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000012193
Chandler Carruth8e543b32010-12-12 08:17:55 +000012194 ExprResult Arg1 =
12195 PerformCopyInitialization(
12196 InitializedEntity::InitializeParameter(Context,
12197 FnDecl->getParamDecl(0)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012198 SourceLocation(), Args[1]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000012199 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012200 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000012201
John Wiegley01296292011-04-08 18:41:53 +000012202 ExprResult Arg0 =
Craig Topperc3ec1492014-05-26 06:22:03 +000012203 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012204 Best->FoundDecl, Method);
12205 if (Arg0.isInvalid())
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000012206 return ExprError();
Akira Hatanaka22461672017-07-13 06:08:27 +000012207 Base = Args[0] = Arg0.getAs<Expr>();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012208 Args[1] = RHS = Arg1.getAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012209 } else {
12210 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +000012211 ExprResult Arg0 = PerformCopyInitialization(
12212 InitializedEntity::InitializeParameter(Context,
12213 FnDecl->getParamDecl(0)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012214 SourceLocation(), Args[0]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000012215 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012216 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000012217
Chandler Carruth8e543b32010-12-12 08:17:55 +000012218 ExprResult Arg1 =
12219 PerformCopyInitialization(
12220 InitializedEntity::InitializeParameter(Context,
12221 FnDecl->getParamDecl(1)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012222 SourceLocation(), Args[1]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000012223 if (Arg1.isInvalid())
12224 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012225 Args[0] = LHS = Arg0.getAs<Expr>();
12226 Args[1] = RHS = Arg1.getAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012227 }
12228
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012229 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012230 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Akira Hatanaka22461672017-07-13 06:08:27 +000012231 Best->FoundDecl, Base,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012232 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000012233 if (FnExpr.isInvalid())
12234 return ExprError();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012235
Richard Smithc1564702013-11-15 02:58:23 +000012236 // Determine the result type.
Alp Toker314cc812014-01-25 16:55:45 +000012237 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000012238 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12239 ResultTy = ResultTy.getNonLValueExprType(Context);
12240
John McCallb268a282010-08-23 23:25:46 +000012241 CXXOperatorCallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012242 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
Lang Hames5de91cc2012-10-02 04:45:10 +000012243 Args, ResultTy, VK, OpLoc,
Adam Nemet484aa452017-03-27 19:17:25 +000012244 FPFeatures);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012245
Alp Toker314cc812014-01-25 16:55:45 +000012246 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000012247 FnDecl))
12248 return ExprError();
12249
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000012250 ArrayRef<const Expr *> ArgsArray(Args, 2);
George Burgess IVce6284b2017-01-28 02:19:40 +000012251 const Expr *ImplicitThis = nullptr;
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000012252 // Cut off the implicit 'this'.
George Burgess IVce6284b2017-01-28 02:19:40 +000012253 if (isa<CXXMethodDecl>(FnDecl)) {
12254 ImplicitThis = ArgsArray[0];
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000012255 ArgsArray = ArgsArray.slice(1);
George Burgess IVce6284b2017-01-28 02:19:40 +000012256 }
Richard Trieu36d0b2b2015-01-13 02:32:02 +000012257
12258 // Check for a self move.
12259 if (Op == OO_Equal)
12260 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
12261
George Burgess IVce6284b2017-01-28 02:19:40 +000012262 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
12263 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
12264 VariadicDoesNotApply);
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000012265
John McCallb268a282010-08-23 23:25:46 +000012266 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012267 } else {
12268 // We matched a built-in operator. Convert the arguments, then
12269 // break out so that we will build the appropriate built-in
12270 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000012271 ExprResult ArgsRes0 =
George Burgess IV5f6ab9a2017-06-08 20:55:21 +000012272 PerformImplicitConversion(Args[0], Best->BuiltinParamTypes[0],
12273 Best->Conversions[0], AA_Passing);
John Wiegley01296292011-04-08 18:41:53 +000012274 if (ArgsRes0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012275 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012276 Args[0] = ArgsRes0.get();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012277
John Wiegley01296292011-04-08 18:41:53 +000012278 ExprResult ArgsRes1 =
George Burgess IV5f6ab9a2017-06-08 20:55:21 +000012279 PerformImplicitConversion(Args[1], Best->BuiltinParamTypes[1],
12280 Best->Conversions[1], AA_Passing);
John Wiegley01296292011-04-08 18:41:53 +000012281 if (ArgsRes1.isInvalid())
12282 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012283 Args[1] = ArgsRes1.get();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012284 break;
12285 }
12286 }
12287
Douglas Gregor66950a32009-09-30 21:46:01 +000012288 case OR_No_Viable_Function: {
12289 // C++ [over.match.oper]p9:
12290 // If the operator is the operator , [...] and there are no
12291 // viable functions, then the operator is assumed to be the
12292 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +000012293 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +000012294 break;
12295
Chandler Carruth8e543b32010-12-12 08:17:55 +000012296 // For class as left operand for assignment or compound assigment
12297 // operator do not fall through to handling in built-in, but report that
12298 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +000012299 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012300 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +000012301 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +000012302 Diag(OpLoc, diag::err_ovl_no_viable_oper)
12303 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +000012304 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Eli Friedmana31efa02013-08-28 20:35:35 +000012305 if (Args[0]->getType()->isIncompleteType()) {
12306 Diag(OpLoc, diag::note_assign_lhs_incomplete)
12307 << Args[0]->getType()
12308 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12309 }
Douglas Gregor66950a32009-09-30 21:46:01 +000012310 } else {
Richard Smith998a5912011-06-05 22:42:48 +000012311 // This is an erroneous use of an operator which can be overloaded by
12312 // a non-member function. Check for non-member operators which were
12313 // defined too late to be candidates.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012314 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smith998a5912011-06-05 22:42:48 +000012315 // FIXME: Recover by calling the found function.
12316 return ExprError();
12317
Douglas Gregor66950a32009-09-30 21:46:01 +000012318 // No viable function; try to create a built-in operation, which will
12319 // produce an error. Then, show the non-viable candidates.
12320 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +000012321 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012322 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +000012323 "C++ binary operator overloading is missing candidates!");
12324 if (Result.isInvalid())
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012325 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012326 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012327 return Result;
Douglas Gregor66950a32009-09-30 21:46:01 +000012328 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012329
12330 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000012331 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012332 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +000012333 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +000012334 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012335 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012336 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012337 return ExprError();
12338
12339 case OR_Deleted:
Douglas Gregor74f7d502012-02-15 19:33:52 +000012340 if (isImplicitlyDeleted(Best->Function)) {
12341 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12342 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
Richard Smithde1a4872012-12-28 12:23:24 +000012343 << Context.getRecordType(Method->getParent())
12344 << getSpecialMember(Method);
Richard Smith6f1e2c62012-04-02 20:59:25 +000012345
Richard Smithde1a4872012-12-28 12:23:24 +000012346 // The user probably meant to call this special member. Just
12347 // explain why it's deleted.
12348 NoteDeletedFunction(Method);
12349 return ExprError();
Douglas Gregor74f7d502012-02-15 19:33:52 +000012350 } else {
12351 Diag(OpLoc, diag::err_ovl_deleted_oper)
12352 << Best->Function->isDeleted()
12353 << BinaryOperator::getOpcodeStr(Opc)
12354 << getDeletedOrUnavailableSuffix(Best->Function)
12355 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12356 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012357 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000012358 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012359 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +000012360 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012361
Douglas Gregor66950a32009-09-30 21:46:01 +000012362 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +000012363 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012364}
12365
John McCalldadc5752010-08-24 06:29:42 +000012366ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +000012367Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
12368 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +000012369 Expr *Base, Expr *Idx) {
12370 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +000012371 DeclarationName OpName =
12372 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
12373
12374 // If either side is type-dependent, create an appropriate dependent
12375 // expression.
12376 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12377
Craig Topperc3ec1492014-05-26 06:22:03 +000012378 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000012379 // CHECKME: no 'operator' keyword?
12380 DeclarationNameInfo OpNameInfo(OpName, LLoc);
12381 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +000012382 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000012383 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000012384 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000012385 /*ADL*/ true, /*Overloaded*/ false,
12386 UnresolvedSetIterator(),
12387 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +000012388 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +000012389
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012390 return new (Context)
12391 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
Adam Nemet484aa452017-03-27 19:17:25 +000012392 Context.DependentTy, VK_RValue, RLoc, FPOptions());
Sebastian Redladba46e2009-10-29 20:17:01 +000012393 }
12394
John McCall4124c492011-10-17 18:40:02 +000012395 // Handle placeholders on both operands.
12396 if (checkPlaceholderForOverload(*this, Args[0]))
12397 return ExprError();
12398 if (checkPlaceholderForOverload(*this, Args[1]))
12399 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012400
Sebastian Redladba46e2009-10-29 20:17:01 +000012401 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000012402 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
Sebastian Redladba46e2009-10-29 20:17:01 +000012403
12404 // Subscript can only be overloaded as a member function.
12405
12406 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000012407 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000012408
12409 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000012410 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000012411
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012412 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12413
Sebastian Redladba46e2009-10-29 20:17:01 +000012414 // Perform overload resolution.
12415 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012416 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +000012417 case OR_Success: {
12418 // We found a built-in operator or an overloaded operator.
12419 FunctionDecl *FnDecl = Best->Function;
12420
12421 if (FnDecl) {
12422 // We matched an overloaded operator. Build a call to that
12423 // operator.
12424
John McCalla0296f72010-03-19 07:35:19 +000012425 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall58cc69d2010-01-27 01:50:18 +000012426
Sebastian Redladba46e2009-10-29 20:17:01 +000012427 // Convert the arguments.
12428 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley01296292011-04-08 18:41:53 +000012429 ExprResult Arg0 =
Craig Topperc3ec1492014-05-26 06:22:03 +000012430 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012431 Best->FoundDecl, Method);
12432 if (Arg0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000012433 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012434 Args[0] = Arg0.get();
Sebastian Redladba46e2009-10-29 20:17:01 +000012435
Anders Carlssona68e51e2010-01-29 18:37:50 +000012436 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000012437 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +000012438 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000012439 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +000012440 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012441 SourceLocation(),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012442 Args[1]);
Anders Carlssona68e51e2010-01-29 18:37:50 +000012443 if (InputInit.isInvalid())
12444 return ExprError();
12445
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012446 Args[1] = InputInit.getAs<Expr>();
Anders Carlssona68e51e2010-01-29 18:37:50 +000012447
Sebastian Redladba46e2009-10-29 20:17:01 +000012448 // Build the actual expression node.
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012449 DeclarationNameInfo OpLocInfo(OpName, LLoc);
12450 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012451 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000012452 Best->FoundDecl,
Akira Hatanaka22461672017-07-13 06:08:27 +000012453 Base,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012454 HadMultipleCandidates,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012455 OpLocInfo.getLoc(),
12456 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000012457 if (FnExpr.isInvalid())
12458 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000012459
Richard Smithc1564702013-11-15 02:58:23 +000012460 // Determine the result type
Alp Toker314cc812014-01-25 16:55:45 +000012461 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000012462 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12463 ResultTy = ResultTy.getNonLValueExprType(Context);
12464
John McCallb268a282010-08-23 23:25:46 +000012465 CXXOperatorCallExpr *TheCall =
12466 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012467 FnExpr.get(), Args,
Lang Hames5de91cc2012-10-02 04:45:10 +000012468 ResultTy, VK, RLoc,
Adam Nemet484aa452017-03-27 19:17:25 +000012469 FPOptions());
Sebastian Redladba46e2009-10-29 20:17:01 +000012470
Alp Toker314cc812014-01-25 16:55:45 +000012471 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
Sebastian Redladba46e2009-10-29 20:17:01 +000012472 return ExprError();
12473
George Burgess IVce6284b2017-01-28 02:19:40 +000012474 if (CheckFunctionCall(Method, TheCall,
12475 Method->getType()->castAs<FunctionProtoType>()))
12476 return ExprError();
12477
John McCallb268a282010-08-23 23:25:46 +000012478 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +000012479 } else {
12480 // We matched a built-in operator. Convert the arguments, then
12481 // break out so that we will build the appropriate built-in
12482 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000012483 ExprResult ArgsRes0 =
George Burgess IV5f6ab9a2017-06-08 20:55:21 +000012484 PerformImplicitConversion(Args[0], Best->BuiltinParamTypes[0],
12485 Best->Conversions[0], AA_Passing);
John Wiegley01296292011-04-08 18:41:53 +000012486 if (ArgsRes0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000012487 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012488 Args[0] = ArgsRes0.get();
John Wiegley01296292011-04-08 18:41:53 +000012489
12490 ExprResult ArgsRes1 =
George Burgess IV5f6ab9a2017-06-08 20:55:21 +000012491 PerformImplicitConversion(Args[1], Best->BuiltinParamTypes[1],
12492 Best->Conversions[1], AA_Passing);
John Wiegley01296292011-04-08 18:41:53 +000012493 if (ArgsRes1.isInvalid())
12494 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012495 Args[1] = ArgsRes1.get();
Sebastian Redladba46e2009-10-29 20:17:01 +000012496
12497 break;
12498 }
12499 }
12500
12501 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +000012502 if (CandidateSet.empty())
12503 Diag(LLoc, diag::err_ovl_no_oper)
12504 << Args[0]->getType() << /*subscript*/ 0
12505 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12506 else
12507 Diag(LLoc, diag::err_ovl_no_viable_subscript)
12508 << Args[0]->getType()
12509 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012510 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012511 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +000012512 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000012513 }
12514
12515 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000012516 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012517 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +000012518 << Args[0]->getType() << Args[1]->getType()
12519 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012520 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012521 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000012522 return ExprError();
12523
12524 case OR_Deleted:
12525 Diag(LLoc, diag::err_ovl_deleted_oper)
12526 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012527 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +000012528 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012529 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012530 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000012531 return ExprError();
12532 }
12533
12534 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +000012535 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000012536}
12537
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012538/// BuildCallToMemberFunction - Build a call to a member
12539/// function. MemExpr is the expression that refers to the member
12540/// function (and includes the object parameter), Args/NumArgs are the
12541/// arguments to the function call (not including the object
12542/// parameter). The caller needs to validate that the member
John McCall0009fcc2011-04-26 20:42:42 +000012543/// expression refers to a non-static member function or an overloaded
12544/// member function.
John McCalldadc5752010-08-24 06:29:42 +000012545ExprResult
Mike Stump11289f42009-09-09 15:08:12 +000012546Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012547 SourceLocation LParenLoc,
12548 MultiExprArg Args,
12549 SourceLocation RParenLoc) {
John McCall0009fcc2011-04-26 20:42:42 +000012550 assert(MemExprE->getType() == Context.BoundMemberTy ||
12551 MemExprE->getType() == Context.OverloadTy);
12552
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012553 // Dig out the member expression. This holds both the object
12554 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +000012555 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012556
John McCall0009fcc2011-04-26 20:42:42 +000012557 // Determine whether this is a call to a pointer-to-member function.
12558 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
12559 assert(op->getType() == Context.BoundMemberTy);
12560 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
12561
12562 QualType fnType =
12563 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
12564
12565 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
12566 QualType resultType = proto->getCallResultType(Context);
Alp Toker314cc812014-01-25 16:55:45 +000012567 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
John McCall0009fcc2011-04-26 20:42:42 +000012568
12569 // Check that the object type isn't more qualified than the
12570 // member function we're calling.
12571 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
12572
12573 QualType objectType = op->getLHS()->getType();
12574 if (op->getOpcode() == BO_PtrMemI)
12575 objectType = objectType->castAs<PointerType>()->getPointeeType();
12576 Qualifiers objectQuals = objectType.getQualifiers();
12577
12578 Qualifiers difference = objectQuals - funcQuals;
12579 difference.removeObjCGCAttr();
12580 difference.removeAddressSpace();
12581 if (difference) {
12582 std::string qualsString = difference.getAsString();
12583 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
12584 << fnType.getUnqualifiedType()
12585 << qualsString
12586 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
12587 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +000012588
John McCall0009fcc2011-04-26 20:42:42 +000012589 CXXMemberCallExpr *call
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012590 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall0009fcc2011-04-26 20:42:42 +000012591 resultType, valueKind, RParenLoc);
12592
Alp Toker314cc812014-01-25 16:55:45 +000012593 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
Craig Topperc3ec1492014-05-26 06:22:03 +000012594 call, nullptr))
John McCall0009fcc2011-04-26 20:42:42 +000012595 return ExprError();
12596
Craig Topperc3ec1492014-05-26 06:22:03 +000012597 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
John McCall0009fcc2011-04-26 20:42:42 +000012598 return ExprError();
12599
Richard Trieu9be9c682013-06-22 02:30:38 +000012600 if (CheckOtherCall(call, proto))
12601 return ExprError();
12602
John McCall0009fcc2011-04-26 20:42:42 +000012603 return MaybeBindToTemporary(call);
12604 }
12605
David Majnemerced8bdf2015-02-25 17:36:15 +000012606 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
12607 return new (Context)
12608 CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc);
12609
John McCall4124c492011-10-17 18:40:02 +000012610 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012611 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000012612 return ExprError();
12613
John McCall10eae182009-11-30 22:42:35 +000012614 MemberExpr *MemExpr;
Craig Topperc3ec1492014-05-26 06:22:03 +000012615 CXXMethodDecl *Method = nullptr;
12616 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
12617 NestedNameSpecifier *Qualifier = nullptr;
John McCall10eae182009-11-30 22:42:35 +000012618 if (isa<MemberExpr>(NakedMemExpr)) {
12619 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +000012620 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +000012621 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +000012622 Qualifier = MemExpr->getQualifier();
John McCall4124c492011-10-17 18:40:02 +000012623 UnbridgedCasts.restore();
John McCall10eae182009-11-30 22:42:35 +000012624 } else {
12625 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +000012626 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012627
John McCall6e9f8f62009-12-03 04:06:58 +000012628 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +000012629 Expr::Classification ObjectClassification
12630 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
12631 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +000012632
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012633 // Add overload candidates
Richard Smith100b24a2014-04-17 01:52:14 +000012634 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
12635 OverloadCandidateSet::CSK_Normal);
Mike Stump11289f42009-09-09 15:08:12 +000012636
John McCall2d74de92009-12-01 22:10:20 +000012637 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000012638 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCall2d74de92009-12-01 22:10:20 +000012639 if (UnresExpr->hasExplicitTemplateArgs()) {
12640 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12641 TemplateArgs = &TemplateArgsBuffer;
12642 }
12643
John McCall10eae182009-11-30 22:42:35 +000012644 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
12645 E = UnresExpr->decls_end(); I != E; ++I) {
12646
John McCall6e9f8f62009-12-03 04:06:58 +000012647 NamedDecl *Func = *I;
12648 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
12649 if (isa<UsingShadowDecl>(Func))
12650 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
12651
Douglas Gregor02824322011-01-26 19:30:28 +000012652
Francois Pichet64225792011-01-18 05:04:39 +000012653 // Microsoft supports direct constructor calls.
David Blaikiebbafb8a2012-03-11 07:00:24 +000012654 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012655 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012656 Args, CandidateSet);
Francois Pichet64225792011-01-18 05:04:39 +000012657 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +000012658 // If explicit template arguments were provided, we can't call a
12659 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +000012660 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +000012661 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012662
John McCalla0296f72010-03-19 07:35:19 +000012663 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
George Burgess IVce6284b2017-01-28 02:19:40 +000012664 ObjectClassification, Args, CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +000012665 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000012666 } else {
George Burgess IV177399e2017-01-09 04:12:14 +000012667 AddMethodTemplateCandidate(
12668 cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC,
George Burgess IVce6284b2017-01-28 02:19:40 +000012669 TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet,
George Burgess IV177399e2017-01-09 04:12:14 +000012670 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000012671 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000012672 }
Mike Stump11289f42009-09-09 15:08:12 +000012673
John McCall10eae182009-11-30 22:42:35 +000012674 DeclarationName DeclName = UnresExpr->getMemberName();
12675
John McCall4124c492011-10-17 18:40:02 +000012676 UnbridgedCasts.restore();
12677
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012678 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012679 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +000012680 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012681 case OR_Success:
12682 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +000012683 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +000012684 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000012685 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
12686 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000012687 // If FoundDecl is different from Method (such as if one is a template
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000012688 // and the other a specialization), make sure DiagnoseUseOfDecl is
Faisal Valid6676412013-06-15 11:54:37 +000012689 // called on both.
12690 // FIXME: This would be more comprehensively addressed by modifying
12691 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
12692 // being used.
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000012693 if (Method != FoundDecl.getDecl() &&
Faisal Valid6676412013-06-15 11:54:37 +000012694 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
12695 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012696 break;
12697
12698 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +000012699 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012700 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000012701 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012702 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012703 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000012704 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012705
12706 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +000012707 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000012708 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012709 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012710 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000012711 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000012712
12713 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +000012714 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +000012715 << Best->Function->isDeleted()
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000012716 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012717 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012718 << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012719 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000012720 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000012721 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012722 }
12723
John McCall16df1e52010-03-30 21:47:33 +000012724 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +000012725
John McCall2d74de92009-12-01 22:10:20 +000012726 // If overload resolution picked a static member, build a
12727 // non-member call based on that function.
12728 if (Method->isStatic()) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012729 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
12730 RParenLoc);
John McCall2d74de92009-12-01 22:10:20 +000012731 }
12732
John McCall10eae182009-11-30 22:42:35 +000012733 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012734 }
12735
Alp Toker314cc812014-01-25 16:55:45 +000012736 QualType ResultType = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000012737 ExprValueKind VK = Expr::getValueKindForType(ResultType);
12738 ResultType = ResultType.getNonLValueExprType(Context);
12739
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012740 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012741 CXXMemberCallExpr *TheCall =
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012742 new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall7decc9e2010-11-18 06:31:45 +000012743 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012744
Anders Carlssonc4859ba2009-10-10 00:06:20 +000012745 // Check for a valid return type.
Alp Toker314cc812014-01-25 16:55:45 +000012746 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +000012747 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +000012748 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012749
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012750 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +000012751 // We only need to do this if there was actually an overload; otherwise
12752 // it was done at lookup.
John Wiegley01296292011-04-08 18:41:53 +000012753 if (!Method->isStatic()) {
12754 ExprResult ObjectArg =
12755 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
12756 FoundDecl, Method);
12757 if (ObjectArg.isInvalid())
12758 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012759 MemExpr->setBase(ObjectArg.get());
John Wiegley01296292011-04-08 18:41:53 +000012760 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012761
12762 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +000012763 const FunctionProtoType *Proto =
12764 Method->getType()->getAs<FunctionProtoType>();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012765 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012766 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +000012767 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012768
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012769 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000012770
Richard Smith55ce3522012-06-25 20:30:08 +000012771 if (CheckFunctionCall(Method, TheCall, Proto))
John McCall2d74de92009-12-01 22:10:20 +000012772 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +000012773
George Burgess IVaea6ade2015-09-25 17:53:16 +000012774 // In the case the method to call was not selected by the overloading
12775 // resolution process, we still need to handle the enable_if attribute. Do
George Burgess IV0d546532016-11-10 21:47:12 +000012776 // that here, so it will not hide previous -- and more relevant -- errors.
George Burgess IVadd6ab52016-11-16 21:31:25 +000012777 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
George Burgess IVaea6ade2015-09-25 17:53:16 +000012778 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
George Burgess IVadd6ab52016-11-16 21:31:25 +000012779 Diag(MemE->getMemberLoc(),
George Burgess IVaea6ade2015-09-25 17:53:16 +000012780 diag::err_ovl_no_viable_member_function_in_call)
12781 << Method << Method->getSourceRange();
12782 Diag(Method->getLocation(),
George Burgess IV177399e2017-01-09 04:12:14 +000012783 diag::note_ovl_candidate_disabled_by_function_cond_attr)
George Burgess IVaea6ade2015-09-25 17:53:16 +000012784 << Attr->getCond()->getSourceRange() << Attr->getMessage();
12785 return ExprError();
12786 }
12787 }
12788
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000012789 if ((isa<CXXConstructorDecl>(CurContext) ||
12790 isa<CXXDestructorDecl>(CurContext)) &&
Anders Carlsson47061ee2011-05-06 14:25:31 +000012791 TheCall->getMethodDecl()->isPure()) {
12792 const CXXMethodDecl *MD = TheCall->getMethodDecl();
12793
Davide Italianoccb37382015-07-14 23:36:10 +000012794 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
12795 MemExpr->performsVirtualDispatch(getLangOpts())) {
12796 Diag(MemExpr->getLocStart(),
Anders Carlsson47061ee2011-05-06 14:25:31 +000012797 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
12798 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
12799 << MD->getParent()->getDeclName();
12800
12801 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Davide Italianoccb37382015-07-14 23:36:10 +000012802 if (getLangOpts().AppleKext)
12803 Diag(MemExpr->getLocStart(),
12804 diag::note_pure_qualified_call_kext)
12805 << MD->getParent()->getDeclName()
12806 << MD->getDeclName();
Chandler Carruth59259262011-06-27 08:31:58 +000012807 }
Anders Carlsson47061ee2011-05-06 14:25:31 +000012808 }
Nico Weber5a9259c2016-01-15 21:45:31 +000012809
12810 if (CXXDestructorDecl *DD =
12811 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
12812 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
Justin Lebard35f7062016-07-12 23:23:01 +000012813 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
Nico Weber5a9259c2016-01-15 21:45:31 +000012814 CheckVirtualDtorCall(DD, MemExpr->getLocStart(), /*IsDelete=*/false,
12815 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
12816 MemExpr->getMemberLoc());
12817 }
12818
John McCallb268a282010-08-23 23:25:46 +000012819 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012820}
12821
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012822/// BuildCallToObjectOfClassType - Build a call to an object of class
12823/// type (C++ [over.call.object]), which can end up invoking an
12824/// overloaded function call operator (@c operator()) or performing a
12825/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +000012826ExprResult
John Wiegley01296292011-04-08 18:41:53 +000012827Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregorb0846b02008-12-06 00:22:45 +000012828 SourceLocation LParenLoc,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012829 MultiExprArg Args,
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012830 SourceLocation RParenLoc) {
John McCall4124c492011-10-17 18:40:02 +000012831 if (checkPlaceholderForOverload(*this, Obj))
12832 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012833 ExprResult Object = Obj;
John McCall4124c492011-10-17 18:40:02 +000012834
12835 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012836 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000012837 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012838
Nico Weberb58e51c2014-11-19 05:21:39 +000012839 assert(Object.get()->getType()->isRecordType() &&
12840 "Requires object type argument");
John Wiegley01296292011-04-08 18:41:53 +000012841 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +000012842
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012843 // C++ [over.call.object]p1:
12844 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +000012845 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012846 // candidate functions includes at least the function call
12847 // operators of T. The function call operators of T are obtained by
12848 // ordinary lookup of the name operator() in the context of
12849 // (E).operator().
Richard Smith100b24a2014-04-17 01:52:14 +000012850 OverloadCandidateSet CandidateSet(LParenLoc,
12851 OverloadCandidateSet::CSK_Operator);
Douglas Gregor91f84212008-12-11 16:49:14 +000012852 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +000012853
John Wiegley01296292011-04-08 18:41:53 +000012854 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012855 diag::err_incomplete_object_call, Object.get()))
Douglas Gregorc473cbb2009-11-15 07:48:03 +000012856 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012857
John McCall27b18f82009-11-17 02:14:36 +000012858 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
12859 LookupQualifiedName(R, Record->getDecl());
12860 R.suppressDiagnostics();
12861
Douglas Gregorc473cbb2009-11-15 07:48:03 +000012862 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +000012863 Oper != OperEnd; ++Oper) {
John Wiegley01296292011-04-08 18:41:53 +000012864 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
George Burgess IVce6284b2017-01-28 02:19:40 +000012865 Object.get()->Classify(Context), Args, CandidateSet,
12866 /*SuppressUserConversions=*/false);
Douglas Gregor358e7742009-11-07 17:23:56 +000012867 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012868
Douglas Gregorab7897a2008-11-19 22:57:39 +000012869 // C++ [over.call.object]p2:
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000012870 // In addition, for each (non-explicit in C++0x) conversion function
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012871 // declared in T of the form
Douglas Gregorab7897a2008-11-19 22:57:39 +000012872 //
12873 // operator conversion-type-id () cv-qualifier;
12874 //
12875 // where cv-qualifier is the same cv-qualification as, or a
12876 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +000012877 // denotes the type "pointer to function of (P1,...,Pn) returning
12878 // R", or the type "reference to pointer to function of
12879 // (P1,...,Pn) returning R", or the type "reference to function
12880 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +000012881 // is also considered as a candidate function. Similarly,
12882 // surrogate call functions are added to the set of candidate
12883 // functions for each conversion function declared in an
12884 // accessible base class provided the function is not hidden
12885 // within T by another intervening declaration.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +000012886 const auto &Conversions =
12887 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
12888 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +000012889 NamedDecl *D = *I;
12890 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
12891 if (isa<UsingShadowDecl>(D))
12892 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012893
Douglas Gregor74ba25c2009-10-21 06:18:39 +000012894 // Skip over templated conversion functions; they aren't
12895 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +000012896 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +000012897 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +000012898
John McCall6e9f8f62009-12-03 04:06:58 +000012899 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012900 if (!Conv->isExplicit()) {
12901 // Strip the reference type (if any) and then the pointer type (if
12902 // any) to get down to what might be a function type.
12903 QualType ConvType = Conv->getConversionType().getNonReferenceType();
12904 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
12905 ConvType = ConvPtrType->getPointeeType();
John McCalld14a8642009-11-21 08:51:07 +000012906
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012907 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
12908 {
12909 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012910 Object.get(), Args, CandidateSet);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012911 }
12912 }
Douglas Gregorab7897a2008-11-19 22:57:39 +000012913 }
Mike Stump11289f42009-09-09 15:08:12 +000012914
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012915 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12916
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012917 // Perform overload resolution.
12918 OverloadCandidateSet::iterator Best;
John Wiegley01296292011-04-08 18:41:53 +000012919 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall5c32be02010-08-24 20:38:10 +000012920 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012921 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +000012922 // Overload resolution succeeded; we'll build the appropriate call
12923 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012924 break;
12925
12926 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +000012927 if (CandidateSet.empty())
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012928 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley01296292011-04-08 18:41:53 +000012929 << Object.get()->getType() << /*call*/ 1
12930 << Object.get()->getSourceRange();
John McCall02374852010-01-07 02:04:15 +000012931 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012932 Diag(Object.get()->getLocStart(),
John McCall02374852010-01-07 02:04:15 +000012933 diag::err_ovl_no_viable_object_call)
John Wiegley01296292011-04-08 18:41:53 +000012934 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012935 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012936 break;
12937
12938 case OR_Ambiguous:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012939 Diag(Object.get()->getLocStart(),
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012940 diag::err_ovl_ambiguous_object_call)
John Wiegley01296292011-04-08 18:41:53 +000012941 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012942 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012943 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000012944
12945 case OR_Deleted:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012946 Diag(Object.get()->getLocStart(),
Douglas Gregor171c45a2009-02-18 21:56:37 +000012947 diag::err_ovl_deleted_object_call)
12948 << Best->Function->isDeleted()
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000012949 << Object.get()->getType()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012950 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley01296292011-04-08 18:41:53 +000012951 << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012952 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000012953 break;
Mike Stump11289f42009-09-09 15:08:12 +000012954 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012955
Douglas Gregorb412e172010-07-25 18:17:45 +000012956 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012957 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012958
John McCall4124c492011-10-17 18:40:02 +000012959 UnbridgedCasts.restore();
12960
Craig Topperc3ec1492014-05-26 06:22:03 +000012961 if (Best->Function == nullptr) {
Douglas Gregorab7897a2008-11-19 22:57:39 +000012962 // Since there is no function declaration, this is one of the
12963 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +000012964 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +000012965 = cast<CXXConversionDecl>(
12966 Best->Conversions[0].UserDefined.ConversionFunction);
12967
Craig Topperc3ec1492014-05-26 06:22:03 +000012968 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
12969 Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000012970 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
12971 return ExprError();
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000012972 assert(Conv == Best->FoundDecl.getDecl() &&
Faisal Valid6676412013-06-15 11:54:37 +000012973 "Found Decl & conversion-to-functionptr should be same, right?!");
Douglas Gregorab7897a2008-11-19 22:57:39 +000012974 // We selected one of the surrogate functions that converts the
12975 // object parameter to a function pointer. Perform the conversion
12976 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012977
Fariborz Jahanian774cf792009-09-28 18:35:46 +000012978 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +000012979 // and then call it.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012980 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
12981 Conv, HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +000012982 if (Call.isInvalid())
12983 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +000012984 // Record usage of conversion in an implicit cast.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012985 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
12986 CK_UserDefinedConversion, Call.get(),
12987 nullptr, VK_RValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012988
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012989 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +000012990 }
12991
Craig Topperc3ec1492014-05-26 06:22:03 +000012992 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
John McCall49ec2e62010-01-28 01:54:34 +000012993
Douglas Gregorab7897a2008-11-19 22:57:39 +000012994 // We found an overloaded operator(). Build a CXXOperatorCallExpr
12995 // that calls this method, using Object for the implicit object
12996 // parameter and passing along the remaining arguments.
12997 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Nico Weber1fefe412012-11-09 06:06:14 +000012998
12999 // An error diagnostic has already been printed when parsing the declaration.
Nico Weber9512d3f2012-11-09 08:38:04 +000013000 if (Method->isInvalidDecl())
Nico Weber1fefe412012-11-09 06:06:14 +000013001 return ExprError();
13002
Chandler Carruth8e543b32010-12-12 08:17:55 +000013003 const FunctionProtoType *Proto =
13004 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013005
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000013006 unsigned NumParams = Proto->getNumParams();
Mike Stump11289f42009-09-09 15:08:12 +000013007
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000013008 DeclarationNameInfo OpLocInfo(
13009 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
13010 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Nick Lewycky134af912013-02-07 05:08:22 +000013011 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Akira Hatanaka22461672017-07-13 06:08:27 +000013012 Obj, HadMultipleCandidates,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000013013 OpLocInfo.getLoc(),
13014 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000013015 if (NewFn.isInvalid())
13016 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013017
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000013018 // Build the full argument list for the method call (the implicit object
13019 // parameter is placed at the beginning of the list).
George Burgess IV215f6e72016-12-13 19:22:56 +000013020 SmallVector<Expr *, 8> MethodArgs(Args.size() + 1);
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000013021 MethodArgs[0] = Object.get();
George Burgess IV215f6e72016-12-13 19:22:56 +000013022 std::copy(Args.begin(), Args.end(), MethodArgs.begin() + 1);
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000013023
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013024 // Once we've built TheCall, all of the expressions are properly
13025 // owned.
Alp Toker314cc812014-01-25 16:55:45 +000013026 QualType ResultTy = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000013027 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13028 ResultTy = ResultTy.getNonLValueExprType(Context);
13029
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000013030 CXXOperatorCallExpr *TheCall = new (Context)
George Burgess IV215f6e72016-12-13 19:22:56 +000013031 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(), MethodArgs, ResultTy,
Adam Nemet484aa452017-03-27 19:17:25 +000013032 VK, RParenLoc, FPOptions());
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013033
Alp Toker314cc812014-01-25 16:55:45 +000013034 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
Anders Carlsson3d5829c2009-10-13 21:49:31 +000013035 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013036
Douglas Gregor02a0acd2009-01-13 05:10:00 +000013037 // We may have default arguments. If so, we need to allocate more
13038 // slots in the call for them.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000013039 if (Args.size() < NumParams)
13040 TheCall->setNumArgs(Context, NumParams + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +000013041
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000013042 bool IsError = false;
13043
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013044 // Initialize the implicit object parameter.
John Wiegley01296292011-04-08 18:41:53 +000013045 ExprResult ObjRes =
Craig Topperc3ec1492014-05-26 06:22:03 +000013046 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000013047 Best->FoundDecl, Method);
13048 if (ObjRes.isInvalid())
13049 IsError = true;
13050 else
Benjamin Kramer62b95d82012-08-23 21:35:17 +000013051 Object = ObjRes;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013052 TheCall->setArg(0, Object.get());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000013053
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013054 // Check the argument types.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000013055 for (unsigned i = 0; i != NumParams; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013056 Expr *Arg;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000013057 if (i < Args.size()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013058 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +000013059
Douglas Gregor02a0acd2009-01-13 05:10:00 +000013060 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +000013061
John McCalldadc5752010-08-24 06:29:42 +000013062 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +000013063 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000013064 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +000013065 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +000013066 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013067
Anders Carlsson7c5fe482010-01-29 18:43:53 +000013068 IsError |= InputInit.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013069 Arg = InputInit.getAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000013070 } else {
John McCalldadc5752010-08-24 06:29:42 +000013071 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +000013072 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
13073 if (DefArg.isInvalid()) {
13074 IsError = true;
13075 break;
13076 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013077
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013078 Arg = DefArg.getAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000013079 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013080
13081 TheCall->setArg(i + 1, Arg);
13082 }
13083
13084 // If this is a variadic call, handle args passed through "...".
13085 if (Proto->isVariadic()) {
13086 // Promote the arguments (C99 6.5.2.2p7).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000013087 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
Craig Topperc3ec1492014-05-26 06:22:03 +000013088 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
13089 nullptr);
John Wiegley01296292011-04-08 18:41:53 +000013090 IsError |= Arg.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013091 TheCall->setArg(i + 1, Arg.get());
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013092 }
13093 }
13094
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000013095 if (IsError) return true;
13096
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000013097 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000013098
Richard Smith55ce3522012-06-25 20:30:08 +000013099 if (CheckFunctionCall(Method, TheCall, Proto))
Anders Carlssonbc4c1072009-08-16 01:56:34 +000013100 return true;
13101
John McCalle172be52010-08-24 06:09:16 +000013102 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013103}
13104
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013105/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +000013106/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013107/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +000013108ExprResult
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000013109Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
13110 bool *NoArrowOperatorFound) {
Chandler Carruth8e543b32010-12-12 08:17:55 +000013111 assert(Base->getType()->isRecordType() &&
13112 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +000013113
John McCall4124c492011-10-17 18:40:02 +000013114 if (checkPlaceholderForOverload(*this, Base))
13115 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000013116
John McCallbc077cf2010-02-08 23:07:23 +000013117 SourceLocation Loc = Base->getExprLoc();
13118
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013119 // C++ [over.ref]p1:
13120 //
13121 // [...] An expression x->m is interpreted as (x.operator->())->m
13122 // for a class object x of type T if T::operator->() exists and if
13123 // the operator is selected as the best match function by the
13124 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +000013125 DeclarationName OpName =
13126 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
Richard Smith100b24a2014-04-17 01:52:14 +000013127 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
Ted Kremenekc23c7e62009-07-29 21:53:49 +000013128 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +000013129
John McCallbc077cf2010-02-08 23:07:23 +000013130 if (RequireCompleteType(Loc, Base->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000013131 diag::err_typecheck_incomplete_tag, Base))
Eli Friedman132e70b2009-11-18 01:28:03 +000013132 return ExprError();
13133
John McCall27b18f82009-11-17 02:14:36 +000013134 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
13135 LookupQualifiedName(R, BaseRecord->getDecl());
13136 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +000013137
13138 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +000013139 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +000013140 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
George Burgess IVce6284b2017-01-28 02:19:40 +000013141 None, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +000013142 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013143
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013144 bool HadMultipleCandidates = (CandidateSet.size() > 1);
13145
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013146 // Perform overload resolution.
13147 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000013148 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013149 case OR_Success:
13150 // Overload resolution succeeded; we'll build the call below.
13151 break;
13152
13153 case OR_No_Viable_Function:
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000013154 if (CandidateSet.empty()) {
13155 QualType BaseType = Base->getType();
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000013156 if (NoArrowOperatorFound) {
13157 // Report this specific error to the caller instead of emitting a
13158 // diagnostic, as requested.
13159 *NoArrowOperatorFound = true;
13160 return ExprError();
13161 }
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000013162 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
13163 << BaseType << Base->getSourceRange();
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000013164 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000013165 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000013166 << FixItHint::CreateReplacement(OpLoc, ".");
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000013167 }
13168 } else
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013169 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +000013170 << "operator->" << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000013171 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000013172 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013173
13174 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000013175 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
13176 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000013177 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000013178 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000013179
13180 case OR_Deleted:
13181 Diag(OpLoc, diag::err_ovl_deleted_oper)
13182 << Best->Function->isDeleted()
Simon Pilgrimfb9662a2017-06-01 18:17:18 +000013183 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000013184 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000013185 << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000013186 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000013187 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013188 }
13189
Craig Topperc3ec1492014-05-26 06:22:03 +000013190 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
John McCalla0296f72010-03-19 07:35:19 +000013191
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013192 // Convert the object parameter.
13193 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000013194 ExprResult BaseResult =
Craig Topperc3ec1492014-05-26 06:22:03 +000013195 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000013196 Best->FoundDecl, Method);
13197 if (BaseResult.isInvalid())
Douglas Gregord8061562009-08-06 03:17:00 +000013198 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013199 Base = BaseResult.get();
Douglas Gregor9ecea262008-11-21 03:04:22 +000013200
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013201 // Build the operator call.
Nick Lewycky134af912013-02-07 05:08:22 +000013202 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Akira Hatanaka22461672017-07-13 06:08:27 +000013203 Base, HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000013204 if (FnExpr.isInvalid())
13205 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013206
Alp Toker314cc812014-01-25 16:55:45 +000013207 QualType ResultTy = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000013208 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13209 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +000013210 CXXOperatorCallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013211 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
Adam Nemet484aa452017-03-27 19:17:25 +000013212 Base, ResultTy, VK, OpLoc, FPOptions());
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000013213
Alp Toker314cc812014-01-25 16:55:45 +000013214 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
George Burgess IVce6284b2017-01-28 02:19:40 +000013215 return ExprError();
13216
13217 if (CheckFunctionCall(Method, TheCall,
13218 Method->getType()->castAs<FunctionProtoType>()))
13219 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +000013220
13221 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013222}
13223
Richard Smithbcc22fc2012-03-09 08:00:36 +000013224/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
13225/// a literal operator described by the provided lookup results.
13226ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
13227 DeclarationNameInfo &SuffixInfo,
13228 ArrayRef<Expr*> Args,
13229 SourceLocation LitEndLoc,
13230 TemplateArgumentListInfo *TemplateArgs) {
13231 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smithc67fdd42012-03-07 08:35:16 +000013232
Richard Smith100b24a2014-04-17 01:52:14 +000013233 OverloadCandidateSet CandidateSet(UDSuffixLoc,
13234 OverloadCandidateSet::CSK_Normal);
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000013235 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
13236 /*SuppressUserConversions=*/true);
Richard Smithc67fdd42012-03-07 08:35:16 +000013237
Richard Smithbcc22fc2012-03-09 08:00:36 +000013238 bool HadMultipleCandidates = (CandidateSet.size() > 1);
13239
Richard Smithbcc22fc2012-03-09 08:00:36 +000013240 // Perform overload resolution. This will usually be trivial, but might need
13241 // to perform substitutions for a literal operator template.
13242 OverloadCandidateSet::iterator Best;
13243 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
13244 case OR_Success:
13245 case OR_Deleted:
13246 break;
13247
13248 case OR_No_Viable_Function:
13249 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
13250 << R.getLookupName();
13251 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13252 return ExprError();
13253
13254 case OR_Ambiguous:
13255 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
13256 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
13257 return ExprError();
Richard Smithc67fdd42012-03-07 08:35:16 +000013258 }
13259
Richard Smithbcc22fc2012-03-09 08:00:36 +000013260 FunctionDecl *FD = Best->Function;
Nick Lewycky134af912013-02-07 05:08:22 +000013261 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
Akira Hatanaka22461672017-07-13 06:08:27 +000013262 nullptr, HadMultipleCandidates,
Richard Smithbcc22fc2012-03-09 08:00:36 +000013263 SuffixInfo.getLoc(),
13264 SuffixInfo.getInfo());
13265 if (Fn.isInvalid())
13266 return true;
Richard Smithc67fdd42012-03-07 08:35:16 +000013267
13268 // Check the argument types. This should almost always be a no-op, except
13269 // that array-to-pointer decay is applied to string literals.
Richard Smithc67fdd42012-03-07 08:35:16 +000013270 Expr *ConvArgs[2];
Richard Smithe54c3072013-05-05 15:51:06 +000013271 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Richard Smithc67fdd42012-03-07 08:35:16 +000013272 ExprResult InputInit = PerformCopyInitialization(
13273 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
13274 SourceLocation(), Args[ArgIdx]);
13275 if (InputInit.isInvalid())
13276 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013277 ConvArgs[ArgIdx] = InputInit.get();
Richard Smithc67fdd42012-03-07 08:35:16 +000013278 }
13279
Alp Toker314cc812014-01-25 16:55:45 +000013280 QualType ResultTy = FD->getReturnType();
Richard Smithc67fdd42012-03-07 08:35:16 +000013281 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13282 ResultTy = ResultTy.getNonLValueExprType(Context);
13283
Richard Smithc67fdd42012-03-07 08:35:16 +000013284 UserDefinedLiteral *UDL =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013285 new (Context) UserDefinedLiteral(Context, Fn.get(),
Benjamin Kramerc215e762012-08-24 11:54:20 +000013286 llvm::makeArrayRef(ConvArgs, Args.size()),
Richard Smithc67fdd42012-03-07 08:35:16 +000013287 ResultTy, VK, LitEndLoc, UDSuffixLoc);
13288
Alp Toker314cc812014-01-25 16:55:45 +000013289 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
Richard Smithc67fdd42012-03-07 08:35:16 +000013290 return ExprError();
13291
Craig Topperc3ec1492014-05-26 06:22:03 +000013292 if (CheckFunctionCall(FD, UDL, nullptr))
Richard Smithc67fdd42012-03-07 08:35:16 +000013293 return ExprError();
13294
13295 return MaybeBindToTemporary(UDL);
13296}
13297
Sam Panzer0f384432012-08-21 00:52:01 +000013298/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
13299/// given LookupResult is non-empty, it is assumed to describe a member which
13300/// will be invoked. Otherwise, the function will be found via argument
13301/// dependent lookup.
13302/// CallExpr is set to a valid expression and FRS_Success returned on success,
13303/// otherwise CallExpr is set to ExprError() and some non-success value
13304/// is returned.
13305Sema::ForRangeStatus
Richard Smith9f690bd2015-10-27 06:02:45 +000013306Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
13307 SourceLocation RangeLoc,
Sam Panzer0f384432012-08-21 00:52:01 +000013308 const DeclarationNameInfo &NameInfo,
13309 LookupResult &MemberLookup,
13310 OverloadCandidateSet *CandidateSet,
13311 Expr *Range, ExprResult *CallExpr) {
Richard Smith9f690bd2015-10-27 06:02:45 +000013312 Scope *S = nullptr;
13313
Sam Panzer0f384432012-08-21 00:52:01 +000013314 CandidateSet->clear();
13315 if (!MemberLookup.empty()) {
13316 ExprResult MemberRef =
13317 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
13318 /*IsPtr=*/false, CXXScopeSpec(),
13319 /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +000013320 /*FirstQualifierInScope=*/nullptr,
Sam Panzer0f384432012-08-21 00:52:01 +000013321 MemberLookup,
Aaron Ballman6924dcd2015-09-01 14:49:24 +000013322 /*TemplateArgs=*/nullptr, S);
Sam Panzer0f384432012-08-21 00:52:01 +000013323 if (MemberRef.isInvalid()) {
13324 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000013325 return FRS_DiagnosticIssued;
13326 }
Craig Topperc3ec1492014-05-26 06:22:03 +000013327 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
Sam Panzer0f384432012-08-21 00:52:01 +000013328 if (CallExpr->isInvalid()) {
13329 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000013330 return FRS_DiagnosticIssued;
13331 }
13332 } else {
13333 UnresolvedSet<0> FoundNames;
Sam Panzer0f384432012-08-21 00:52:01 +000013334 UnresolvedLookupExpr *Fn =
Craig Topperc3ec1492014-05-26 06:22:03 +000013335 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
Sam Panzer0f384432012-08-21 00:52:01 +000013336 NestedNameSpecifierLoc(), NameInfo,
13337 /*NeedsADL=*/true, /*Overloaded=*/false,
Richard Smithb6626742012-10-18 17:56:02 +000013338 FoundNames.begin(), FoundNames.end());
Sam Panzer0f384432012-08-21 00:52:01 +000013339
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000013340 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
Sam Panzer0f384432012-08-21 00:52:01 +000013341 CandidateSet, CallExpr);
13342 if (CandidateSet->empty() || CandidateSetError) {
13343 *CallExpr = ExprError();
13344 return FRS_NoViableFunction;
13345 }
13346 OverloadCandidateSet::iterator Best;
13347 OverloadingResult OverloadResult =
13348 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
13349
13350 if (OverloadResult == OR_No_Viable_Function) {
13351 *CallExpr = ExprError();
13352 return FRS_NoViableFunction;
13353 }
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000013354 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
Craig Topperc3ec1492014-05-26 06:22:03 +000013355 Loc, nullptr, CandidateSet, &Best,
Sam Panzer0f384432012-08-21 00:52:01 +000013356 OverloadResult,
13357 /*AllowTypoCorrection=*/false);
13358 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
13359 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000013360 return FRS_DiagnosticIssued;
13361 }
13362 }
13363 return FRS_Success;
13364}
13365
13366
Douglas Gregorcd695e52008-11-10 20:40:00 +000013367/// FixOverloadedFunctionReference - E is an expression that refers to
13368/// a C++ overloaded function (possibly with some parentheses and
13369/// perhaps a '&' around it). We have resolved the overloaded function
13370/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +000013371/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +000013372Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +000013373 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +000013374 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000013375 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
13376 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000013377 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000013378 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013379
Douglas Gregor51c538b2009-11-20 19:42:02 +000013380 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013381 }
13382
Douglas Gregor51c538b2009-11-20 19:42:02 +000013383 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000013384 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
13385 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013386 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +000013387 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +000013388 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +000013389 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +000013390 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000013391 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013392
13393 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +000013394 ICE->getCastKind(),
Craig Topperc3ec1492014-05-26 06:22:03 +000013395 SubExpr, nullptr,
John McCall2536c6d2010-08-25 10:28:54 +000013396 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013397 }
13398
Aaron Ballmanff7bd8b2016-09-02 13:45:40 +000013399 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
13400 if (!GSE->isResultDependent()) {
13401 Expr *SubExpr =
13402 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
13403 if (SubExpr == GSE->getResultExpr())
13404 return GSE;
13405
13406 // Replace the resulting type information before rebuilding the generic
13407 // selection expression.
Aaron Ballman8b871d92016-09-02 18:31:31 +000013408 ArrayRef<Expr *> A = GSE->getAssocExprs();
13409 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
Aaron Ballmanff7bd8b2016-09-02 13:45:40 +000013410 unsigned ResultIdx = GSE->getResultIndex();
13411 AssocExprs[ResultIdx] = SubExpr;
13412
13413 return new (Context) GenericSelectionExpr(
13414 Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
13415 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
13416 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
13417 ResultIdx);
13418 }
13419 // Rather than fall through to the unreachable, return the original generic
13420 // selection expression.
13421 return GSE;
13422 }
13423
Douglas Gregor51c538b2009-11-20 19:42:02 +000013424 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +000013425 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +000013426 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +000013427 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13428 if (Method->isStatic()) {
13429 // Do nothing: static member functions aren't any different
13430 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +000013431 } else {
Alp Toker028ed912013-12-06 17:56:43 +000013432 // Fix the subexpression, which really has to be an
John McCalle66edc12009-11-24 19:00:30 +000013433 // UnresolvedLookupExpr holding an overloaded member function
13434 // or template.
John McCall16df1e52010-03-30 21:47:33 +000013435 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13436 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +000013437 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000013438 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +000013439
John McCalld14a8642009-11-21 08:51:07 +000013440 assert(isa<DeclRefExpr>(SubExpr)
13441 && "fixed to something other than a decl ref");
13442 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
13443 && "fixed to a member ref with no nested name qualifier");
13444
13445 // We have taken the address of a pointer to member
13446 // function. Perform the computation here so that we get the
13447 // appropriate pointer to member type.
13448 QualType ClassType
13449 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
13450 QualType MemPtrType
13451 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
David Majnemer02d57cc2016-06-30 03:02:03 +000013452 // Under the MS ABI, lock down the inheritance model now.
13453 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13454 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
John McCalld14a8642009-11-21 08:51:07 +000013455
John McCall7decc9e2010-11-18 06:31:45 +000013456 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
13457 VK_RValue, OK_Ordinary,
13458 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +000013459 }
13460 }
John McCall16df1e52010-03-30 21:47:33 +000013461 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13462 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000013463 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000013464 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013465
John McCalle3027922010-08-25 11:45:40 +000013466 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +000013467 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +000013468 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +000013469 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013470 }
John McCalld14a8642009-11-21 08:51:07 +000013471
Richard Smith84a0b6d2016-10-18 23:39:12 +000013472 // C++ [except.spec]p17:
13473 // An exception-specification is considered to be needed when:
13474 // - in an expression the function is the unique lookup result or the
13475 // selected member of a set of overloaded functions
13476 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13477 ResolveExceptionSpec(E->getExprLoc(), FPT);
13478
John McCalld14a8642009-11-21 08:51:07 +000013479 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +000013480 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000013481 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCalle66edc12009-11-24 19:00:30 +000013482 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +000013483 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
13484 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +000013485 }
13486
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013487 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13488 ULE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000013489 ULE->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013490 Fn,
John McCall113bee02012-03-10 09:33:50 +000013491 /*enclosing*/ false, // FIXME?
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013492 ULE->getNameLoc(),
13493 Fn->getType(),
13494 VK_LValue,
13495 Found.getDecl(),
13496 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000013497 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013498 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
13499 return DRE;
John McCalld14a8642009-11-21 08:51:07 +000013500 }
13501
John McCall10eae182009-11-30 22:42:35 +000013502 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +000013503 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000013504 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCall2d74de92009-12-01 22:10:20 +000013505 if (MemExpr->hasExplicitTemplateArgs()) {
13506 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
13507 TemplateArgs = &TemplateArgsBuffer;
13508 }
John McCall6b51f282009-11-23 01:53:49 +000013509
John McCall2d74de92009-12-01 22:10:20 +000013510 Expr *Base;
13511
John McCall7decc9e2010-11-18 06:31:45 +000013512 // If we're filling in a static method where we used to have an
13513 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +000013514 if (MemExpr->isImplicitAccess()) {
13515 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013516 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13517 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000013518 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013519 Fn,
John McCall113bee02012-03-10 09:33:50 +000013520 /*enclosing*/ false,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013521 MemExpr->getMemberLoc(),
13522 Fn->getType(),
13523 VK_LValue,
13524 Found.getDecl(),
13525 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000013526 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013527 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
13528 return DRE;
Douglas Gregorb15af892010-01-07 23:12:05 +000013529 } else {
13530 SourceLocation Loc = MemExpr->getMemberLoc();
13531 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +000013532 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman73a04092012-01-07 04:59:52 +000013533 CheckCXXThisCapture(Loc);
Douglas Gregorb15af892010-01-07 23:12:05 +000013534 Base = new (Context) CXXThisExpr(Loc,
13535 MemExpr->getBaseType(),
13536 /*isImplicit=*/true);
13537 }
John McCall2d74de92009-12-01 22:10:20 +000013538 } else
John McCallc3007a22010-10-26 07:05:15 +000013539 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +000013540
John McCall4adb38c2011-04-27 00:36:17 +000013541 ExprValueKind valueKind;
13542 QualType type;
13543 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13544 valueKind = VK_LValue;
13545 type = Fn->getType();
13546 } else {
13547 valueKind = VK_RValue;
Yunzhong Gaoeba323a2015-05-01 02:04:32 +000013548 type = Context.BoundMemberTy;
13549 }
13550
13551 MemberExpr *ME = MemberExpr::Create(
13552 Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
13553 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
13554 MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
13555 OK_Ordinary);
13556 ME->setHadMultipleCandidates(true);
13557 MarkMemberReferenced(ME);
13558 return ME;
Douglas Gregor51c538b2009-11-20 19:42:02 +000013559 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013560
John McCallc3007a22010-10-26 07:05:15 +000013561 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregorcd695e52008-11-10 20:40:00 +000013562}
13563
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013564ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +000013565 DeclAccessPair Found,
13566 FunctionDecl *Fn) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000013567 return FixOverloadedFunctionReference(E.get(), Found, Fn);
Douglas Gregor3e1e5272009-12-09 23:02:17 +000013568}