blob: 32a03a57ca38bcf67393e5186a7c6da052d986e7 [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,
51 bool HadMultipleCandidates,
Douglas Gregore9d62932011-07-15 16:25:15 +000052 SourceLocation Loc = SourceLocation(),
53 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
Richard Smith22262ab2013-05-04 06:44:46 +000054 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
Faisal Valid6676412013-06-15 11:54:37 +000055 return ExprError();
56 // If FoundDecl is different from Fn (such as if one is a template
57 // and the other a specialization), make sure DiagnoseUseOfDecl is
58 // 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
71 S.MarkDeclRefReferenced(DRE);
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
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +000082static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
83 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,
134 ICR_Conversion,
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);
Richard Smith52e624f2016-12-21 21:42:57 +0000333
334 // If it's value-dependent, we can't tell whether it's narrowing.
335 if (Initializer->isValueDependent())
336 return NK_Dependent_Narrowing;
337
Richard Smith66e05fe2012-01-18 05:21:49 +0000338 if (Initializer &&
339 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
340 // 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;
855
856 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
866 i = Entries.begin(), e = Entries.end(); i != e; ++i)
867 *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
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000920// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000921// overload of the declarations in Old. This routine returns false if
922// New and Old cannot be overloaded, e.g., if New has the same
923// signature as some function in Old (C++ 1.3.10) or if the Old
924// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000925// it does return false, MatchedDecl will point to the decl that New
926// cannot be overloaded with. This decl may be a UsingShadowDecl on
927// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000928//
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",
Mike Stump11289f42009-09-09 15:08:12 +0000936// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000937//
John McCall3d988d92009-12-02 08:47:38 +0000938// When we process #2, Old contains only the FunctionDecl for #1. By
939// comparing the parameter types, we see that #1 and #2 are overloaded
940// (since they have different signatures), so this routine returns
941// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000942//
John McCall3d988d92009-12-02 08:47:38 +0000943// When we process #3, Old is an overload set containing #1 and #2. We
944// compare the signatures of #3 to #1 (they're overloaded, so we do
945// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
946// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000947// signature), IsOverload returns false and MatchedDecl will be set to
948// point to the FunctionDecl for #2.
John McCalle9cccd82010-06-16 08:42:20 +0000949//
950// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
951// into a class by a using declaration. The rules for whether to hide
952// shadow declarations ignore some properties which otherwise figure
953// into a function template's signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000954Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000955Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
956 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000957 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000958 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000959 NamedDecl *OldD = *I;
960
961 bool OldIsUsingDecl = false;
962 if (isa<UsingShadowDecl>(OldD)) {
963 OldIsUsingDecl = true;
964
965 // We can always introduce two using declarations into the same
966 // context, even if they have identical signatures.
967 if (NewIsUsingDecl) continue;
968
969 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
970 }
971
Richard Smithf091e122015-09-15 01:28:55 +0000972 // A using-declaration does not conflict with another declaration
973 // if one of them is hidden.
974 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
975 continue;
976
John McCalle9cccd82010-06-16 08:42:20 +0000977 // If either declaration was introduced by a using declaration,
978 // we'll need to use slightly different rules for matching.
979 // Essentially, these rules are the normal rules, except that
980 // function templates hide function templates with different
981 // return types or template parameter lists.
982 bool UseMemberUsingDeclRules =
John McCallc70fca62013-04-03 21:19:47 +0000983 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
984 !New->getFriendObjectKind();
John McCalle9cccd82010-06-16 08:42:20 +0000985
Alp Tokera2794f92014-01-22 07:29:52 +0000986 if (FunctionDecl *OldF = OldD->getAsFunction()) {
John McCalle9cccd82010-06-16 08:42:20 +0000987 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
988 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
989 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
990 continue;
991 }
992
Alp Tokera2794f92014-01-22 07:29:52 +0000993 if (!isa<FunctionTemplateDecl>(OldD) &&
994 !shouldLinkPossiblyHiddenDecl(*I, New))
Rafael Espindola5bddd6a2013-04-15 12:49:13 +0000995 continue;
996
John McCalldaa3d6b2009-12-09 03:35:25 +0000997 Match = *I;
998 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000999 }
Richard Smith151c4562016-12-20 21:35:28 +00001000 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +00001001 // We can overload with these, which can show up when doing
1002 // redeclaration checks for UsingDecls.
1003 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalla8987a2942010-11-10 03:01:53 +00001004 } else if (isa<TagDecl>(OldD)) {
1005 // We can always overload with tags by hiding them.
Richard Smithd8a9e372016-12-18 21:39:37 +00001006 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +00001007 // Optimistically assume that an unresolved using decl will
1008 // overload; if it doesn't, we'll have to diagnose during
1009 // template instantiation.
Richard Smithd8a9e372016-12-18 21:39:37 +00001010 //
1011 // Exception: if the scope is dependent and this is not a class
1012 // member, the using declaration can only introduce an enumerator.
1013 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1014 Match = *I;
1015 return Ovl_NonFunction;
1016 }
John McCall84d87672009-12-10 09:41:52 +00001017 } else {
John McCall1f82f242009-11-18 22:49:29 +00001018 // (C++ 13p1):
1019 // Only function declarations can be overloaded; object and type
1020 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +00001021 Match = *I;
1022 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +00001023 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001024 }
John McCall1f82f242009-11-18 22:49:29 +00001025
John McCalldaa3d6b2009-12-09 03:35:25 +00001026 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +00001027}
1028
Richard Smithac974a32013-06-30 09:48:50 +00001029bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
Justin Lebarba122ab2016-03-30 23:30:21 +00001030 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
Richard Smithac974a32013-06-30 09:48:50 +00001031 // C++ [basic.start.main]p2: This function shall not be overloaded.
1032 if (New->isMain())
Rafael Espindola576127d2012-12-28 14:21:58 +00001033 return false;
Rafael Espindola7cf35ef2013-01-12 01:47:40 +00001034
David Majnemerc729b0b2013-09-16 22:44:20 +00001035 // MSVCRT user defined entry points cannot be overloaded.
1036 if (New->isMSVCRTEntryPoint())
1037 return false;
1038
John McCall1f82f242009-11-18 22:49:29 +00001039 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1040 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1041
1042 // C++ [temp.fct]p2:
1043 // A function template can be overloaded with other function templates
1044 // and with normal (non-template) functions.
Craig Topperc3ec1492014-05-26 06:22:03 +00001045 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
John McCall1f82f242009-11-18 22:49:29 +00001046 return true;
1047
1048 // Is the function New an overload of the function Old?
Richard Smithac974a32013-06-30 09:48:50 +00001049 QualType OldQType = Context.getCanonicalType(Old->getType());
1050 QualType NewQType = Context.getCanonicalType(New->getType());
John McCall1f82f242009-11-18 22:49:29 +00001051
1052 // Compare the signatures (C++ 1.3.10) of the two functions to
1053 // determine whether they are overloads. If we find any mismatch
1054 // in the signature, they are overloads.
1055
1056 // If either of these functions is a K&R-style function (no
1057 // prototype), then we consider them to have matching signatures.
1058 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1059 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1060 return false;
1061
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001062 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1063 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
John McCall1f82f242009-11-18 22:49:29 +00001064
1065 // The signature of a function includes the types of its
1066 // parameters (C++ 1.3.10), which includes the presence or absence
1067 // of the ellipsis; see C++ DR 357).
1068 if (OldQType != NewQType &&
Alp Toker9cacbab2014-01-20 20:26:09 +00001069 (OldType->getNumParams() != NewType->getNumParams() ||
John McCall1f82f242009-11-18 22:49:29 +00001070 OldType->isVariadic() != NewType->isVariadic() ||
Alp Toker9cacbab2014-01-20 20:26:09 +00001071 !FunctionParamTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +00001072 return true;
1073
1074 // C++ [temp.over.link]p4:
1075 // The signature of a function template consists of its function
1076 // signature, its return type and its template parameter list. The names
1077 // of the template parameters are significant only for establishing the
1078 // relationship between the template parameters and the rest of the
1079 // signature.
1080 //
1081 // We check the return type and template parameter lists for function
1082 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +00001083 //
1084 // However, we don't consider either of these when deciding whether
1085 // a member introduced by a shadow declaration is hidden.
Justin Lebar39fd5292016-03-30 20:41:05 +00001086 if (!UseMemberUsingDeclRules && NewTemplate &&
Richard Smithac974a32013-06-30 09:48:50 +00001087 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1088 OldTemplate->getTemplateParameters(),
1089 false, TPL_TemplateMatch) ||
Alp Toker314cc812014-01-25 16:55:45 +00001090 OldType->getReturnType() != NewType->getReturnType()))
John McCall1f82f242009-11-18 22:49:29 +00001091 return true;
1092
1093 // If the function is a class member, its signature includes the
Douglas Gregorb2f8aa92011-01-26 17:47:49 +00001094 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall1f82f242009-11-18 22:49:29 +00001095 //
1096 // As part of this, also check whether one of the member functions
1097 // is static, in which case they are not overloads (C++
1098 // 13.1p2). While not part of the definition of the signature,
1099 // this check is important to determine whether these functions
1100 // can be overloaded.
Richard Smith574f4f62013-01-14 05:37:29 +00001101 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1102 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
John McCall1f82f242009-11-18 22:49:29 +00001103 if (OldMethod && NewMethod &&
Richard Smith574f4f62013-01-14 05:37:29 +00001104 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1105 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
Justin Lebar39fd5292016-03-30 20:41:05 +00001106 if (!UseMemberUsingDeclRules &&
Richard Smith574f4f62013-01-14 05:37:29 +00001107 (OldMethod->getRefQualifier() == RQ_None ||
1108 NewMethod->getRefQualifier() == RQ_None)) {
1109 // C++0x [over.load]p2:
1110 // - Member function declarations with the same name and the same
1111 // parameter-type-list as well as member function template
1112 // declarations with the same name, the same parameter-type-list, and
1113 // the same template parameter lists cannot be overloaded if any of
1114 // them, but not all, have a ref-qualifier (8.3.5).
Richard Smithac974a32013-06-30 09:48:50 +00001115 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
Richard Smith574f4f62013-01-14 05:37:29 +00001116 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
Richard Smithac974a32013-06-30 09:48:50 +00001117 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
Richard Smith574f4f62013-01-14 05:37:29 +00001118 }
1119 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001120 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001121
Richard Smith574f4f62013-01-14 05:37:29 +00001122 // We may not have applied the implicit const for a constexpr member
1123 // function yet (because we haven't yet resolved whether this is a static
1124 // or non-static member function). Add it now, on the assumption that this
1125 // is a redeclaration of OldMethod.
David Majnemer42350df2013-11-03 23:51:28 +00001126 unsigned OldQuals = OldMethod->getTypeQualifiers();
Richard Smith574f4f62013-01-14 05:37:29 +00001127 unsigned NewQuals = NewMethod->getTypeQualifiers();
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001128 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
Richard Smithe83b1d32013-06-25 18:46:26 +00001129 !isa<CXXConstructorDecl>(NewMethod))
Richard Smith574f4f62013-01-14 05:37:29 +00001130 NewQuals |= Qualifiers::Const;
David Majnemer42350df2013-11-03 23:51:28 +00001131
1132 // We do not allow overloading based off of '__restrict'.
1133 OldQuals &= ~Qualifiers::Restrict;
1134 NewQuals &= ~Qualifiers::Restrict;
1135 if (OldQuals != NewQuals)
Richard Smith574f4f62013-01-14 05:37:29 +00001136 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001137 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001138
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001139 // Though pass_object_size is placed on parameters and takes an argument, we
1140 // consider it to be a function-level modifier for the sake of function
1141 // identity. Either the function has one or more parameters with
1142 // pass_object_size or it doesn't.
1143 if (functionHasPassObjectSizeParams(New) !=
1144 functionHasPassObjectSizeParams(Old))
1145 return true;
1146
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001147 // enable_if attributes are an order-sensitive part of the signature.
1148 for (specific_attr_iterator<EnableIfAttr>
1149 NewI = New->specific_attr_begin<EnableIfAttr>(),
1150 NewE = New->specific_attr_end<EnableIfAttr>(),
1151 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1152 OldE = Old->specific_attr_end<EnableIfAttr>();
1153 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1154 if (NewI == NewE || OldI == OldE)
1155 return true;
1156 llvm::FoldingSetNodeID NewID, OldID;
1157 NewI->getCond()->Profile(NewID, Context, true);
1158 OldI->getCond()->Profile(OldID, Context, true);
Nick Lewyckyd950ae72014-01-21 01:30:30 +00001159 if (NewID != OldID)
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001160 return true;
1161 }
1162
Justin Lebarba122ab2016-03-30 23:30:21 +00001163 if (getLangOpts().CUDA && ConsiderCudaAttrs) {
Justin Lebare060feb2016-10-03 16:48:23 +00001164 // Don't allow overloading of destructors. (In theory we could, but it
1165 // would be a giant change to clang.)
1166 if (isa<CXXDestructorDecl>(New))
1167 return false;
1168
Artem Belevich94a55e82015-09-22 17:22:59 +00001169 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1170 OldTarget = IdentifyCUDATarget(Old);
Artem Belevich13e9b4d2016-12-07 19:27:16 +00001171 if (NewTarget == CFT_InvalidTarget)
Artem Belevich94a55e82015-09-22 17:22:59 +00001172 return false;
1173
1174 assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target.");
1175
Justin Lebar53b000af2016-10-03 16:48:27 +00001176 // Allow overloading of functions with same signature and different CUDA
1177 // target attributes.
Artem Belevich94a55e82015-09-22 17:22:59 +00001178 return NewTarget != OldTarget;
1179 }
1180
John McCall1f82f242009-11-18 22:49:29 +00001181 // The signatures match; this is not an overload.
1182 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001183}
1184
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00001185/// \brief Checks availability of the function depending on the current
1186/// function context. Inside an unavailable function, unavailability is ignored.
1187///
1188/// \returns true if \arg FD is unavailable and current context is inside
1189/// an available function, false otherwise.
1190bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
Duncan P. N. Exon Smith85363922016-03-08 10:28:52 +00001191 if (!FD->isUnavailable())
1192 return false;
1193
1194 // Walk up the context of the caller.
1195 Decl *C = cast<Decl>(CurContext);
1196 do {
1197 if (C->isUnavailable())
1198 return false;
1199 } while ((C = cast_or_null<Decl>(C->getDeclContext())));
1200 return true;
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00001201}
1202
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001203/// \brief Tries a user-defined conversion from From to ToType.
1204///
1205/// Produces an implicit conversion sequence for when a standard conversion
1206/// is not an option. See TryImplicitConversion for more information.
1207static ImplicitConversionSequence
1208TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1209 bool SuppressUserConversions,
1210 bool AllowExplicit,
1211 bool InOverloadResolution,
1212 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001213 bool AllowObjCWritebackConversion,
1214 bool AllowObjCConversionOnExplicit) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001215 ImplicitConversionSequence ICS;
1216
1217 if (SuppressUserConversions) {
1218 // We're not in the case above, so there is no conversion that
1219 // we can perform.
1220 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1221 return ICS;
1222 }
1223
1224 // Attempt user-defined conversion.
Richard Smith100b24a2014-04-17 01:52:14 +00001225 OverloadCandidateSet Conversions(From->getExprLoc(),
1226 OverloadCandidateSet::CSK_Normal);
Richard Smith48372b62015-01-27 03:30:40 +00001227 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1228 Conversions, AllowExplicit,
1229 AllowObjCConversionOnExplicit)) {
1230 case OR_Success:
1231 case OR_Deleted:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001232 ICS.setUserDefined();
1233 // C++ [over.ics.user]p4:
1234 // A conversion of an expression of class type to the same class
1235 // type is given Exact Match rank, and a conversion of an
1236 // expression of class type to a base class of that type is
1237 // given Conversion rank, in spite of the fact that a copy
1238 // constructor (i.e., a user-defined conversion function) is
1239 // called for those cases.
1240 if (CXXConstructorDecl *Constructor
1241 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1242 QualType FromCanon
1243 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1244 QualType ToCanon
1245 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1246 if (Constructor->isCopyConstructor() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00001247 (FromCanon == ToCanon ||
1248 S.IsDerivedFrom(From->getLocStart(), FromCanon, ToCanon))) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001249 // Turn this into a "standard" conversion sequence, so that it
1250 // gets ranked with standard conversion sequences.
Richard Smithc2bebe92016-05-11 20:37:46 +00001251 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001252 ICS.setStandard();
1253 ICS.Standard.setAsIdentityConversion();
1254 ICS.Standard.setFromType(From->getType());
1255 ICS.Standard.setAllToTypes(ToType);
1256 ICS.Standard.CopyConstructor = Constructor;
Richard Smithc2bebe92016-05-11 20:37:46 +00001257 ICS.Standard.FoundCopyConstructor = Found;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001258 if (ToCanon != FromCanon)
1259 ICS.Standard.Second = ICK_Derived_To_Base;
1260 }
1261 }
Richard Smith48372b62015-01-27 03:30:40 +00001262 break;
1263
1264 case OR_Ambiguous:
Richard Smith1bbaba82015-01-27 23:23:39 +00001265 ICS.setAmbiguous();
1266 ICS.Ambiguous.setFromType(From->getType());
1267 ICS.Ambiguous.setToType(ToType);
1268 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1269 Cand != Conversions.end(); ++Cand)
1270 if (Cand->Viable)
Richard Smithc2bebe92016-05-11 20:37:46 +00001271 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
Richard Smith1bbaba82015-01-27 23:23:39 +00001272 break;
Richard Smith48372b62015-01-27 03:30:40 +00001273
1274 // Fall through.
1275 case OR_No_Viable_Function:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001276 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Richard Smith48372b62015-01-27 03:30:40 +00001277 break;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001278 }
1279
1280 return ICS;
1281}
1282
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001283/// TryImplicitConversion - Attempt to perform an implicit conversion
1284/// from the given expression (Expr) to the given type (ToType). This
1285/// function returns an implicit conversion sequence that can be used
1286/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001287///
1288/// void f(float f);
1289/// void g(int i) { f(i); }
1290///
1291/// this routine would produce an implicit conversion sequence to
1292/// describe the initialization of f from i, which will be a standard
1293/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1294/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1295//
1296/// Note that this routine only determines how the conversion can be
1297/// performed; it does not actually perform the conversion. As such,
1298/// it will not produce any diagnostics if no conversion is available,
1299/// but will instead return an implicit conversion sequence of kind
1300/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +00001301///
1302/// If @p SuppressUserConversions, then user-defined conversions are
1303/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +00001304/// If @p AllowExplicit, then explicit user-defined conversions are
1305/// permitted.
John McCall31168b02011-06-15 23:02:42 +00001306///
1307/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1308/// writeback conversion, which allows __autoreleasing id* parameters to
1309/// be initialized with __strong id* or __weak id* arguments.
John McCall5c32be02010-08-24 20:38:10 +00001310static ImplicitConversionSequence
1311TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1312 bool SuppressUserConversions,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001313 bool AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001314 bool InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001315 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001316 bool AllowObjCWritebackConversion,
1317 bool AllowObjCConversionOnExplicit) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001318 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +00001319 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001320 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall0d1da222010-01-12 00:44:57 +00001321 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +00001322 return ICS;
1323 }
1324
David Blaikiebbafb8a2012-03-11 07:00:24 +00001325 if (!S.getLangOpts().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +00001326 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +00001327 return ICS;
1328 }
1329
Douglas Gregor836a7e82010-08-11 02:15:33 +00001330 // C++ [over.ics.user]p4:
1331 // A conversion of an expression of class type to the same class
1332 // type is given Exact Match rank, and a conversion of an
1333 // expression of class type to a base class of that type is
1334 // given Conversion rank, in spite of the fact that a copy/move
1335 // constructor (i.e., a user-defined conversion function) is
1336 // called for those cases.
1337 QualType FromType = From->getType();
1338 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00001339 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00001340 S.IsDerivedFrom(From->getLocStart(), FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001341 ICS.setStandard();
1342 ICS.Standard.setAsIdentityConversion();
1343 ICS.Standard.setFromType(FromType);
1344 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001345
Douglas Gregor5ab11652010-04-17 22:01:05 +00001346 // We don't actually check at this point whether there is a valid
1347 // copy/move constructor, since overloading just assumes that it
1348 // exists. When we actually perform initialization, we'll find the
1349 // appropriate constructor to copy the returned object, if needed.
Craig Topperc3ec1492014-05-26 06:22:03 +00001350 ICS.Standard.CopyConstructor = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001351
Douglas Gregor5ab11652010-04-17 22:01:05 +00001352 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +00001353 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +00001354 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001355
Douglas Gregor836a7e82010-08-11 02:15:33 +00001356 return ICS;
1357 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001358
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001359 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1360 AllowExplicit, InOverloadResolution, CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001361 AllowObjCWritebackConversion,
1362 AllowObjCConversionOnExplicit);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001363}
1364
John McCall31168b02011-06-15 23:02:42 +00001365ImplicitConversionSequence
1366Sema::TryImplicitConversion(Expr *From, QualType ToType,
1367 bool SuppressUserConversions,
1368 bool AllowExplicit,
1369 bool InOverloadResolution,
1370 bool CStyle,
1371 bool AllowObjCWritebackConversion) {
Richard Smith17c00b42014-11-12 01:24:00 +00001372 return ::TryImplicitConversion(*this, From, ToType,
1373 SuppressUserConversions, AllowExplicit,
1374 InOverloadResolution, CStyle,
1375 AllowObjCWritebackConversion,
1376 /*AllowObjCConversionOnExplicit=*/false);
John McCall5c32be02010-08-24 20:38:10 +00001377}
1378
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001379/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley01296292011-04-08 18:41:53 +00001380/// expression From to the type ToType. Returns the
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001381/// converted expression. Flavor is the kind of conversion we're
1382/// performing, used in the error message. If @p AllowExplicit,
1383/// explicit user-defined conversions are permitted.
John Wiegley01296292011-04-08 18:41:53 +00001384ExprResult
1385Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redlcc152642011-10-16 18:19:06 +00001386 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001387 ImplicitConversionSequence ICS;
Sebastian Redlcc152642011-10-16 18:19:06 +00001388 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001389}
1390
John Wiegley01296292011-04-08 18:41:53 +00001391ExprResult
1392Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001393 AssignmentAction Action, bool AllowExplicit,
Sebastian Redlcc152642011-10-16 18:19:06 +00001394 ImplicitConversionSequence& ICS) {
John McCall526ab472011-10-25 17:37:35 +00001395 if (checkPlaceholderForOverload(*this, From))
1396 return ExprError();
1397
John McCall31168b02011-06-15 23:02:42 +00001398 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1399 bool AllowObjCWritebackConversion
David Blaikiebbafb8a2012-03-11 07:00:24 +00001400 = getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001401 (Action == AA_Passing || Action == AA_Sending);
Fariborz Jahanian381edf52013-12-16 22:54:37 +00001402 if (getLangOpts().ObjC1)
1403 CheckObjCBridgeRelatedConversions(From->getLocStart(),
1404 ToType, From->getType(), From);
Richard Smith17c00b42014-11-12 01:24:00 +00001405 ICS = ::TryImplicitConversion(*this, From, ToType,
1406 /*SuppressUserConversions=*/false,
1407 AllowExplicit,
1408 /*InOverloadResolution=*/false,
1409 /*CStyle=*/false,
1410 AllowObjCWritebackConversion,
1411 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001412 return PerformImplicitConversion(From, ToType, ICS, Action);
1413}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001414
1415/// \brief Determine whether the conversion from FromType to ToType is a valid
Richard Smith3c4f8d22016-10-16 17:54:23 +00001416/// conversion that strips "noexcept" or "noreturn" off the nested function
1417/// type.
1418bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
Chandler Carruth53e61b02011-06-18 01:19:03 +00001419 QualType &ResultTy) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001420 if (Context.hasSameUnqualifiedType(FromType, ToType))
1421 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001422
John McCall991eb4b2010-12-21 00:44:39 +00001423 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
Richard Smith3c4f8d22016-10-16 17:54:23 +00001424 // or F(t noexcept) -> F(t)
John McCall991eb4b2010-12-21 00:44:39 +00001425 // where F adds one of the following at most once:
1426 // - a pointer
1427 // - a member pointer
1428 // - a block pointer
Richard Smitheb7ef2e2016-10-20 21:53:09 +00001429 // Changes here need matching changes in FindCompositePointerType.
John McCall991eb4b2010-12-21 00:44:39 +00001430 CanQualType CanTo = Context.getCanonicalType(ToType);
1431 CanQualType CanFrom = Context.getCanonicalType(FromType);
1432 Type::TypeClass TyClass = CanTo->getTypeClass();
1433 if (TyClass != CanFrom->getTypeClass()) return false;
1434 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1435 if (TyClass == Type::Pointer) {
1436 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1437 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1438 } else if (TyClass == Type::BlockPointer) {
1439 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1440 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1441 } else if (TyClass == Type::MemberPointer) {
Richard Smitheb7ef2e2016-10-20 21:53:09 +00001442 auto ToMPT = CanTo.getAs<MemberPointerType>();
1443 auto FromMPT = CanFrom.getAs<MemberPointerType>();
1444 // A function pointer conversion cannot change the class of the function.
1445 if (ToMPT->getClass() != FromMPT->getClass())
1446 return false;
1447 CanTo = ToMPT->getPointeeType();
1448 CanFrom = FromMPT->getPointeeType();
John McCall991eb4b2010-12-21 00:44:39 +00001449 } else {
1450 return false;
1451 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001452
John McCall991eb4b2010-12-21 00:44:39 +00001453 TyClass = CanTo->getTypeClass();
1454 if (TyClass != CanFrom->getTypeClass()) return false;
1455 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1456 return false;
1457 }
1458
Richard Smith3c4f8d22016-10-16 17:54:23 +00001459 const auto *FromFn = cast<FunctionType>(CanFrom);
1460 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
John McCall991eb4b2010-12-21 00:44:39 +00001461
Richard Smith6f427402016-10-20 00:01:36 +00001462 const auto *ToFn = cast<FunctionType>(CanTo);
Richard Smith3c4f8d22016-10-16 17:54:23 +00001463 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1464
1465 bool Changed = false;
1466
1467 // Drop 'noreturn' if not present in target type.
1468 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1469 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1470 Changed = true;
1471 }
1472
1473 // Drop 'noexcept' if not present in target type.
1474 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
Richard Smith6f427402016-10-20 00:01:36 +00001475 const auto *ToFPT = cast<FunctionProtoType>(ToFn);
Richard Smith3c4f8d22016-10-16 17:54:23 +00001476 if (FromFPT->isNothrow(Context) && !ToFPT->isNothrow(Context)) {
1477 FromFn = cast<FunctionType>(
1478 Context.getFunctionType(FromFPT->getReturnType(),
1479 FromFPT->getParamTypes(),
1480 FromFPT->getExtProtoInfo().withExceptionSpec(
1481 FunctionProtoType::ExceptionSpecInfo()))
1482 .getTypePtr());
1483 Changed = true;
1484 }
1485 }
1486
1487 if (!Changed)
1488 return false;
1489
John McCall991eb4b2010-12-21 00:44:39 +00001490 assert(QualType(FromFn, 0).isCanonical());
1491 if (QualType(FromFn, 0) != CanTo) return false;
1492
1493 ResultTy = ToType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001494 return true;
1495}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001496
Douglas Gregor46188682010-05-18 22:42:18 +00001497/// \brief Determine whether the conversion from FromType to ToType is a valid
1498/// vector conversion.
1499///
1500/// \param ICK Will be set to the vector conversion kind, if this is a vector
1501/// conversion.
John McCall9b595db2014-02-04 23:58:19 +00001502static bool IsVectorConversion(Sema &S, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001503 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregor46188682010-05-18 22:42:18 +00001504 // We need at least one of these types to be a vector type to have a vector
1505 // conversion.
1506 if (!ToType->isVectorType() && !FromType->isVectorType())
1507 return false;
1508
1509 // Identical types require no conversions.
John McCall9b595db2014-02-04 23:58:19 +00001510 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor46188682010-05-18 22:42:18 +00001511 return false;
1512
1513 // There are no conversions between extended vector types, only identity.
1514 if (ToType->isExtVectorType()) {
1515 // There are no conversions between extended vector types other than the
1516 // identity conversion.
1517 if (FromType->isExtVectorType())
1518 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001519
Douglas Gregor46188682010-05-18 22:42:18 +00001520 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +00001521 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +00001522 ICK = ICK_Vector_Splat;
1523 return true;
1524 }
1525 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001526
1527 // We can perform the conversion between vector types in the following cases:
1528 // 1)vector types are equivalent AltiVec and GCC vector types
1529 // 2)lax vector conversions are permitted and the vector types are of the
1530 // same size
1531 if (ToType->isVectorType() && FromType->isVectorType()) {
John McCall9b595db2014-02-04 23:58:19 +00001532 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1533 S.isLaxVectorConversion(FromType, ToType)) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001534 ICK = ICK_Vector_Conversion;
1535 return true;
1536 }
Douglas Gregor46188682010-05-18 22:42:18 +00001537 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001538
Douglas Gregor46188682010-05-18 22:42:18 +00001539 return false;
1540}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001541
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001542static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1543 bool InOverloadResolution,
1544 StandardConversionSequence &SCS,
1545 bool CStyle);
George Burgess IV45461812015-10-11 20:13:20 +00001546
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001547/// IsStandardConversion - Determines whether there is a standard
1548/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1549/// expression From to the type ToType. Standard conversion sequences
1550/// only consider non-class types; for conversions that involve class
1551/// types, use TryImplicitConversion. If a conversion exists, SCS will
1552/// contain the standard conversion sequence required to perform this
1553/// conversion and this routine will return true. Otherwise, this
1554/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +00001555static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1556 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +00001557 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +00001558 bool CStyle,
1559 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001560 QualType FromType = From->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001561
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001562 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +00001563 SCS.setAsIdentityConversion();
Douglas Gregor47d3f272008-12-19 17:40:08 +00001564 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +00001565 SCS.setFromType(FromType);
Craig Topperc3ec1492014-05-26 06:22:03 +00001566 SCS.CopyConstructor = nullptr;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001567
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001568 // There are no standard conversions for class types in C++, so
George Burgess IV45461812015-10-11 20:13:20 +00001569 // abort early. When overloading in C, however, we do permit them.
1570 if (S.getLangOpts().CPlusPlus &&
1571 (FromType->isRecordType() || ToType->isRecordType()))
1572 return false;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001573
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001574 // The first conversion can be an lvalue-to-rvalue conversion,
1575 // array-to-pointer conversion, or function-to-pointer conversion
1576 // (C++ 4p1).
1577
John McCall5c32be02010-08-24 20:38:10 +00001578 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001579 DeclAccessPair AccessPair;
1580 if (FunctionDecl *Fn
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001581 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall5c32be02010-08-24 20:38:10 +00001582 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001583 // We were able to resolve the address of the overloaded function,
1584 // so we can convert to the type of that function.
1585 FromType = Fn->getType();
Ehsan Akhgaric3ad3ba2014-07-22 20:20:14 +00001586 SCS.setFromType(FromType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00001587
1588 // we can sometimes resolve &foo<int> regardless of ToType, so check
1589 // if the type matches (identity) or we are converting to bool
1590 if (!S.Context.hasSameUnqualifiedType(
1591 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1592 QualType resultTy;
1593 // if the function type matches except for [[noreturn]], it's ok
Richard Smith3c4f8d22016-10-16 17:54:23 +00001594 if (!S.IsFunctionConversion(FromType,
Douglas Gregorb491ed32011-02-19 21:32:49 +00001595 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1596 // otherwise, only a boolean conversion is standard
1597 if (!ToType->isBooleanType())
1598 return false;
Douglas Gregor980fb162010-04-29 18:24:40 +00001599 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001600
Chandler Carruthffce2452011-03-29 08:08:18 +00001601 // Check if the "from" expression is taking the address of an overloaded
1602 // function and recompute the FromType accordingly. Take advantage of the
1603 // fact that non-static member functions *must* have such an address-of
1604 // expression.
1605 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1606 if (Method && !Method->isStatic()) {
1607 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1608 "Non-unary operator on non-static member address");
1609 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1610 == UO_AddrOf &&
1611 "Non-address-of operator on non-static member address");
1612 const Type *ClassType
1613 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1614 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruth7750f762011-03-29 18:38:10 +00001615 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1616 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1617 UO_AddrOf &&
Chandler Carruthffce2452011-03-29 08:08:18 +00001618 "Non-address-of operator for overloaded function expression");
1619 FromType = S.Context.getPointerType(FromType);
1620 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001621
Douglas Gregor980fb162010-04-29 18:24:40 +00001622 // Check that we've computed the proper type after overload resolution.
Richard Smith9095e5b2016-11-01 01:31:23 +00001623 // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't
1624 // be calling it from within an NDEBUG block.
Chandler Carruthffce2452011-03-29 08:08:18 +00001625 assert(S.Context.hasSameType(
1626 FromType,
1627 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001628 } else {
1629 return false;
1630 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001631 }
John McCall154a2fd2011-08-30 00:57:29 +00001632 // Lvalue-to-rvalue conversion (C++11 4.1):
1633 // A glvalue (3.10) of a non-function, non-array type T can
1634 // be converted to a prvalue.
1635 bool argIsLValue = From->isGLValue();
John McCall086a4642010-11-24 05:12:34 +00001636 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001637 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001638 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001639 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001640
Douglas Gregorc79862f2012-04-12 17:51:55 +00001641 // C11 6.3.2.1p2:
1642 // ... if the lvalue has atomic type, the value has the non-atomic version
1643 // of the type of the lvalue ...
1644 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1645 FromType = Atomic->getValueType();
1646
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001647 // If T is a non-class type, the type of the rvalue is the
1648 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001649 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1650 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001651 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001652 } else if (FromType->isArrayType()) {
1653 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001654 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001655
1656 // An lvalue or rvalue of type "array of N T" or "array of unknown
1657 // bound of T" can be converted to an rvalue of type "pointer to
1658 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001659 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001660
John McCall5c32be02010-08-24 20:38:10 +00001661 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00001662 // This conversion is deprecated in C++03 (D.4)
Douglas Gregore489a7d2010-02-28 18:30:25 +00001663 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001664
1665 // For the purpose of ranking in overload resolution
1666 // (13.3.3.1.1), this conversion is considered an
1667 // array-to-pointer conversion followed by a qualification
1668 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001669 SCS.Second = ICK_Identity;
1670 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001671 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001672 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001673 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001674 }
John McCall086a4642010-11-24 05:12:34 +00001675 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001676 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001677 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001678
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001679 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1680 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1681 if (!S.checkAddressOfFunctionIsAvailable(FD))
1682 return false;
1683
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001684 // An lvalue of function type T can be converted to an rvalue of
1685 // type "pointer to T." The result is a pointer to the
1686 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001687 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001688 } else {
1689 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001690 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001691 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001692 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001693
1694 // The second conversion can be an integral promotion, floating
1695 // point promotion, integral conversion, floating point conversion,
1696 // floating-integral conversion, pointer conversion,
1697 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001698 // For overloading in C, this can also be a "compatible-type"
1699 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001700 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001701 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001702 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001703 // The unqualified versions of the types are the same: there's no
1704 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001705 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001706 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001707 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001708 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001709 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001710 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001711 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001712 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001713 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001714 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001715 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001716 SCS.Second = ICK_Complex_Promotion;
1717 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001718 } else if (ToType->isBooleanType() &&
1719 (FromType->isArithmeticType() ||
1720 FromType->isAnyPointerType() ||
1721 FromType->isBlockPointerType() ||
1722 FromType->isMemberPointerType() ||
1723 FromType->isNullPtrType())) {
1724 // Boolean conversions (C++ 4.12).
1725 SCS.Second = ICK_Boolean_Conversion;
1726 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001727 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001728 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001729 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001730 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001731 FromType = ToType.getUnqualifiedType();
Richard Smithb8a98242013-05-10 20:29:50 +00001732 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001733 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001734 SCS.Second = ICK_Complex_Conversion;
1735 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001736 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1737 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001738 // Complex-real conversions (C99 6.3.1.7)
1739 SCS.Second = ICK_Complex_Real;
1740 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001741 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001742 // FIXME: disable conversions between long double and __float128 if
1743 // their representation is different until there is back end support
1744 // We of course allow this conversion if long double is really double.
1745 if (&S.Context.getFloatTypeSemantics(FromType) !=
1746 &S.Context.getFloatTypeSemantics(ToType)) {
1747 bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1748 ToType == S.Context.LongDoubleTy) ||
1749 (FromType == S.Context.LongDoubleTy &&
1750 ToType == S.Context.Float128Ty));
1751 if (Float128AndLongDouble &&
1752 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) !=
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001753 &llvm::APFloat::IEEEdouble()))
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001754 return false;
1755 }
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001756 // Floating point conversions (C++ 4.8).
1757 SCS.Second = ICK_Floating_Conversion;
1758 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001759 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001760 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001761 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001762 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001763 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001764 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001765 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001766 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCall31168b02011-06-15 23:02:42 +00001767 SCS.Second = ICK_Block_Pointer_Conversion;
1768 } else if (AllowObjCWritebackConversion &&
1769 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1770 SCS.Second = ICK_Writeback_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001771 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1772 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001773 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001774 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001775 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregoraec25842011-04-26 23:16:46 +00001776 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001777 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall5c32be02010-08-24 20:38:10 +00001778 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001779 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001780 SCS.Second = ICK_Pointer_Member;
John McCall9b595db2014-02-04 23:58:19 +00001781 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001782 SCS.Second = SecondICK;
1783 FromType = ToType.getUnqualifiedType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001784 } else if (!S.getLangOpts().CPlusPlus &&
John McCall5c32be02010-08-24 20:38:10 +00001785 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001786 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001787 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001788 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001789 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1790 InOverloadResolution,
1791 SCS, CStyle)) {
1792 SCS.Second = ICK_TransparentUnionConversion;
1793 FromType = ToType;
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001794 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1795 CStyle)) {
1796 // tryAtomicConversion has updated the standard conversion sequence
Douglas Gregorc79862f2012-04-12 17:51:55 +00001797 // appropriately.
1798 return true;
George Burgess IV45461812015-10-11 20:13:20 +00001799 } else if (ToType->isEventT() &&
Guy Benyei259f9f42013-02-07 16:05:33 +00001800 From->isIntegerConstantExpr(S.getASTContext()) &&
George Burgess IV45461812015-10-11 20:13:20 +00001801 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
Guy Benyei259f9f42013-02-07 16:05:33 +00001802 SCS.Second = ICK_Zero_Event_Conversion;
1803 FromType = ToType;
Egor Churaev89831422016-12-23 14:55:49 +00001804 } else if (ToType->isQueueT() &&
1805 From->isIntegerConstantExpr(S.getASTContext()) &&
1806 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1807 SCS.Second = ICK_Zero_Queue_Conversion;
1808 FromType = ToType;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001809 } else {
1810 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001811 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001812 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001813 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001814
Richard Smitheb7ef2e2016-10-20 21:53:09 +00001815 // The third conversion can be a function pointer conversion or a
1816 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
John McCall31168b02011-06-15 23:02:42 +00001817 bool ObjCLifetimeConversion;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00001818 if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1819 // Function pointer conversions (removing 'noexcept') including removal of
1820 // 'noreturn' (Clang extension).
1821 SCS.Third = ICK_Function_Conversion;
1822 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1823 ObjCLifetimeConversion)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001824 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001825 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001826 FromType = ToType;
1827 } else {
1828 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001829 SCS.Third = ICK_Identity;
Richard Smith9c37e662016-10-20 17:57:33 +00001830 }
Richard Smitheb7ef2e2016-10-20 21:53:09 +00001831
1832 // C++ [over.best.ics]p6:
1833 // [...] Any difference in top-level cv-qualification is
1834 // subsumed by the initialization itself and does not constitute
1835 // a conversion. [...]
1836 QualType CanonFrom = S.Context.getCanonicalType(FromType);
1837 QualType CanonTo = S.Context.getCanonicalType(ToType);
1838 if (CanonFrom.getLocalUnqualifiedType()
1839 == CanonTo.getLocalUnqualifiedType() &&
1840 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1841 FromType = ToType;
1842 CanonFrom = CanonTo;
1843 }
1844
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001845 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001846
George Burgess IV45461812015-10-11 20:13:20 +00001847 if (CanonFrom == CanonTo)
1848 return true;
1849
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001850 // If we have not converted the argument type to the parameter type,
George Burgess IV45461812015-10-11 20:13:20 +00001851 // this is a bad conversion sequence, unless we're resolving an overload in C.
1852 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001853 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001854
George Burgess IV45461812015-10-11 20:13:20 +00001855 ExprResult ER = ExprResult{From};
George Burgess IV2099b542016-09-02 22:59:57 +00001856 Sema::AssignConvertType Conv =
1857 S.CheckSingleAssignmentConstraints(ToType, ER,
1858 /*Diagnose=*/false,
1859 /*DiagnoseCFAudited=*/false,
1860 /*ConvertRHS=*/false);
George Burgess IV6098fd12016-09-03 00:28:25 +00001861 ImplicitConversionKind SecondConv;
George Burgess IV2099b542016-09-02 22:59:57 +00001862 switch (Conv) {
1863 case Sema::Compatible:
George Burgess IV6098fd12016-09-03 00:28:25 +00001864 SecondConv = ICK_C_Only_Conversion;
George Burgess IV2099b542016-09-02 22:59:57 +00001865 break;
1866 // For our purposes, discarding qualifiers is just as bad as using an
1867 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
1868 // qualifiers, as well.
1869 case Sema::CompatiblePointerDiscardsQualifiers:
1870 case Sema::IncompatiblePointer:
1871 case Sema::IncompatiblePointerSign:
George Burgess IV6098fd12016-09-03 00:28:25 +00001872 SecondConv = ICK_Incompatible_Pointer_Conversion;
George Burgess IV2099b542016-09-02 22:59:57 +00001873 break;
1874 default:
George Burgess IV45461812015-10-11 20:13:20 +00001875 return false;
George Burgess IV2099b542016-09-02 22:59:57 +00001876 }
George Burgess IV45461812015-10-11 20:13:20 +00001877
George Burgess IV6098fd12016-09-03 00:28:25 +00001878 // First can only be an lvalue conversion, so we pretend that this was the
1879 // second conversion. First should already be valid from earlier in the
1880 // function.
1881 SCS.Second = SecondConv;
1882 SCS.setToType(1, ToType);
1883
1884 // Third is Identity, because Second should rank us worse than any other
1885 // conversion. This could also be ICK_Qualification, but it's simpler to just
1886 // lump everything in with the second conversion, and we don't gain anything
1887 // from making this ICK_Qualification.
1888 SCS.Third = ICK_Identity;
1889 SCS.setToType(2, ToType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001890 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001891}
George Burgess IV2099b542016-09-02 22:59:57 +00001892
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001893static bool
1894IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1895 QualType &ToType,
1896 bool InOverloadResolution,
1897 StandardConversionSequence &SCS,
1898 bool CStyle) {
1899
1900 const RecordType *UT = ToType->getAsUnionType();
1901 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1902 return false;
1903 // The field to initialize within the transparent union.
1904 RecordDecl *UD = UT->getDecl();
1905 // It's compatible if the expression matches any of the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001906 for (const auto *it : UD->fields()) {
John McCall31168b02011-06-15 23:02:42 +00001907 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1908 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001909 ToType = it->getType();
1910 return true;
1911 }
1912 }
1913 return false;
1914}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001915
1916/// IsIntegralPromotion - Determines whether the conversion from the
1917/// expression From (whose potentially-adjusted type is FromType) to
1918/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1919/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001920bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001921 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001922 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001923 if (!To) {
1924 return false;
1925 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001926
1927 // An rvalue of type char, signed char, unsigned char, short int, or
1928 // unsigned short int can be converted to an rvalue of type int if
1929 // int can represent all the values of the source type; otherwise,
1930 // the source rvalue can be converted to an rvalue of type unsigned
1931 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001932 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1933 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001934 if (// We can promote any signed, promotable integer type to an int
1935 (FromType->isSignedIntegerType() ||
1936 // We can promote any unsigned integer type whose size is
1937 // less than int to an int.
Benjamin Kramer5ff67472016-04-11 08:26:13 +00001938 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001939 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001940 }
1941
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001942 return To->getKind() == BuiltinType::UInt;
1943 }
1944
Richard Smithb9c5a602012-09-13 21:18:54 +00001945 // C++11 [conv.prom]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001946 // A prvalue of an unscoped enumeration type whose underlying type is not
1947 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1948 // following types that can represent all the values of the enumeration
1949 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1950 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001951 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001952 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001953 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001954 // with lowest integer conversion rank (4.13) greater than the rank of long
1955 // long in which all the values of the enumeration can be represented. If
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001956 // there are two such extended types, the signed one is chosen.
Richard Smithb9c5a602012-09-13 21:18:54 +00001957 // C++11 [conv.prom]p4:
1958 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1959 // can be converted to a prvalue of its underlying type. Moreover, if
1960 // integral promotion can be applied to its underlying type, a prvalue of an
1961 // unscoped enumeration type whose underlying type is fixed can also be
1962 // converted to a prvalue of the promoted underlying type.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001963 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1964 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1965 // provided for a scoped enumeration.
1966 if (FromEnumType->getDecl()->isScoped())
1967 return false;
1968
Richard Smithb9c5a602012-09-13 21:18:54 +00001969 // We can perform an integral promotion to the underlying type of the enum,
Richard Smithac8c1752015-03-28 00:31:40 +00001970 // even if that's not the promoted type. Note that the check for promoting
1971 // the underlying type is based on the type alone, and does not consider
1972 // the bitfield-ness of the actual source expression.
Richard Smithb9c5a602012-09-13 21:18:54 +00001973 if (FromEnumType->getDecl()->isFixed()) {
1974 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1975 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
Richard Smithac8c1752015-03-28 00:31:40 +00001976 IsIntegralPromotion(nullptr, Underlying, ToType);
Richard Smithb9c5a602012-09-13 21:18:54 +00001977 }
1978
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001979 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001980 if (ToType->isIntegerType() &&
Richard Smithdb0ac552015-12-18 22:40:25 +00001981 isCompleteType(From->getLocStart(), FromType))
Richard Smith88f4bba2015-03-26 00:16:07 +00001982 return Context.hasSameUnqualifiedType(
1983 ToType, FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001984 }
John McCall56774992009-12-09 09:09:27 +00001985
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001986 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001987 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1988 // to an rvalue a prvalue of the first of the following types that can
1989 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001990 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001991 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001992 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001993 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001994 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001995 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001996 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001997 // Determine whether the type we're converting from is signed or
1998 // unsigned.
David Majnemerfa01a582011-07-22 21:09:04 +00001999 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002000 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002001
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002002 // The types we'll try to promote to, in the appropriate
2003 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00002004 QualType PromoteTypes[6] = {
2005 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00002006 Context.LongTy, Context.UnsignedLongTy ,
2007 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002008 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00002009 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002010 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2011 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00002012 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002013 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2014 // We found the type that we can promote to. If this is the
2015 // type we wanted, we have a promotion. Otherwise, no
2016 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002017 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002018 }
2019 }
2020 }
2021
2022 // An rvalue for an integral bit-field (9.6) can be converted to an
2023 // rvalue of type int if int can represent all the values of the
2024 // bit-field; otherwise, it can be converted to unsigned int if
2025 // unsigned int can represent all the values of the bit-field. If
2026 // the bit-field is larger yet, no integral promotion applies to
2027 // it. If the bit-field has an enumerated type, it is treated as any
2028 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00002029 // FIXME: We should delay checking of bit-fields until we actually perform the
2030 // conversion.
Richard Smith88f4bba2015-03-26 00:16:07 +00002031 if (From) {
John McCalld25db7e2013-05-06 21:39:12 +00002032 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
Richard Smith88f4bba2015-03-26 00:16:07 +00002033 llvm::APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00002034 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00002035 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
Richard Smith88f4bba2015-03-26 00:16:07 +00002036 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
Douglas Gregor71235ec2009-05-02 02:18:30 +00002037 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00002038
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00002039 // Are we promoting to an int from a bitfield that fits in an int?
2040 if (BitWidth < ToSize ||
2041 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
2042 return To->getKind() == BuiltinType::Int;
2043 }
Mike Stump11289f42009-09-09 15:08:12 +00002044
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00002045 // Are we promoting to an unsigned int from an unsigned bitfield
2046 // that fits into an unsigned int?
2047 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
2048 return To->getKind() == BuiltinType::UInt;
2049 }
Mike Stump11289f42009-09-09 15:08:12 +00002050
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00002051 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002052 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002053 }
Richard Smith88f4bba2015-03-26 00:16:07 +00002054 }
Mike Stump11289f42009-09-09 15:08:12 +00002055
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002056 // An rvalue of type bool can be converted to an rvalue of type int,
2057 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002058 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002059 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002060 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002061
2062 return false;
2063}
2064
2065/// IsFloatingPointPromotion - Determines whether the conversion from
2066/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2067/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00002068bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00002069 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2070 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002071 /// An rvalue of type float can be converted to an rvalue of type
2072 /// double. (C++ 4.6p1).
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002073 if (FromBuiltin->getKind() == BuiltinType::Float &&
2074 ToBuiltin->getKind() == BuiltinType::Double)
2075 return true;
2076
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002077 // C99 6.3.1.5p1:
2078 // When a float is promoted to double or long double, or a
2079 // double is promoted to long double [...].
David Blaikiebbafb8a2012-03-11 07:00:24 +00002080 if (!getLangOpts().CPlusPlus &&
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002081 (FromBuiltin->getKind() == BuiltinType::Float ||
2082 FromBuiltin->getKind() == BuiltinType::Double) &&
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002083 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2084 ToBuiltin->getKind() == BuiltinType::Float128))
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002085 return true;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002086
2087 // Half can be promoted to float.
Joey Goulydd7f4562013-01-23 11:56:20 +00002088 if (!getLangOpts().NativeHalfType &&
2089 FromBuiltin->getKind() == BuiltinType::Half &&
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002090 ToBuiltin->getKind() == BuiltinType::Float)
2091 return true;
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002092 }
2093
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002094 return false;
2095}
2096
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002097/// \brief Determine if a conversion is a complex promotion.
2098///
2099/// A complex promotion is defined as a complex -> complex conversion
2100/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00002101/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002102bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00002103 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002104 if (!FromComplex)
2105 return false;
2106
John McCall9dd450b2009-09-21 23:43:11 +00002107 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002108 if (!ToComplex)
2109 return false;
2110
2111 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00002112 ToComplex->getElementType()) ||
Craig Topperc3ec1492014-05-26 06:22:03 +00002113 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00002114 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002115}
2116
Douglas Gregor237f96c2008-11-26 23:31:11 +00002117/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2118/// the pointer type FromPtr to a pointer to type ToPointee, with the
2119/// same type qualifiers as FromPtr has on its pointee type. ToType,
2120/// if non-empty, will be a pointer to ToType that may or may not have
2121/// the right set of qualifiers on its pointee.
John McCall31168b02011-06-15 23:02:42 +00002122///
Mike Stump11289f42009-09-09 15:08:12 +00002123static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002124BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002125 QualType ToPointee, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002126 ASTContext &Context,
2127 bool StripObjCLifetime = false) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002128 assert((FromPtr->getTypeClass() == Type::Pointer ||
2129 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2130 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002131
John McCall31168b02011-06-15 23:02:42 +00002132 /// Conversions to 'id' subsume cv-qualifier conversions.
2133 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00002134 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002135
2136 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002137 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00002138 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00002139 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00002140
John McCall31168b02011-06-15 23:02:42 +00002141 if (StripObjCLifetime)
2142 Quals.removeObjCLifetime();
2143
Mike Stump11289f42009-09-09 15:08:12 +00002144 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002145 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00002146 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00002147 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00002148 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002149
2150 // Build a pointer to ToPointee. It has the right qualifiers
2151 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002152 if (isa<ObjCObjectPointerType>(ToType))
2153 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00002154 return Context.getPointerType(ToPointee);
2155 }
2156
2157 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002158 QualType QualifiedCanonToPointee
2159 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002160
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002161 if (isa<ObjCObjectPointerType>(ToType))
2162 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2163 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002164}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002165
Mike Stump11289f42009-09-09 15:08:12 +00002166static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00002167 bool InOverloadResolution,
2168 ASTContext &Context) {
2169 // Handle value-dependent integral null pointer constants correctly.
2170 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2171 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00002172 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00002173 return !InOverloadResolution;
2174
Douglas Gregor56751b52009-09-25 04:25:58 +00002175 return Expr->isNullPointerConstant(Context,
2176 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2177 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00002178}
Mike Stump11289f42009-09-09 15:08:12 +00002179
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002180/// IsPointerConversion - Determines whether the conversion of the
2181/// expression From, which has the (possibly adjusted) type FromType,
2182/// can be converted to the type ToType via a pointer conversion (C++
2183/// 4.10). If so, returns true and places the converted type (that
2184/// might differ from ToType in its cv-qualifiers at some level) into
2185/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00002186///
Douglas Gregora29dc052008-11-27 01:19:21 +00002187/// This routine also supports conversions to and from block pointers
2188/// and conversions with Objective-C's 'id', 'id<protocols...>', and
2189/// pointers to interfaces. FIXME: Once we've determined the
2190/// appropriate overloading rules for Objective-C, we may want to
2191/// split the Objective-C checks into a different routine; however,
2192/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00002193/// conversions, so for now they live here. IncompatibleObjC will be
2194/// set if the conversion is an allowed Objective-C conversion that
2195/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002196bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00002197 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00002198 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00002199 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00002200 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00002201 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2202 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00002203 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00002204
Mike Stump11289f42009-09-09 15:08:12 +00002205 // Conversion from a null pointer constant to any Objective-C pointer type.
2206 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002207 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00002208 ConvertedType = ToType;
2209 return true;
2210 }
2211
Douglas Gregor231d1c62008-11-27 00:15:41 +00002212 // Blocks: Block pointers can be converted to void*.
2213 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002214 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00002215 ConvertedType = ToType;
2216 return true;
2217 }
2218 // Blocks: A null pointer constant can be converted to a block
2219 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00002220 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002221 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00002222 ConvertedType = ToType;
2223 return true;
2224 }
2225
Sebastian Redl576fd422009-05-10 18:38:11 +00002226 // If the left-hand-side is nullptr_t, the right side can be a null
2227 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00002228 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002229 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00002230 ConvertedType = ToType;
2231 return true;
2232 }
2233
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002234 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002235 if (!ToTypePtr)
2236 return false;
2237
2238 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00002239 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002240 ConvertedType = ToType;
2241 return true;
2242 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002243
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002244 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002245 // , including objective-c pointers.
2246 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00002247 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002248 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002249 ConvertedType = BuildSimilarlyQualifiedPointerType(
2250 FromType->getAs<ObjCObjectPointerType>(),
2251 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002252 ToType, Context);
2253 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002254 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002255 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002256 if (!FromTypePtr)
2257 return false;
2258
2259 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002260
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002261 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-08-18 21:25:30 +00002262 // pointer conversion, so don't do all of the work below.
2263 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2264 return false;
2265
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002266 // An rvalue of type "pointer to cv T," where T is an object type,
2267 // can be converted to an rvalue of type "pointer to cv void" (C++
2268 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00002269 if (FromPointeeType->isIncompleteOrObjectType() &&
2270 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002271 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002272 ToPointeeType,
John McCall31168b02011-06-15 23:02:42 +00002273 ToType, Context,
2274 /*StripObjCLifetime=*/true);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002275 return true;
2276 }
2277
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002278 // MSVC allows implicit function to void* type conversion.
David Majnemer6bf02822015-10-31 08:42:14 +00002279 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002280 ToPointeeType->isVoidType()) {
2281 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2282 ToPointeeType,
2283 ToType, Context);
2284 return true;
2285 }
2286
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002287 // When we're overloading in C, we allow a special kind of pointer
2288 // conversion for compatible-but-not-identical pointee types.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002289 if (!getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002290 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002291 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002292 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00002293 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002294 return true;
2295 }
2296
Douglas Gregor5c407d92008-10-23 00:40:37 +00002297 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002298 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00002299 // An rvalue of type "pointer to cv D," where D is a class type,
2300 // can be converted to an rvalue of type "pointer to cv B," where
2301 // B is a base class (clause 10) of D. If B is an inaccessible
2302 // (clause 11) or ambiguous (10.2) base class of D, a program that
2303 // necessitates this conversion is ill-formed. The result of the
2304 // conversion is a pointer to the base class sub-object of the
2305 // derived class object. The null pointer value is converted to
2306 // the null pointer value of the destination type.
2307 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00002308 // Note that we do not check for ambiguity or inaccessibility
2309 // here. That is handled by CheckPointerConversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002310 if (getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002311 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00002312 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00002313 IsDerivedFrom(From->getLocStart(), FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002314 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002315 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002316 ToType, Context);
2317 return true;
2318 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002319
Fariborz Jahanianbc2ee932011-04-14 20:33:36 +00002320 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2321 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2322 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2323 ToPointeeType,
2324 ToType, Context);
2325 return true;
2326 }
2327
Douglas Gregora119f102008-12-19 19:13:09 +00002328 return false;
2329}
Douglas Gregoraec25842011-04-26 23:16:46 +00002330
2331/// \brief Adopt the given qualifiers for the given type.
2332static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2333 Qualifiers TQs = T.getQualifiers();
2334
2335 // Check whether qualifiers already match.
2336 if (TQs == Qs)
2337 return T;
2338
2339 if (Qs.compatiblyIncludes(TQs))
2340 return Context.getQualifiedType(T, Qs);
2341
2342 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2343}
Douglas Gregora119f102008-12-19 19:13:09 +00002344
2345/// isObjCPointerConversion - Determines whether this is an
2346/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2347/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00002348bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00002349 QualType& ConvertedType,
2350 bool &IncompatibleObjC) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002351 if (!getLangOpts().ObjC1)
Douglas Gregora119f102008-12-19 19:13:09 +00002352 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002353
Douglas Gregoraec25842011-04-26 23:16:46 +00002354 // The set of qualifiers on the type we're converting from.
2355 Qualifiers FromQualifiers = FromType.getQualifiers();
2356
Steve Naroff7cae42b2009-07-10 23:34:53 +00002357 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00002358 const ObjCObjectPointerType* ToObjCPtr =
2359 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00002360 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00002361 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002362
Steve Naroff7cae42b2009-07-10 23:34:53 +00002363 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002364 // If the pointee types are the same (ignoring qualifications),
2365 // then this is not a pointer conversion.
2366 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2367 FromObjCPtr->getPointeeType()))
2368 return false;
2369
Douglas Gregorab209d82015-07-07 03:58:42 +00002370 // Conversion between Objective-C pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00002371 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002372 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2373 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002374 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002375 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2376 FromObjCPtr->getPointeeType()))
2377 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002378 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002379 ToObjCPtr->getPointeeType(),
2380 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002381 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002382 return true;
2383 }
2384
2385 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2386 // Okay: this is some kind of implicit downcast of Objective-C
2387 // interfaces, which is permitted. However, we're going to
2388 // complain about it.
2389 IncompatibleObjC = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002390 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002391 ToObjCPtr->getPointeeType(),
2392 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002393 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002394 return true;
2395 }
Mike Stump11289f42009-09-09 15:08:12 +00002396 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00002397 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00002398 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002399 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002400 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002401 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002402 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002403 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002404 // to a block pointer type.
2405 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002406 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002407 return true;
2408 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002409 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002410 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002411 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002412 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002413 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002414 // pointer to any object.
Douglas Gregoraec25842011-04-26 23:16:46 +00002415 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002416 return true;
2417 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002418 else
Douglas Gregora119f102008-12-19 19:13:09 +00002419 return false;
2420
Douglas Gregor033f56d2008-12-23 00:53:59 +00002421 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002422 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002423 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00002424 else if (const BlockPointerType *FromBlockPtr =
2425 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00002426 FromPointeeType = FromBlockPtr->getPointeeType();
2427 else
Douglas Gregora119f102008-12-19 19:13:09 +00002428 return false;
2429
Douglas Gregora119f102008-12-19 19:13:09 +00002430 // If we have pointers to pointers, recursively check whether this
2431 // is an Objective-C conversion.
2432 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2433 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2434 IncompatibleObjC)) {
2435 // We always complain about this conversion.
2436 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002437 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002438 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002439 return true;
2440 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002441 // Allow conversion of pointee being objective-c pointer to another one;
2442 // as in I* to id.
2443 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2444 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2445 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2446 IncompatibleObjC)) {
John McCall31168b02011-06-15 23:02:42 +00002447
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002448 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002449 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002450 return true;
2451 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002452
Douglas Gregor033f56d2008-12-23 00:53:59 +00002453 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00002454 // differences in the argument and result types are in Objective-C
2455 // pointer conversions. If so, we permit the conversion (but
2456 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00002457 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002458 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002459 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002460 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002461 if (FromFunctionType && ToFunctionType) {
2462 // If the function types are exactly the same, this isn't an
2463 // Objective-C pointer conversion.
2464 if (Context.getCanonicalType(FromPointeeType)
2465 == Context.getCanonicalType(ToPointeeType))
2466 return false;
2467
2468 // Perform the quick checks that will tell us whether these
2469 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002470 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Douglas Gregora119f102008-12-19 19:13:09 +00002471 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2472 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2473 return false;
2474
2475 bool HasObjCConversion = false;
Alp Toker314cc812014-01-25 16:55:45 +00002476 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2477 Context.getCanonicalType(ToFunctionType->getReturnType())) {
Douglas Gregora119f102008-12-19 19:13:09 +00002478 // Okay, the types match exactly. Nothing to do.
Alp Toker314cc812014-01-25 16:55:45 +00002479 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2480 ToFunctionType->getReturnType(),
Douglas Gregora119f102008-12-19 19:13:09 +00002481 ConvertedType, IncompatibleObjC)) {
2482 // Okay, we have an Objective-C pointer conversion.
2483 HasObjCConversion = true;
2484 } else {
2485 // Function types are too different. Abort.
2486 return false;
2487 }
Mike Stump11289f42009-09-09 15:08:12 +00002488
Douglas Gregora119f102008-12-19 19:13:09 +00002489 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002490 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Douglas Gregora119f102008-12-19 19:13:09 +00002491 ArgIdx != NumArgs; ++ArgIdx) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002492 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2493 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Douglas Gregora119f102008-12-19 19:13:09 +00002494 if (Context.getCanonicalType(FromArgType)
2495 == Context.getCanonicalType(ToArgType)) {
2496 // Okay, the types match exactly. Nothing to do.
2497 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2498 ConvertedType, IncompatibleObjC)) {
2499 // Okay, we have an Objective-C pointer conversion.
2500 HasObjCConversion = true;
2501 } else {
2502 // Argument types are too different. Abort.
2503 return false;
2504 }
2505 }
2506
2507 if (HasObjCConversion) {
2508 // We had an Objective-C conversion. Allow this pointer
2509 // conversion, but complain about it.
Douglas Gregoraec25842011-04-26 23:16:46 +00002510 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002511 IncompatibleObjC = true;
2512 return true;
2513 }
2514 }
2515
Sebastian Redl72b597d2009-01-25 19:43:20 +00002516 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002517}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002518
John McCall31168b02011-06-15 23:02:42 +00002519/// \brief Determine whether this is an Objective-C writeback conversion,
2520/// used for parameter passing when performing automatic reference counting.
2521///
2522/// \param FromType The type we're converting form.
2523///
2524/// \param ToType The type we're converting to.
2525///
2526/// \param ConvertedType The type that will be produced after applying
2527/// this conversion.
2528bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2529 QualType &ConvertedType) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002530 if (!getLangOpts().ObjCAutoRefCount ||
John McCall31168b02011-06-15 23:02:42 +00002531 Context.hasSameUnqualifiedType(FromType, ToType))
2532 return false;
2533
2534 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2535 QualType ToPointee;
2536 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2537 ToPointee = ToPointer->getPointeeType();
2538 else
2539 return false;
2540
2541 Qualifiers ToQuals = ToPointee.getQualifiers();
2542 if (!ToPointee->isObjCLifetimeType() ||
2543 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall18ce25e2012-02-08 00:46:36 +00002544 !ToQuals.withoutObjCLifetime().empty())
John McCall31168b02011-06-15 23:02:42 +00002545 return false;
2546
2547 // Argument must be a pointer to __strong to __weak.
2548 QualType FromPointee;
2549 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2550 FromPointee = FromPointer->getPointeeType();
2551 else
2552 return false;
2553
2554 Qualifiers FromQuals = FromPointee.getQualifiers();
2555 if (!FromPointee->isObjCLifetimeType() ||
2556 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2557 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2558 return false;
2559
2560 // Make sure that we have compatible qualifiers.
2561 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2562 if (!ToQuals.compatiblyIncludes(FromQuals))
2563 return false;
2564
2565 // Remove qualifiers from the pointee type we're converting from; they
2566 // aren't used in the compatibility check belong, and we'll be adding back
2567 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2568 FromPointee = FromPointee.getUnqualifiedType();
2569
2570 // The unqualified form of the pointee types must be compatible.
2571 ToPointee = ToPointee.getUnqualifiedType();
2572 bool IncompatibleObjC;
2573 if (Context.typesAreCompatible(FromPointee, ToPointee))
2574 FromPointee = ToPointee;
2575 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2576 IncompatibleObjC))
2577 return false;
2578
2579 /// \brief Construct the type we're converting to, which is a pointer to
2580 /// __autoreleasing pointee.
2581 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2582 ConvertedType = Context.getPointerType(FromPointee);
2583 return true;
2584}
2585
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002586bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2587 QualType& ConvertedType) {
2588 QualType ToPointeeType;
2589 if (const BlockPointerType *ToBlockPtr =
2590 ToType->getAs<BlockPointerType>())
2591 ToPointeeType = ToBlockPtr->getPointeeType();
2592 else
2593 return false;
2594
2595 QualType FromPointeeType;
2596 if (const BlockPointerType *FromBlockPtr =
2597 FromType->getAs<BlockPointerType>())
2598 FromPointeeType = FromBlockPtr->getPointeeType();
2599 else
2600 return false;
2601 // We have pointer to blocks, check whether the only
2602 // differences in the argument and result types are in Objective-C
2603 // pointer conversions. If so, we permit the conversion.
2604
2605 const FunctionProtoType *FromFunctionType
2606 = FromPointeeType->getAs<FunctionProtoType>();
2607 const FunctionProtoType *ToFunctionType
2608 = ToPointeeType->getAs<FunctionProtoType>();
2609
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002610 if (!FromFunctionType || !ToFunctionType)
2611 return false;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002612
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002613 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002614 return true;
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002615
2616 // Perform the quick checks that will tell us whether these
2617 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002618 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002619 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2620 return false;
2621
2622 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2623 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2624 if (FromEInfo != ToEInfo)
2625 return false;
2626
2627 bool IncompatibleObjC = false;
Alp Toker314cc812014-01-25 16:55:45 +00002628 if (Context.hasSameType(FromFunctionType->getReturnType(),
2629 ToFunctionType->getReturnType())) {
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002630 // Okay, the types match exactly. Nothing to do.
2631 } else {
Alp Toker314cc812014-01-25 16:55:45 +00002632 QualType RHS = FromFunctionType->getReturnType();
2633 QualType LHS = ToFunctionType->getReturnType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002634 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002635 !RHS.hasQualifiers() && LHS.hasQualifiers())
2636 LHS = LHS.getUnqualifiedType();
2637
2638 if (Context.hasSameType(RHS,LHS)) {
2639 // OK exact match.
2640 } else if (isObjCPointerConversion(RHS, LHS,
2641 ConvertedType, IncompatibleObjC)) {
2642 if (IncompatibleObjC)
2643 return false;
2644 // Okay, we have an Objective-C pointer conversion.
2645 }
2646 else
2647 return false;
2648 }
2649
2650 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002651 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002652 ArgIdx != NumArgs; ++ArgIdx) {
2653 IncompatibleObjC = false;
Alp Toker9cacbab2014-01-20 20:26:09 +00002654 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2655 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002656 if (Context.hasSameType(FromArgType, ToArgType)) {
2657 // Okay, the types match exactly. Nothing to do.
2658 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2659 ConvertedType, IncompatibleObjC)) {
2660 if (IncompatibleObjC)
2661 return false;
2662 // Okay, we have an Objective-C pointer conversion.
2663 } else
2664 // Argument types are too different. Abort.
2665 return false;
2666 }
John McCall18afab72016-03-01 00:49:02 +00002667 if (!Context.doFunctionTypesMatchOnExtParameterInfos(FromFunctionType,
2668 ToFunctionType))
Fariborz Jahanian97676972011-09-28 21:52:05 +00002669 return false;
Fariborz Jahanian600ba202011-09-28 20:22:05 +00002670
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002671 ConvertedType = ToType;
2672 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002673}
2674
Richard Trieucaff2472011-11-23 22:32:32 +00002675enum {
2676 ft_default,
2677 ft_different_class,
2678 ft_parameter_arity,
2679 ft_parameter_mismatch,
2680 ft_return_type,
Richard Smith3c4f8d22016-10-16 17:54:23 +00002681 ft_qualifer_mismatch,
2682 ft_noexcept
Richard Trieucaff2472011-11-23 22:32:32 +00002683};
2684
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002685/// Attempts to get the FunctionProtoType from a Type. Handles
2686/// MemberFunctionPointers properly.
2687static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2688 if (auto *FPT = FromType->getAs<FunctionProtoType>())
2689 return FPT;
2690
2691 if (auto *MPT = FromType->getAs<MemberPointerType>())
2692 return MPT->getPointeeType()->getAs<FunctionProtoType>();
2693
2694 return nullptr;
2695}
2696
Richard Trieucaff2472011-11-23 22:32:32 +00002697/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2698/// function types. Catches different number of parameter, mismatch in
2699/// parameter types, and different return types.
2700void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2701 QualType FromType, QualType ToType) {
Richard Trieu96ed5b62011-12-13 23:19:45 +00002702 // If either type is not valid, include no extra info.
2703 if (FromType.isNull() || ToType.isNull()) {
2704 PDiag << ft_default;
2705 return;
2706 }
2707
Richard Trieucaff2472011-11-23 22:32:32 +00002708 // Get the function type from the pointers.
2709 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2710 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2711 *ToMember = ToType->getAs<MemberPointerType>();
Richard Trieu9098c9f2014-05-22 01:39:16 +00002712 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
Richard Trieucaff2472011-11-23 22:32:32 +00002713 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2714 << QualType(FromMember->getClass(), 0);
2715 return;
2716 }
2717 FromType = FromMember->getPointeeType();
2718 ToType = ToMember->getPointeeType();
Richard Trieucaff2472011-11-23 22:32:32 +00002719 }
2720
Richard Trieu96ed5b62011-12-13 23:19:45 +00002721 if (FromType->isPointerType())
2722 FromType = FromType->getPointeeType();
2723 if (ToType->isPointerType())
2724 ToType = ToType->getPointeeType();
2725
2726 // Remove references.
Richard Trieucaff2472011-11-23 22:32:32 +00002727 FromType = FromType.getNonReferenceType();
2728 ToType = ToType.getNonReferenceType();
2729
Richard Trieucaff2472011-11-23 22:32:32 +00002730 // Don't print extra info for non-specialized template functions.
2731 if (FromType->isInstantiationDependentType() &&
2732 !FromType->getAs<TemplateSpecializationType>()) {
2733 PDiag << ft_default;
2734 return;
2735 }
2736
Richard Trieu96ed5b62011-12-13 23:19:45 +00002737 // No extra info for same types.
2738 if (Context.hasSameType(FromType, ToType)) {
2739 PDiag << ft_default;
2740 return;
2741 }
2742
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002743 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2744 *ToFunction = tryGetFunctionProtoType(ToType);
Richard Trieucaff2472011-11-23 22:32:32 +00002745
2746 // Both types need to be function types.
2747 if (!FromFunction || !ToFunction) {
2748 PDiag << ft_default;
2749 return;
2750 }
2751
Alp Toker9cacbab2014-01-20 20:26:09 +00002752 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2753 PDiag << ft_parameter_arity << ToFunction->getNumParams()
2754 << FromFunction->getNumParams();
Richard Trieucaff2472011-11-23 22:32:32 +00002755 return;
2756 }
2757
2758 // Handle different parameter types.
2759 unsigned ArgPos;
Alp Toker9cacbab2014-01-20 20:26:09 +00002760 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
Richard Trieucaff2472011-11-23 22:32:32 +00002761 PDiag << ft_parameter_mismatch << ArgPos + 1
Alp Toker9cacbab2014-01-20 20:26:09 +00002762 << ToFunction->getParamType(ArgPos)
2763 << FromFunction->getParamType(ArgPos);
Richard Trieucaff2472011-11-23 22:32:32 +00002764 return;
2765 }
2766
2767 // Handle different return type.
Alp Toker314cc812014-01-25 16:55:45 +00002768 if (!Context.hasSameType(FromFunction->getReturnType(),
2769 ToFunction->getReturnType())) {
2770 PDiag << ft_return_type << ToFunction->getReturnType()
2771 << FromFunction->getReturnType();
Richard Trieucaff2472011-11-23 22:32:32 +00002772 return;
2773 }
2774
2775 unsigned FromQuals = FromFunction->getTypeQuals(),
2776 ToQuals = ToFunction->getTypeQuals();
2777 if (FromQuals != ToQuals) {
2778 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2779 return;
2780 }
2781
Richard Smith3c4f8d22016-10-16 17:54:23 +00002782 // Handle exception specification differences on canonical type (in C++17
2783 // onwards).
2784 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2785 ->isNothrow(Context) !=
2786 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2787 ->isNothrow(Context)) {
2788 PDiag << ft_noexcept;
2789 return;
2790 }
2791
Richard Trieucaff2472011-11-23 22:32:32 +00002792 // Unable to find a difference, so add no extra info.
2793 PDiag << ft_default;
2794}
2795
Alp Toker9cacbab2014-01-20 20:26:09 +00002796/// FunctionParamTypesAreEqual - This routine checks two function proto types
Douglas Gregor2039ca02011-12-15 17:15:07 +00002797/// for equality of their argument types. Caller has already checked that
Eli Friedman5f508952013-06-18 22:41:37 +00002798/// they have same number of arguments. If the parameters are different,
2799/// ArgPos will have the parameter index of the first different parameter.
Alp Toker9cacbab2014-01-20 20:26:09 +00002800bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2801 const FunctionProtoType *NewType,
2802 unsigned *ArgPos) {
2803 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2804 N = NewType->param_type_begin(),
2805 E = OldType->param_type_end();
2806 O && (O != E); ++O, ++N) {
Richard Trieu4b03d982013-08-09 21:42:32 +00002807 if (!Context.hasSameType(O->getUnqualifiedType(),
2808 N->getUnqualifiedType())) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002809 if (ArgPos)
2810 *ArgPos = O - OldType->param_type_begin();
Larisse Voufo4154f462013-08-06 03:57:41 +00002811 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002812 }
2813 }
2814 return true;
2815}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002816
Douglas Gregor39c16d42008-10-24 04:54:22 +00002817/// CheckPointerConversion - Check the pointer conversion from the
2818/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00002819/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00002820/// conversions for which IsPointerConversion has already returned
2821/// true. It returns true and produces a diagnostic if there was an
2822/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002823bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002824 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002825 CXXCastPath& BasePath,
George Burgess IV60bc9722016-01-13 23:36:34 +00002826 bool IgnoreBaseAccess,
2827 bool Diagnose) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002828 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00002829 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002830
John McCall8cb679e2010-11-15 09:13:47 +00002831 Kind = CK_BitCast;
2832
George Burgess IV60bc9722016-01-13 23:36:34 +00002833 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
Argyrios Kyrtzidis3e3305d2014-02-02 05:26:43 +00002834 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
George Burgess IV60bc9722016-01-13 23:36:34 +00002835 Expr::NPCK_ZeroExpression) {
David Blaikie1c7c8f72012-08-08 17:33:31 +00002836 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2837 DiagRuntimeBehavior(From->getExprLoc(), From,
2838 PDiag(diag::warn_impcast_bool_to_null_pointer)
2839 << ToType << From->getSourceRange());
2840 else if (!isUnevaluatedContext())
2841 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2842 << ToType << From->getSourceRange();
2843 }
John McCall9320b872011-09-09 05:25:32 +00002844 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2845 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002846 QualType FromPointeeType = FromPtrType->getPointeeType(),
2847 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00002848
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002849 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2850 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002851 // We must have a derived-to-base conversion. Check an
2852 // ambiguous or inaccessible conversion.
George Burgess IV60bc9722016-01-13 23:36:34 +00002853 unsigned InaccessibleID = 0;
2854 unsigned AmbigiousID = 0;
2855 if (Diagnose) {
2856 InaccessibleID = diag::err_upcast_to_inaccessible_base;
2857 AmbigiousID = diag::err_ambiguous_derived_to_base_conv;
2858 }
2859 if (CheckDerivedToBaseConversion(
2860 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID,
2861 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
2862 &BasePath, IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002863 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002864
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002865 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00002866 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002867 }
David Majnemer6bf02822015-10-31 08:42:14 +00002868
George Burgess IV60bc9722016-01-13 23:36:34 +00002869 if (Diagnose && !IsCStyleOrFunctionalCast &&
2870 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
David Majnemer6bf02822015-10-31 08:42:14 +00002871 assert(getLangOpts().MSVCCompat &&
2872 "this should only be possible with MSVCCompat!");
2873 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
2874 << From->getSourceRange();
2875 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00002876 }
John McCall9320b872011-09-09 05:25:32 +00002877 } else if (const ObjCObjectPointerType *ToPtrType =
2878 ToType->getAs<ObjCObjectPointerType>()) {
2879 if (const ObjCObjectPointerType *FromPtrType =
2880 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002881 // Objective-C++ conversions are always okay.
2882 // FIXME: We should have a different class of conversions for the
2883 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00002884 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002885 return false;
John McCall9320b872011-09-09 05:25:32 +00002886 } else if (FromType->isBlockPointerType()) {
2887 Kind = CK_BlockPointerToObjCPointerCast;
2888 } else {
2889 Kind = CK_CPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00002890 }
John McCall9320b872011-09-09 05:25:32 +00002891 } else if (ToType->isBlockPointerType()) {
2892 if (!FromType->isBlockPointerType())
2893 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002894 }
John McCall8cb679e2010-11-15 09:13:47 +00002895
2896 // We shouldn't fall into this case unless it's valid for other
2897 // reasons.
2898 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2899 Kind = CK_NullToPointer;
2900
Douglas Gregor39c16d42008-10-24 04:54:22 +00002901 return false;
2902}
2903
Sebastian Redl72b597d2009-01-25 19:43:20 +00002904/// IsMemberPointerConversion - Determines whether the conversion of the
2905/// expression From, which has the (possibly adjusted) type FromType, can be
2906/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2907/// If so, returns true and places the converted type (that might differ from
2908/// ToType in its cv-qualifiers at some level) into ConvertedType.
2909bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002910 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00002911 bool InOverloadResolution,
2912 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002913 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002914 if (!ToTypePtr)
2915 return false;
2916
2917 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00002918 if (From->isNullPointerConstant(Context,
2919 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2920 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002921 ConvertedType = ToType;
2922 return true;
2923 }
2924
2925 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002926 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002927 if (!FromTypePtr)
2928 return false;
2929
2930 // A pointer to member of B can be converted to a pointer to member of D,
2931 // where D is derived from B (C++ 4.11p2).
2932 QualType FromClass(FromTypePtr->getClass(), 0);
2933 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002934
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002935 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00002936 IsDerivedFrom(From->getLocStart(), ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002937 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2938 ToClass.getTypePtr());
2939 return true;
2940 }
2941
2942 return false;
2943}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002944
Sebastian Redl72b597d2009-01-25 19:43:20 +00002945/// CheckMemberPointerConversion - Check the member pointer conversion from the
2946/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002947/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002948/// for which IsMemberPointerConversion has already returned true. It returns
2949/// true and produces a diagnostic if there was an error, or returns false
2950/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002951bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002952 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002953 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002954 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002955 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002956 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00002957 if (!FromPtrType) {
2958 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002959 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00002960 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00002961 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00002962 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00002963 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00002964 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00002965
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002966 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00002967 assert(ToPtrType && "No member pointer cast has a target type "
2968 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002969
Sebastian Redled8f2002009-01-28 18:33:18 +00002970 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2971 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002972
Sebastian Redled8f2002009-01-28 18:33:18 +00002973 // FIXME: What about dependent types?
2974 assert(FromClass->isRecordType() && "Pointer into non-class.");
2975 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002976
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002977 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002978 /*DetectVirtual=*/true);
Richard Smith0f59cb32015-12-18 21:45:41 +00002979 bool DerivationOkay =
2980 IsDerivedFrom(From->getLocStart(), ToClass, FromClass, Paths);
Sebastian Redled8f2002009-01-28 18:33:18 +00002981 assert(DerivationOkay &&
2982 "Should not have been called if derivation isn't OK.");
2983 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002984
Sebastian Redled8f2002009-01-28 18:33:18 +00002985 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2986 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002987 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2988 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2989 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2990 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002991 }
Sebastian Redled8f2002009-01-28 18:33:18 +00002992
Douglas Gregor89ee6822009-02-28 01:32:25 +00002993 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002994 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2995 << FromClass << ToClass << QualType(VBase, 0)
2996 << From->getSourceRange();
2997 return true;
2998 }
2999
John McCall5b0829a2010-02-10 09:31:12 +00003000 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00003001 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3002 Paths.front(),
3003 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00003004
Anders Carlssond7923c62009-08-22 23:33:40 +00003005 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00003006 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00003007 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00003008 return false;
3009}
3010
Douglas Gregorc9f019a2013-11-08 02:04:24 +00003011/// Determine whether the lifetime conversion between the two given
3012/// qualifiers sets is nontrivial.
3013static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3014 Qualifiers ToQuals) {
3015 // Converting anything to const __unsafe_unretained is trivial.
3016 if (ToQuals.hasConst() &&
3017 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3018 return false;
3019
3020 return true;
3021}
3022
Douglas Gregor9a657932008-10-21 23:43:52 +00003023/// IsQualificationConversion - Determines whether the conversion from
3024/// an rvalue of type FromType to ToType is a qualification conversion
3025/// (C++ 4.4).
John McCall31168b02011-06-15 23:02:42 +00003026///
3027/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3028/// when the qualification conversion involves a change in the Objective-C
3029/// object lifetime.
Mike Stump11289f42009-09-09 15:08:12 +00003030bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003031Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00003032 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor9a657932008-10-21 23:43:52 +00003033 FromType = Context.getCanonicalType(FromType);
3034 ToType = Context.getCanonicalType(ToType);
John McCall31168b02011-06-15 23:02:42 +00003035 ObjCLifetimeConversion = false;
3036
Douglas Gregor9a657932008-10-21 23:43:52 +00003037 // If FromType and ToType are the same type, this is not a
3038 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00003039 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00003040 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00003041
Douglas Gregor9a657932008-10-21 23:43:52 +00003042 // (C++ 4.4p4):
3043 // A conversion can add cv-qualifiers at levels other than the first
3044 // in multi-level pointers, subject to the following rules: [...]
3045 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00003046 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003047 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00003048 // Within each iteration of the loop, we check the qualifiers to
3049 // determine if this still looks like a qualification
3050 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003051 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00003052 // until there are no more pointers or pointers-to-members left to
3053 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003054 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00003055
Douglas Gregor90609aa2011-04-25 18:40:17 +00003056 Qualifiers FromQuals = FromType.getQualifiers();
3057 Qualifiers ToQuals = ToType.getQualifiers();
Andrey Bokhanko45d41322016-05-11 18:38:21 +00003058
3059 // Ignore __unaligned qualifier if this type is void.
3060 if (ToType.getUnqualifiedType()->isVoidType())
3061 FromQuals.removeUnaligned();
Douglas Gregor90609aa2011-04-25 18:40:17 +00003062
John McCall31168b02011-06-15 23:02:42 +00003063 // Objective-C ARC:
3064 // Check Objective-C lifetime conversions.
3065 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
3066 UnwrappedAnyPointer) {
3067 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00003068 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3069 ObjCLifetimeConversion = true;
John McCall31168b02011-06-15 23:02:42 +00003070 FromQuals.removeObjCLifetime();
3071 ToQuals.removeObjCLifetime();
3072 } else {
3073 // Qualification conversions cannot cast between different
3074 // Objective-C lifetime qualifiers.
3075 return false;
3076 }
3077 }
3078
Douglas Gregorf30053d2011-05-08 06:09:53 +00003079 // Allow addition/removal of GC attributes but not changing GC attributes.
3080 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3081 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3082 FromQuals.removeObjCGCAttr();
3083 ToQuals.removeObjCGCAttr();
3084 }
3085
Douglas Gregor9a657932008-10-21 23:43:52 +00003086 // -- for every j > 0, if const is in cv 1,j then const is in cv
3087 // 2,j, and similarly for volatile.
Douglas Gregor90609aa2011-04-25 18:40:17 +00003088 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor9a657932008-10-21 23:43:52 +00003089 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003090
Douglas Gregor9a657932008-10-21 23:43:52 +00003091 // -- if the cv 1,j and cv 2,j are different, then const is in
3092 // every cv for 0 < k < j.
Douglas Gregor90609aa2011-04-25 18:40:17 +00003093 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003094 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00003095 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003096
Douglas Gregor9a657932008-10-21 23:43:52 +00003097 // Keep track of whether all prior cv-qualifiers in the "to" type
3098 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00003099 PreviousToQualsIncludeConst
Douglas Gregor90609aa2011-04-25 18:40:17 +00003100 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003101 }
Douglas Gregor9a657932008-10-21 23:43:52 +00003102
3103 // We are left with FromType and ToType being the pointee types
3104 // after unwrapping the original FromType and ToType the same number
3105 // of types. If we unwrapped any pointers, and if FromType and
3106 // ToType have the same unqualified type (since we checked
3107 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003108 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00003109}
3110
Douglas Gregorc79862f2012-04-12 17:51:55 +00003111/// \brief - Determine whether this is a conversion from a scalar type to an
3112/// atomic type.
3113///
3114/// If successful, updates \c SCS's second and third steps in the conversion
3115/// sequence to finish the conversion.
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00003116static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3117 bool InOverloadResolution,
3118 StandardConversionSequence &SCS,
3119 bool CStyle) {
Douglas Gregorc79862f2012-04-12 17:51:55 +00003120 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3121 if (!ToAtomic)
3122 return false;
3123
3124 StandardConversionSequence InnerSCS;
3125 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3126 InOverloadResolution, InnerSCS,
3127 CStyle, /*AllowObjCWritebackConversion=*/false))
3128 return false;
3129
3130 SCS.Second = InnerSCS.Second;
3131 SCS.setToType(1, InnerSCS.getToType(1));
3132 SCS.Third = InnerSCS.Third;
3133 SCS.QualificationIncludesObjCLifetime
3134 = InnerSCS.QualificationIncludesObjCLifetime;
3135 SCS.setToType(2, InnerSCS.getToType(2));
3136 return true;
3137}
3138
Sebastian Redle5417162012-03-27 18:33:03 +00003139static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3140 CXXConstructorDecl *Constructor,
3141 QualType Type) {
3142 const FunctionProtoType *CtorType =
3143 Constructor->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00003144 if (CtorType->getNumParams() > 0) {
3145 QualType FirstArg = CtorType->getParamType(0);
Sebastian Redle5417162012-03-27 18:33:03 +00003146 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3147 return true;
3148 }
3149 return false;
3150}
3151
Sebastian Redl82ace982012-02-11 23:51:08 +00003152static OverloadingResult
3153IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3154 CXXRecordDecl *To,
3155 UserDefinedConversionSequence &User,
3156 OverloadCandidateSet &CandidateSet,
3157 bool AllowExplicit) {
Richard Smithc2bebe92016-05-11 20:37:46 +00003158 for (auto *D : S.LookupConstructors(To)) {
3159 auto Info = getConstructorInfo(D);
Richard Smith5179eb72016-06-28 19:03:57 +00003160 if (!Info)
Richard Smithc2bebe92016-05-11 20:37:46 +00003161 continue;
Sebastian Redl82ace982012-02-11 23:51:08 +00003162
Richard Smithc2bebe92016-05-11 20:37:46 +00003163 bool Usable = !Info.Constructor->isInvalidDecl() &&
3164 S.isInitListConstructor(Info.Constructor) &&
3165 (AllowExplicit || !Info.Constructor->isExplicit());
Sebastian Redl82ace982012-02-11 23:51:08 +00003166 if (Usable) {
Sebastian Redle5417162012-03-27 18:33:03 +00003167 // If the first argument is (a reference to) the target type,
3168 // suppress conversions.
Richard Smithc2bebe92016-05-11 20:37:46 +00003169 bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3170 S.Context, Info.Constructor, ToType);
3171 if (Info.ConstructorTmpl)
3172 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3173 /*ExplicitArgs*/ nullptr, From,
3174 CandidateSet, SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00003175 else
Richard Smithc2bebe92016-05-11 20:37:46 +00003176 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3177 CandidateSet, SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00003178 }
3179 }
3180
3181 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3182
3183 OverloadCandidateSet::iterator Best;
Fariborz Jahaniandcf06f42015-04-14 17:21:58 +00003184 switch (auto Result =
3185 CandidateSet.BestViableFunction(S, From->getLocStart(),
3186 Best, true)) {
3187 case OR_Deleted:
Sebastian Redl82ace982012-02-11 23:51:08 +00003188 case OR_Success: {
3189 // Record the standard conversion we used and the conversion function.
3190 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Sebastian Redl82ace982012-02-11 23:51:08 +00003191 QualType ThisType = Constructor->getThisType(S.Context);
3192 // Initializer lists don't have conversions as such.
3193 User.Before.setAsIdentityConversion();
3194 User.HadMultipleCandidates = HadMultipleCandidates;
3195 User.ConversionFunction = Constructor;
3196 User.FoundConversionFunction = Best->FoundDecl;
3197 User.After.setAsIdentityConversion();
3198 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3199 User.After.setAllToTypes(ToType);
Fariborz Jahaniandcf06f42015-04-14 17:21:58 +00003200 return Result;
Sebastian Redl82ace982012-02-11 23:51:08 +00003201 }
3202
3203 case OR_No_Viable_Function:
3204 return OR_No_Viable_Function;
Sebastian Redl82ace982012-02-11 23:51:08 +00003205 case OR_Ambiguous:
3206 return OR_Ambiguous;
3207 }
3208
3209 llvm_unreachable("Invalid OverloadResult!");
3210}
3211
Douglas Gregor576e98c2009-01-30 23:27:23 +00003212/// Determines whether there is a user-defined conversion sequence
3213/// (C++ [over.ics.user]) that converts expression From to the type
3214/// ToType. If such a conversion exists, User will contain the
3215/// user-defined conversion sequence that performs such a conversion
3216/// and this routine will return true. Otherwise, this routine returns
3217/// false and User is unspecified.
3218///
Douglas Gregor576e98c2009-01-30 23:27:23 +00003219/// \param AllowExplicit true if the conversion should consider C++0x
3220/// "explicit" conversion functions as well as non-explicit conversion
3221/// functions (C++0x [class.conv.fct]p2).
Douglas Gregor4b60a152013-11-07 22:34:54 +00003222///
3223/// \param AllowObjCConversionOnExplicit true if the conversion should
3224/// allow an extra Objective-C pointer conversion on uses of explicit
3225/// constructors. Requires \c AllowExplicit to also be set.
John McCall5c32be02010-08-24 20:38:10 +00003226static OverloadingResult
3227IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl82ace982012-02-11 23:51:08 +00003228 UserDefinedConversionSequence &User,
3229 OverloadCandidateSet &CandidateSet,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003230 bool AllowExplicit,
3231 bool AllowObjCConversionOnExplicit) {
Douglas Gregor2ee1d992013-11-08 01:20:25 +00003232 assert(AllowExplicit || !AllowObjCConversionOnExplicit);
Douglas Gregor4b60a152013-11-07 22:34:54 +00003233
Douglas Gregor5ab11652010-04-17 22:01:05 +00003234 // Whether we will only visit constructors.
3235 bool ConstructorsOnly = false;
3236
3237 // If the type we are conversion to is a class type, enumerate its
3238 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003239 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00003240 // C++ [over.match.ctor]p1:
3241 // When objects of class type are direct-initialized (8.5), or
3242 // copy-initialized from an expression of the same or a
3243 // derived class type (8.5), overload resolution selects the
3244 // constructor. [...] For copy-initialization, the candidate
3245 // functions are all the converting constructors (12.3.1) of
3246 // that class. The argument list is the expression-list within
3247 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00003248 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00003249 (From->getType()->getAs<RecordType>() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00003250 S.IsDerivedFrom(From->getLocStart(), From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00003251 ConstructorsOnly = true;
3252
Richard Smithdb0ac552015-12-18 22:40:25 +00003253 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003254 // We're not going to find any constructors.
3255 } else if (CXXRecordDecl *ToRecordDecl
3256 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003257
3258 Expr **Args = &From;
3259 unsigned NumArgs = 1;
3260 bool ListInitializing = false;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003261 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003262 // But first, see if there is an init-list-constructor that will work.
Sebastian Redl82ace982012-02-11 23:51:08 +00003263 OverloadingResult Result = IsInitializerListConstructorConversion(
3264 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3265 if (Result != OR_No_Viable_Function)
3266 return Result;
3267 // Never mind.
3268 CandidateSet.clear();
3269
3270 // If we're list-initializing, we pass the individual elements as
3271 // arguments, not the entire list.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003272 Args = InitList->getInits();
3273 NumArgs = InitList->getNumInits();
3274 ListInitializing = true;
3275 }
3276
Richard Smithc2bebe92016-05-11 20:37:46 +00003277 for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3278 auto Info = getConstructorInfo(D);
Richard Smith5179eb72016-06-28 19:03:57 +00003279 if (!Info)
Richard Smithc2bebe92016-05-11 20:37:46 +00003280 continue;
John McCalla0296f72010-03-19 07:35:19 +00003281
Richard Smithc2bebe92016-05-11 20:37:46 +00003282 bool Usable = !Info.Constructor->isInvalidDecl();
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003283 if (ListInitializing)
Richard Smithc2bebe92016-05-11 20:37:46 +00003284 Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit());
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003285 else
Richard Smithc2bebe92016-05-11 20:37:46 +00003286 Usable = Usable &&
3287 Info.Constructor->isConvertingConstructor(AllowExplicit);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003288 if (Usable) {
Sebastian Redld9170b02012-03-20 21:24:14 +00003289 bool SuppressUserConversions = !ConstructorsOnly;
3290 if (SuppressUserConversions && ListInitializing) {
3291 SuppressUserConversions = false;
3292 if (NumArgs == 1) {
3293 // If the first argument is (a reference to) the target type,
3294 // suppress conversions.
Sebastian Redle5417162012-03-27 18:33:03 +00003295 SuppressUserConversions = isFirstArgumentCompatibleWithType(
Richard Smithc2bebe92016-05-11 20:37:46 +00003296 S.Context, Info.Constructor, ToType);
Sebastian Redld9170b02012-03-20 21:24:14 +00003297 }
3298 }
Richard Smithc2bebe92016-05-11 20:37:46 +00003299 if (Info.ConstructorTmpl)
3300 S.AddTemplateOverloadCandidate(
3301 Info.ConstructorTmpl, Info.FoundDecl,
3302 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3303 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003304 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00003305 // Allow one user-defined conversion when user specifies a
3306 // From->ToType conversion via an static cast (c-style, etc).
Richard Smithc2bebe92016-05-11 20:37:46 +00003307 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003308 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003309 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003310 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00003311 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003312 }
3313 }
3314
Douglas Gregor5ab11652010-04-17 22:01:05 +00003315 // Enumerate conversion functions, if we're allowed to.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003316 if (ConstructorsOnly || isa<InitListExpr>(From)) {
Richard Smithdb0ac552015-12-18 22:40:25 +00003317 } else if (!S.isCompleteType(From->getLocStart(), From->getType())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003318 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00003319 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00003320 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00003321 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003322 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3323 // Add all of the conversion functions as candidates.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00003324 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3325 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00003326 DeclAccessPair FoundDecl = I.getPair();
3327 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003328 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3329 if (isa<UsingShadowDecl>(D))
3330 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3331
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003332 CXXConversionDecl *Conv;
3333 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00003334 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3335 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003336 else
John McCallda4458e2010-03-31 01:36:47 +00003337 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003338
3339 if (AllowExplicit || !Conv->isExplicit()) {
3340 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00003341 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3342 ActingContext, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003343 CandidateSet,
3344 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003345 else
John McCall5c32be02010-08-24 20:38:10 +00003346 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003347 From, ToType, CandidateSet,
3348 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003349 }
3350 }
3351 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00003352 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003353
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003354 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3355
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003356 OverloadCandidateSet::iterator Best;
Richard Smith48372b62015-01-27 03:30:40 +00003357 switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(),
3358 Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00003359 case OR_Success:
Richard Smith48372b62015-01-27 03:30:40 +00003360 case OR_Deleted:
John McCall5c32be02010-08-24 20:38:10 +00003361 // Record the standard conversion we used and the conversion function.
3362 if (CXXConstructorDecl *Constructor
3363 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3364 // C++ [over.ics.user]p1:
3365 // If the user-defined conversion is specified by a
3366 // constructor (12.3.1), the initial standard conversion
3367 // sequence converts the source type to the type required by
3368 // the argument of the constructor.
3369 //
3370 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003371 if (isa<InitListExpr>(From)) {
3372 // Initializer lists don't have conversions as such.
3373 User.Before.setAsIdentityConversion();
3374 } else {
3375 if (Best->Conversions[0].isEllipsis())
3376 User.EllipsisConversion = true;
3377 else {
3378 User.Before = Best->Conversions[0].Standard;
3379 User.EllipsisConversion = false;
3380 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003381 }
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003382 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003383 User.ConversionFunction = Constructor;
John McCall30909032011-09-21 08:36:56 +00003384 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003385 User.After.setAsIdentityConversion();
3386 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3387 User.After.setAllToTypes(ToType);
Richard Smith48372b62015-01-27 03:30:40 +00003388 return Result;
David Blaikie8a40f702012-01-17 06:56:22 +00003389 }
3390 if (CXXConversionDecl *Conversion
John McCall5c32be02010-08-24 20:38:10 +00003391 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3392 // C++ [over.ics.user]p1:
3393 //
3394 // [...] If the user-defined conversion is specified by a
3395 // conversion function (12.3.2), the initial standard
3396 // conversion sequence converts the source type to the
3397 // implicit object parameter of the conversion function.
3398 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003399 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003400 User.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00003401 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003402 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00003403
John McCall5c32be02010-08-24 20:38:10 +00003404 // C++ [over.ics.user]p2:
3405 // The second standard conversion sequence converts the
3406 // result of the user-defined conversion to the target type
3407 // for the sequence. Since an implicit conversion sequence
3408 // is an initialization, the special rules for
3409 // initialization by user-defined conversion apply when
3410 // selecting the best user-defined conversion for a
3411 // user-defined conversion sequence (see 13.3.3 and
3412 // 13.3.3.1).
3413 User.After = Best->FinalConversion;
Richard Smith48372b62015-01-27 03:30:40 +00003414 return Result;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003415 }
David Blaikie8a40f702012-01-17 06:56:22 +00003416 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003417
John McCall5c32be02010-08-24 20:38:10 +00003418 case OR_No_Viable_Function:
3419 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003420
John McCall5c32be02010-08-24 20:38:10 +00003421 case OR_Ambiguous:
3422 return OR_Ambiguous;
3423 }
3424
David Blaikie8a40f702012-01-17 06:56:22 +00003425 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003426}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003427
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003428bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00003429Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003430 ImplicitConversionSequence ICS;
Richard Smith100b24a2014-04-17 01:52:14 +00003431 OverloadCandidateSet CandidateSet(From->getExprLoc(),
3432 OverloadCandidateSet::CSK_Normal);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003433 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00003434 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003435 CandidateSet, false, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00003436 if (OvResult == OR_Ambiguous)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003437 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3438 << From->getType() << ToType << From->getSourceRange();
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003439 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
Larisse Voufo70bb43a2013-06-27 03:36:30 +00003440 if (!RequireCompleteType(From->getLocStart(), ToType,
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003441 diag::err_typecheck_nonviable_condition_incomplete,
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003442 From->getType(), From->getSourceRange()))
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003443 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
Nick Lewycky08426e22015-08-25 22:18:46 +00003444 << false << From->getType() << From->getSourceRange() << ToType;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003445 } else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003446 return false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003447 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003448 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003449}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003450
Douglas Gregor2837aa22012-02-22 17:32:19 +00003451/// \brief Compare the user-defined conversion functions or constructors
3452/// of two user-defined conversion sequences to determine whether any ordering
3453/// is possible.
3454static ImplicitConversionSequence::CompareKind
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003455compareConversionFunctions(Sema &S, FunctionDecl *Function1,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003456 FunctionDecl *Function2) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003457 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
Douglas Gregor2837aa22012-02-22 17:32:19 +00003458 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003459
Douglas Gregor2837aa22012-02-22 17:32:19 +00003460 // Objective-C++:
3461 // If both conversion functions are implicitly-declared conversions from
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003462 // a lambda closure type to a function pointer and a block pointer,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003463 // respectively, always prefer the conversion to a function pointer,
3464 // because the function pointer is more lightweight and is more likely
3465 // to keep code working.
Ted Kremenek8d265c22014-04-01 07:23:18 +00003466 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003467 if (!Conv1)
3468 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003469
Douglas Gregor2837aa22012-02-22 17:32:19 +00003470 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3471 if (!Conv2)
3472 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003473
Douglas Gregor2837aa22012-02-22 17:32:19 +00003474 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3475 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3476 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3477 if (Block1 != Block2)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003478 return Block1 ? ImplicitConversionSequence::Worse
3479 : ImplicitConversionSequence::Better;
Douglas Gregor2837aa22012-02-22 17:32:19 +00003480 }
3481
3482 return ImplicitConversionSequence::Indistinguishable;
3483}
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003484
3485static bool hasDeprecatedStringLiteralToCharPtrConversion(
3486 const ImplicitConversionSequence &ICS) {
3487 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3488 (ICS.isUserDefined() &&
3489 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3490}
3491
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003492/// CompareImplicitConversionSequences - Compare two implicit
3493/// conversion sequences to determine whether one is better than the
3494/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00003495static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +00003496CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +00003497 const ImplicitConversionSequence& ICS1,
3498 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003499{
3500 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3501 // conversion sequences (as defined in 13.3.3.1)
3502 // -- a standard conversion sequence (13.3.3.1.1) is a better
3503 // conversion sequence than a user-defined conversion sequence or
3504 // an ellipsis conversion sequence, and
3505 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3506 // conversion sequence than an ellipsis conversion sequence
3507 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00003508 //
John McCall0d1da222010-01-12 00:44:57 +00003509 // C++0x [over.best.ics]p10:
3510 // For the purpose of ranking implicit conversion sequences as
3511 // described in 13.3.3.2, the ambiguous conversion sequence is
3512 // treated as a user-defined sequence that is indistinguishable
3513 // from any other user-defined conversion sequence.
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003514
3515 // String literal to 'char *' conversion has been deprecated in C++03. It has
3516 // been removed from C++11. We still accept this conversion, if it happens at
3517 // the best viable function. Otherwise, this conversion is considered worse
3518 // than ellipsis conversion. Consider this as an extension; this is not in the
3519 // standard. For example:
3520 //
3521 // int &f(...); // #1
3522 // void f(char*); // #2
3523 // void g() { int &r = f("foo"); }
3524 //
3525 // In C++03, we pick #2 as the best viable function.
3526 // In C++11, we pick #1 as the best viable function, because ellipsis
3527 // conversion is better than string-literal to char* conversion (since there
3528 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3529 // convert arguments, #2 would be the best viable function in C++11.
3530 // If the best viable function has this conversion, a warning will be issued
3531 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3532
3533 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3534 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3535 hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3536 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3537 ? ImplicitConversionSequence::Worse
3538 : ImplicitConversionSequence::Better;
3539
Douglas Gregor5ab11652010-04-17 22:01:05 +00003540 if (ICS1.getKindRank() < ICS2.getKindRank())
3541 return ImplicitConversionSequence::Better;
David Blaikie8a40f702012-01-17 06:56:22 +00003542 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor5ab11652010-04-17 22:01:05 +00003543 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003544
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00003545 // The following checks require both conversion sequences to be of
3546 // the same kind.
3547 if (ICS1.getKind() != ICS2.getKind())
3548 return ImplicitConversionSequence::Indistinguishable;
3549
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003550 ImplicitConversionSequence::CompareKind Result =
3551 ImplicitConversionSequence::Indistinguishable;
3552
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003553 // Two implicit conversion sequences of the same form are
3554 // indistinguishable conversion sequences unless one of the
3555 // following rules apply: (C++ 13.3.3.2p3):
Larisse Voufo19d08672015-01-27 18:47:05 +00003556
3557 // List-initialization sequence L1 is a better conversion sequence than
3558 // list-initialization sequence L2 if:
3559 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3560 // if not that,
NAKAMURA Takumib01d86b2015-02-25 11:02:00 +00003561 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
Larisse Voufo19d08672015-01-27 18:47:05 +00003562 // and N1 is smaller than N2.,
3563 // even if one of the other rules in this paragraph would otherwise apply.
3564 if (!ICS1.isBad()) {
3565 if (ICS1.isStdInitializerListElement() &&
3566 !ICS2.isStdInitializerListElement())
3567 return ImplicitConversionSequence::Better;
3568 if (!ICS1.isStdInitializerListElement() &&
3569 ICS2.isStdInitializerListElement())
3570 return ImplicitConversionSequence::Worse;
3571 }
3572
John McCall0d1da222010-01-12 00:44:57 +00003573 if (ICS1.isStandard())
Larisse Voufo19d08672015-01-27 18:47:05 +00003574 // Standard conversion sequence S1 is a better conversion sequence than
3575 // standard conversion sequence S2 if [...]
Richard Smith0f59cb32015-12-18 21:45:41 +00003576 Result = CompareStandardConversionSequences(S, Loc,
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003577 ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00003578 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003579 // User-defined conversion sequence U1 is a better conversion
3580 // sequence than another user-defined conversion sequence U2 if
3581 // they contain the same user-defined conversion function or
3582 // constructor and if the second standard conversion sequence of
3583 // U1 is better than the second standard conversion sequence of
3584 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00003585 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003586 ICS2.UserDefined.ConversionFunction)
Richard Smith0f59cb32015-12-18 21:45:41 +00003587 Result = CompareStandardConversionSequences(S, Loc,
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003588 ICS1.UserDefined.After,
3589 ICS2.UserDefined.After);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003590 else
3591 Result = compareConversionFunctions(S,
3592 ICS1.UserDefined.ConversionFunction,
3593 ICS2.UserDefined.ConversionFunction);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003594 }
3595
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003596 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003597}
3598
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003599static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3600 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3601 Qualifiers Quals;
3602 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003603 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003604 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003605
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003606 return Context.hasSameUnqualifiedType(T1, T2);
3607}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003608
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003609// Per 13.3.3.2p3, compare the given standard conversion sequences to
3610// determine if one is a proper subset of the other.
3611static ImplicitConversionSequence::CompareKind
3612compareStandardConversionSubsets(ASTContext &Context,
3613 const StandardConversionSequence& SCS1,
3614 const StandardConversionSequence& SCS2) {
3615 ImplicitConversionSequence::CompareKind Result
3616 = ImplicitConversionSequence::Indistinguishable;
3617
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003618 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00003619 // any non-identity conversion sequence
Douglas Gregor377c1092011-06-05 06:15:20 +00003620 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3621 return ImplicitConversionSequence::Better;
3622 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3623 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003624
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003625 if (SCS1.Second != SCS2.Second) {
3626 if (SCS1.Second == ICK_Identity)
3627 Result = ImplicitConversionSequence::Better;
3628 else if (SCS2.Second == ICK_Identity)
3629 Result = ImplicitConversionSequence::Worse;
3630 else
3631 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003632 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003633 return ImplicitConversionSequence::Indistinguishable;
3634
3635 if (SCS1.Third == SCS2.Third) {
3636 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3637 : ImplicitConversionSequence::Indistinguishable;
3638 }
3639
3640 if (SCS1.Third == ICK_Identity)
3641 return Result == ImplicitConversionSequence::Worse
3642 ? ImplicitConversionSequence::Indistinguishable
3643 : ImplicitConversionSequence::Better;
3644
3645 if (SCS2.Third == ICK_Identity)
3646 return Result == ImplicitConversionSequence::Better
3647 ? ImplicitConversionSequence::Indistinguishable
3648 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003649
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003650 return ImplicitConversionSequence::Indistinguishable;
3651}
3652
Douglas Gregore696ebb2011-01-26 14:52:12 +00003653/// \brief Determine whether one of the given reference bindings is better
3654/// than the other based on what kind of bindings they are.
Richard Smith19172c42014-07-14 02:28:44 +00003655static bool
3656isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3657 const StandardConversionSequence &SCS2) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003658 // C++0x [over.ics.rank]p3b4:
3659 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3660 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003661 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00003662 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003663 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00003664 // reference*.
3665 //
3666 // FIXME: Rvalue references. We're going rogue with the above edits,
3667 // because the semantics in the current C++0x working paper (N3225 at the
3668 // time of this writing) break the standard definition of std::forward
3669 // and std::reference_wrapper when dealing with references to functions.
3670 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00003671 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3672 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3673 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003674
Douglas Gregore696ebb2011-01-26 14:52:12 +00003675 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3676 SCS2.IsLvalueReference) ||
3677 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
Richard Smith19172c42014-07-14 02:28:44 +00003678 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
Douglas Gregore696ebb2011-01-26 14:52:12 +00003679}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003680
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003681/// CompareStandardConversionSequences - Compare two standard
3682/// conversion sequences to determine whether one is better than the
3683/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00003684static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +00003685CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +00003686 const StandardConversionSequence& SCS1,
3687 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003688{
3689 // Standard conversion sequence S1 is a better conversion sequence
3690 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3691
3692 // -- S1 is a proper subsequence of S2 (comparing the conversion
3693 // sequences in the canonical form defined by 13.3.3.1.1,
3694 // excluding any Lvalue Transformation; the identity conversion
3695 // sequence is considered to be a subsequence of any
3696 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003697 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00003698 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003699 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003700
3701 // -- the rank of S1 is better than the rank of S2 (by the rules
3702 // defined below), or, if not that,
3703 ImplicitConversionRank Rank1 = SCS1.getRank();
3704 ImplicitConversionRank Rank2 = SCS2.getRank();
3705 if (Rank1 < Rank2)
3706 return ImplicitConversionSequence::Better;
3707 else if (Rank2 < Rank1)
3708 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003709
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003710 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3711 // are indistinguishable unless one of the following rules
3712 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00003713
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003714 // A conversion that is not a conversion of a pointer, or
3715 // pointer to member, to bool is better than another conversion
3716 // that is such a conversion.
3717 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3718 return SCS2.isPointerConversionToBool()
3719 ? ImplicitConversionSequence::Better
3720 : ImplicitConversionSequence::Worse;
3721
Douglas Gregor5c407d92008-10-23 00:40:37 +00003722 // C++ [over.ics.rank]p4b2:
3723 //
3724 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003725 // conversion of B* to A* is better than conversion of B* to
3726 // void*, and conversion of A* to void* is better than conversion
3727 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00003728 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003729 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00003730 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003731 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003732 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3733 // Exactly one of the conversion sequences is a conversion to
3734 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003735 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3736 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003737 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3738 // Neither conversion sequence converts to a void pointer; compare
3739 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003740 if (ImplicitConversionSequence::CompareKind DerivedCK
Richard Smith0f59cb32015-12-18 21:45:41 +00003741 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003742 return DerivedCK;
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003743 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3744 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003745 // Both conversion sequences are conversions to void
3746 // pointers. Compare the source types to determine if there's an
3747 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00003748 QualType FromType1 = SCS1.getFromType();
3749 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003750
3751 // Adjust the types we're converting from via the array-to-pointer
3752 // conversion, if we need to.
3753 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003754 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003755 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003756 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003757
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003758 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3759 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003760
Richard Smith0f59cb32015-12-18 21:45:41 +00003761 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003762 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00003763 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003764 return ImplicitConversionSequence::Worse;
3765
3766 // Objective-C++: If one interface is more specific than the
3767 // other, it is the better one.
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003768 const ObjCObjectPointerType* FromObjCPtr1
3769 = FromType1->getAs<ObjCObjectPointerType>();
3770 const ObjCObjectPointerType* FromObjCPtr2
3771 = FromType2->getAs<ObjCObjectPointerType>();
3772 if (FromObjCPtr1 && FromObjCPtr2) {
3773 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3774 FromObjCPtr2);
3775 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3776 FromObjCPtr1);
3777 if (AssignLeft != AssignRight) {
3778 return AssignLeft? ImplicitConversionSequence::Better
3779 : ImplicitConversionSequence::Worse;
3780 }
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003781 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003782 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003783
3784 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3785 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00003786 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00003787 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003788 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003789
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003790 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003791 // Check for a better reference binding based on the kind of bindings.
3792 if (isBetterReferenceBindingKind(SCS1, SCS2))
3793 return ImplicitConversionSequence::Better;
3794 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3795 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003796
Sebastian Redlb28b4072009-03-22 23:49:27 +00003797 // C++ [over.ics.rank]p3b4:
3798 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3799 // which the references refer are the same type except for
3800 // top-level cv-qualifiers, and the type to which the reference
3801 // initialized by S2 refers is more cv-qualified than the type
3802 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003803 QualType T1 = SCS1.getToType(2);
3804 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003805 T1 = S.Context.getCanonicalType(T1);
3806 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003807 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003808 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3809 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003810 if (UnqualT1 == UnqualT2) {
John McCall31168b02011-06-15 23:02:42 +00003811 // Objective-C++ ARC: If the references refer to objects with different
3812 // lifetimes, prefer bindings that don't change lifetime.
3813 if (SCS1.ObjCLifetimeConversionBinding !=
3814 SCS2.ObjCLifetimeConversionBinding) {
3815 return SCS1.ObjCLifetimeConversionBinding
3816 ? ImplicitConversionSequence::Worse
3817 : ImplicitConversionSequence::Better;
3818 }
3819
Chandler Carruth8e543b32010-12-12 08:17:55 +00003820 // If the type is an array type, promote the element qualifiers to the
3821 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003822 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003823 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003824 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003825 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003826 if (T2.isMoreQualifiedThan(T1))
3827 return ImplicitConversionSequence::Better;
3828 else if (T1.isMoreQualifiedThan(T2))
John McCall31168b02011-06-15 23:02:42 +00003829 return ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003830 }
3831 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003832
Francois Pichet08d2fa02011-09-18 21:37:37 +00003833 // In Microsoft mode, prefer an integral conversion to a
3834 // floating-to-integral conversion if the integral conversion
3835 // is between types of the same size.
3836 // For example:
3837 // void f(float);
3838 // void f(int);
3839 // int main {
3840 // long a;
3841 // f(a);
3842 // }
3843 // Here, MSVC will call f(int) instead of generating a compile error
3844 // as clang will do in standard mode.
Alp Tokerbfa39342014-01-14 12:51:41 +00003845 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3846 SCS2.Second == ICK_Floating_Integral &&
Francois Pichet08d2fa02011-09-18 21:37:37 +00003847 S.Context.getTypeSize(SCS1.getFromType()) ==
Alp Tokerbfa39342014-01-14 12:51:41 +00003848 S.Context.getTypeSize(SCS1.getToType(2)))
Francois Pichet08d2fa02011-09-18 21:37:37 +00003849 return ImplicitConversionSequence::Better;
3850
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003851 return ImplicitConversionSequence::Indistinguishable;
3852}
3853
3854/// CompareQualificationConversions - Compares two standard conversion
3855/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00003856/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
Richard Smith17c00b42014-11-12 01:24:00 +00003857static ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003858CompareQualificationConversions(Sema &S,
3859 const StandardConversionSequence& SCS1,
3860 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00003861 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003862 // -- S1 and S2 differ only in their qualification conversion and
3863 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3864 // cv-qualification signature of type T1 is a proper subset of
3865 // the cv-qualification signature of type T2, and S1 is not the
3866 // deprecated string literal array-to-pointer conversion (4.2).
3867 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3868 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3869 return ImplicitConversionSequence::Indistinguishable;
3870
3871 // FIXME: the example in the standard doesn't use a qualification
3872 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003873 QualType T1 = SCS1.getToType(2);
3874 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003875 T1 = S.Context.getCanonicalType(T1);
3876 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003877 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003878 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3879 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003880
3881 // If the types are the same, we won't learn anything by unwrapped
3882 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003883 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003884 return ImplicitConversionSequence::Indistinguishable;
3885
Chandler Carruth607f38e2009-12-29 07:16:59 +00003886 // If the type is an array type, promote the element qualifiers to the type
3887 // for comparison.
3888 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003889 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003890 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003891 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003892
Mike Stump11289f42009-09-09 15:08:12 +00003893 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003894 = ImplicitConversionSequence::Indistinguishable;
John McCall31168b02011-06-15 23:02:42 +00003895
3896 // Objective-C++ ARC:
3897 // Prefer qualification conversions not involving a change in lifetime
3898 // to qualification conversions that do not change lifetime.
3899 if (SCS1.QualificationIncludesObjCLifetime !=
3900 SCS2.QualificationIncludesObjCLifetime) {
3901 Result = SCS1.QualificationIncludesObjCLifetime
3902 ? ImplicitConversionSequence::Worse
3903 : ImplicitConversionSequence::Better;
3904 }
3905
John McCall5c32be02010-08-24 20:38:10 +00003906 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003907 // Within each iteration of the loop, we check the qualifiers to
3908 // determine if this still looks like a qualification
3909 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003910 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003911 // until there are no more pointers or pointers-to-members left
3912 // to unwrap. This essentially mimics what
3913 // IsQualificationConversion does, but here we're checking for a
3914 // strict subset of qualifiers.
3915 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3916 // The qualifiers are the same, so this doesn't tell us anything
3917 // about how the sequences rank.
3918 ;
3919 else if (T2.isMoreQualifiedThan(T1)) {
3920 // T1 has fewer qualifiers, so it could be the better sequence.
3921 if (Result == ImplicitConversionSequence::Worse)
3922 // Neither has qualifiers that are a subset of the other's
3923 // qualifiers.
3924 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003925
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003926 Result = ImplicitConversionSequence::Better;
3927 } else if (T1.isMoreQualifiedThan(T2)) {
3928 // T2 has fewer qualifiers, so it could be the better sequence.
3929 if (Result == ImplicitConversionSequence::Better)
3930 // Neither has qualifiers that are a subset of the other's
3931 // qualifiers.
3932 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003933
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003934 Result = ImplicitConversionSequence::Worse;
3935 } else {
3936 // Qualifiers are disjoint.
3937 return ImplicitConversionSequence::Indistinguishable;
3938 }
3939
3940 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00003941 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003942 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003943 }
3944
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003945 // Check that the winning standard conversion sequence isn't using
3946 // the deprecated string literal array to pointer conversion.
3947 switch (Result) {
3948 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003949 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003950 Result = ImplicitConversionSequence::Indistinguishable;
3951 break;
3952
3953 case ImplicitConversionSequence::Indistinguishable:
3954 break;
3955
3956 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003957 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003958 Result = ImplicitConversionSequence::Indistinguishable;
3959 break;
3960 }
3961
3962 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003963}
3964
Douglas Gregor5c407d92008-10-23 00:40:37 +00003965/// CompareDerivedToBaseConversions - Compares two standard conversion
3966/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00003967/// various kinds of derived-to-base conversions (C++
3968/// [over.ics.rank]p4b3). As part of these checks, we also look at
3969/// conversions between Objective-C interface types.
Richard Smith17c00b42014-11-12 01:24:00 +00003970static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +00003971CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +00003972 const StandardConversionSequence& SCS1,
3973 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00003974 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003975 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00003976 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003977 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003978
3979 // Adjust the types we're converting from via the array-to-pointer
3980 // conversion, if we need to.
3981 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003982 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003983 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003984 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003985
3986 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00003987 FromType1 = S.Context.getCanonicalType(FromType1);
3988 ToType1 = S.Context.getCanonicalType(ToType1);
3989 FromType2 = S.Context.getCanonicalType(FromType2);
3990 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003991
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003992 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00003993 //
3994 // If class B is derived directly or indirectly from class A and
3995 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00003996 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003997 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00003998 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00003999 SCS2.Second == ICK_Pointer_Conversion &&
4000 /*FIXME: Remove if Objective-C id conversions get their own rank*/
4001 FromType1->isPointerType() && FromType2->isPointerType() &&
4002 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00004003 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004004 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00004005 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004006 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00004007 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004008 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00004009 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004010 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00004011
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004012 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00004013 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004014 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00004015 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004016 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00004017 return ImplicitConversionSequence::Worse;
4018 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004019
4020 // -- conversion of B* to A* is better than conversion of C* to A*,
4021 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004022 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004023 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004024 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004025 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00004026 }
4027 } else if (SCS1.Second == ICK_Pointer_Conversion &&
4028 SCS2.Second == ICK_Pointer_Conversion) {
4029 const ObjCObjectPointerType *FromPtr1
4030 = FromType1->getAs<ObjCObjectPointerType>();
4031 const ObjCObjectPointerType *FromPtr2
4032 = FromType2->getAs<ObjCObjectPointerType>();
4033 const ObjCObjectPointerType *ToPtr1
4034 = ToType1->getAs<ObjCObjectPointerType>();
4035 const ObjCObjectPointerType *ToPtr2
4036 = ToType2->getAs<ObjCObjectPointerType>();
4037
4038 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4039 // Apply the same conversion ranking rules for Objective-C pointer types
4040 // that we do for C++ pointers to class types. However, we employ the
4041 // Objective-C pseudo-subtyping relationship used for assignment of
4042 // Objective-C pointer types.
4043 bool FromAssignLeft
4044 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4045 bool FromAssignRight
4046 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4047 bool ToAssignLeft
4048 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4049 bool ToAssignRight
4050 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4051
4052 // A conversion to an a non-id object pointer type or qualified 'id'
4053 // type is better than a conversion to 'id'.
4054 if (ToPtr1->isObjCIdType() &&
4055 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4056 return ImplicitConversionSequence::Worse;
4057 if (ToPtr2->isObjCIdType() &&
4058 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4059 return ImplicitConversionSequence::Better;
4060
4061 // A conversion to a non-id object pointer type is better than a
4062 // conversion to a qualified 'id' type
4063 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4064 return ImplicitConversionSequence::Worse;
4065 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4066 return ImplicitConversionSequence::Better;
4067
4068 // A conversion to an a non-Class object pointer type or qualified 'Class'
4069 // type is better than a conversion to 'Class'.
4070 if (ToPtr1->isObjCClassType() &&
4071 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4072 return ImplicitConversionSequence::Worse;
4073 if (ToPtr2->isObjCClassType() &&
4074 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4075 return ImplicitConversionSequence::Better;
4076
4077 // A conversion to a non-Class object pointer type is better than a
4078 // conversion to a qualified 'Class' type.
4079 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4080 return ImplicitConversionSequence::Worse;
4081 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4082 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00004083
Douglas Gregor058d3de2011-01-31 18:51:41 +00004084 // -- "conversion of C* to B* is better than conversion of C* to A*,"
4085 if (S.Context.hasSameType(FromType1, FromType2) &&
4086 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4087 (ToAssignLeft != ToAssignRight))
4088 return ToAssignLeft? ImplicitConversionSequence::Worse
4089 : ImplicitConversionSequence::Better;
4090
4091 // -- "conversion of B* to A* is better than conversion of C* to A*,"
4092 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4093 (FromAssignLeft != FromAssignRight))
4094 return FromAssignLeft? ImplicitConversionSequence::Better
4095 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004096 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00004097 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00004098
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00004099 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004100 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4101 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4102 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004103 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004104 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004105 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004106 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004107 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004108 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004109 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004110 ToType2->getAs<MemberPointerType>();
4111 const Type *FromPointeeType1 = FromMemPointer1->getClass();
4112 const Type *ToPointeeType1 = ToMemPointer1->getClass();
4113 const Type *FromPointeeType2 = FromMemPointer2->getClass();
4114 const Type *ToPointeeType2 = ToMemPointer2->getClass();
4115 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4116 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4117 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4118 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00004119 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004120 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004121 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004122 return ImplicitConversionSequence::Worse;
Richard Smith0f59cb32015-12-18 21:45:41 +00004123 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004124 return ImplicitConversionSequence::Better;
4125 }
4126 // conversion of B::* to C::* is better than conversion of A::* to C::*
4127 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004128 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004129 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004130 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004131 return ImplicitConversionSequence::Worse;
4132 }
4133 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004134
Douglas Gregor5ab11652010-04-17 22:01:05 +00004135 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00004136 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00004137 // -- binding of an expression of type C to a reference of type
4138 // B& is better than binding an expression of type C to a
4139 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00004140 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4141 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004142 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004143 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004144 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004145 return ImplicitConversionSequence::Worse;
4146 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004147
Douglas Gregor2fe98832008-11-03 19:09:14 +00004148 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00004149 // -- binding of an expression of type B to a reference of type
4150 // A& is better than binding an expression of type C to a
4151 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00004152 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4153 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004154 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004155 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004156 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004157 return ImplicitConversionSequence::Worse;
4158 }
4159 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004160
Douglas Gregor5c407d92008-10-23 00:40:37 +00004161 return ImplicitConversionSequence::Indistinguishable;
4162}
4163
Douglas Gregor45bb4832013-03-26 23:36:30 +00004164/// \brief Determine whether the given type is valid, e.g., it is not an invalid
4165/// C++ class.
4166static bool isTypeValid(QualType T) {
4167 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4168 return !Record->isInvalidDecl();
4169
4170 return true;
4171}
4172
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004173/// CompareReferenceRelationship - Compare the two types T1 and T2 to
4174/// determine whether they are reference-related,
4175/// reference-compatible, reference-compatible with added
4176/// qualification, or incompatible, for use in C++ initialization by
4177/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4178/// type, and the first type (T1) is the pointee type of the reference
4179/// type being initialized.
4180Sema::ReferenceCompareResult
4181Sema::CompareReferenceRelationship(SourceLocation Loc,
4182 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004183 bool &DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004184 bool &ObjCConversion,
4185 bool &ObjCLifetimeConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004186 assert(!OrigT1->isReferenceType() &&
4187 "T1 must be the pointee type of the reference type");
4188 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4189
4190 QualType T1 = Context.getCanonicalType(OrigT1);
4191 QualType T2 = Context.getCanonicalType(OrigT2);
4192 Qualifiers T1Quals, T2Quals;
4193 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4194 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4195
4196 // C++ [dcl.init.ref]p4:
4197 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4198 // reference-related to "cv2 T2" if T1 is the same type as T2, or
4199 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004200 DerivedToBase = false;
4201 ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004202 ObjCLifetimeConversion = false;
Richard Smith1be59c52016-10-22 01:32:19 +00004203 QualType ConvertedT2;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004204 if (UnqualT1 == UnqualT2) {
4205 // Nothing to do.
Richard Smithdb0ac552015-12-18 22:40:25 +00004206 } else if (isCompleteType(Loc, OrigT2) &&
Douglas Gregor45bb4832013-03-26 23:36:30 +00004207 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00004208 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004209 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004210 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4211 UnqualT2->isObjCObjectOrInterfaceType() &&
4212 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4213 ObjCConversion = true;
Richard Smith1be59c52016-10-22 01:32:19 +00004214 else if (UnqualT2->isFunctionType() &&
4215 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2))
4216 // C++1z [dcl.init.ref]p4:
4217 // cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept
4218 // function" and T1 is "function"
4219 //
4220 // We extend this to also apply to 'noreturn', so allow any function
4221 // conversion between function types.
4222 return Ref_Compatible;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004223 else
4224 return Ref_Incompatible;
4225
4226 // At this point, we know that T1 and T2 are reference-related (at
4227 // least).
4228
4229 // If the type is an array type, promote the element qualifiers to the type
4230 // for comparison.
4231 if (isa<ArrayType>(T1) && T1Quals)
4232 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4233 if (isa<ArrayType>(T2) && T2Quals)
4234 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4235
4236 // C++ [dcl.init.ref]p4:
4237 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4238 // reference-related to T2 and cv1 is the same cv-qualification
4239 // as, or greater cv-qualification than, cv2. For purposes of
4240 // overload resolution, cases for which cv1 is greater
4241 // cv-qualification than cv2 are identified as
4242 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregord517d552011-04-28 17:56:11 +00004243 //
4244 // Note that we also require equivalence of Objective-C GC and address-space
4245 // qualifiers when performing these computations, so that e.g., an int in
4246 // address space 1 is not reference-compatible with an int in address
4247 // space 2.
John McCall31168b02011-06-15 23:02:42 +00004248 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4249 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00004250 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4251 ObjCLifetimeConversion = true;
4252
John McCall31168b02011-06-15 23:02:42 +00004253 T1Quals.removeObjCLifetime();
4254 T2Quals.removeObjCLifetime();
John McCall31168b02011-06-15 23:02:42 +00004255 }
4256
Andrey Bokhanko45d41322016-05-11 18:38:21 +00004257 // MS compiler ignores __unaligned qualifier for references; do the same.
4258 T1Quals.removeUnaligned();
4259 T2Quals.removeUnaligned();
4260
Richard Smithce766292016-10-21 23:01:55 +00004261 if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004262 return Ref_Compatible;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004263 else
4264 return Ref_Related;
4265}
4266
George Burgess IVd5c7e7c2017-01-14 05:19:34 +00004267/// \brief Look for a user-defined conversion to a value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00004268/// with DeclType. Return true if something definite is found.
4269static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00004270FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4271 QualType DeclType, SourceLocation DeclLoc,
4272 Expr *Init, QualType T2, bool AllowRvalues,
4273 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004274 assert(T2->isRecordType() && "Can only find conversions of record types.");
4275 CXXRecordDecl *T2RecordDecl
4276 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4277
Richard Smith100b24a2014-04-17 01:52:14 +00004278 OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal);
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004279 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4280 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004281 NamedDecl *D = *I;
4282 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4283 if (isa<UsingShadowDecl>(D))
4284 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4285
4286 FunctionTemplateDecl *ConvTemplate
4287 = dyn_cast<FunctionTemplateDecl>(D);
4288 CXXConversionDecl *Conv;
4289 if (ConvTemplate)
4290 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4291 else
4292 Conv = cast<CXXConversionDecl>(D);
4293
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004294 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00004295 // explicit conversions, skip it.
4296 if (!AllowExplicit && Conv->isExplicit())
4297 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004298
Douglas Gregor836a7e82010-08-11 02:15:33 +00004299 if (AllowRvalues) {
4300 bool DerivedToBase = false;
4301 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004302 bool ObjCLifetimeConversion = false;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004303
4304 // If we are initializing an rvalue reference, don't permit conversion
4305 // functions that return lvalues.
4306 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4307 const ReferenceType *RefType
4308 = Conv->getConversionType()->getAs<LValueReferenceType>();
4309 if (RefType && !RefType->getPointeeType()->isFunctionType())
4310 continue;
4311 }
4312
Douglas Gregor836a7e82010-08-11 02:15:33 +00004313 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00004314 S.CompareReferenceRelationship(
4315 DeclLoc,
4316 Conv->getConversionType().getNonReferenceType()
4317 .getUnqualifiedType(),
4318 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCall31168b02011-06-15 23:02:42 +00004319 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth8e543b32010-12-12 08:17:55 +00004320 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00004321 continue;
4322 } else {
4323 // If the conversion function doesn't return a reference type,
4324 // it can't be considered for this conversion. An rvalue reference
4325 // is only acceptable if its referencee is a function type.
4326
4327 const ReferenceType *RefType =
4328 Conv->getConversionType()->getAs<ReferenceType>();
4329 if (!RefType ||
4330 (!RefType->isLValueReferenceType() &&
4331 !RefType->getPointeeType()->isFunctionType()))
4332 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00004333 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004334
Douglas Gregor836a7e82010-08-11 02:15:33 +00004335 if (ConvTemplate)
4336 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004337 Init, DeclType, CandidateSet,
4338 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor836a7e82010-08-11 02:15:33 +00004339 else
4340 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004341 DeclType, CandidateSet,
4342 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redld92badf2010-06-30 18:13:39 +00004343 }
4344
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004345 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4346
Sebastian Redld92badf2010-06-30 18:13:39 +00004347 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00004348 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004349 case OR_Success:
4350 // C++ [over.ics.ref]p1:
4351 //
4352 // [...] If the parameter binds directly to the result of
4353 // applying a conversion function to the argument
4354 // expression, the implicit conversion sequence is a
4355 // user-defined conversion sequence (13.3.3.1.2), with the
4356 // second standard conversion sequence either an identity
4357 // conversion or, if the conversion function returns an
4358 // entity of a type that is a derived class of the parameter
4359 // type, a derived-to-base Conversion.
4360 if (!Best->FinalConversion.DirectBinding)
4361 return false;
4362
4363 ICS.setUserDefined();
4364 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4365 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004366 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redld92badf2010-06-30 18:13:39 +00004367 ICS.UserDefined.ConversionFunction = Best->Function;
John McCall30909032011-09-21 08:36:56 +00004368 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redld92badf2010-06-30 18:13:39 +00004369 ICS.UserDefined.EllipsisConversion = false;
4370 assert(ICS.UserDefined.After.ReferenceBinding &&
4371 ICS.UserDefined.After.DirectBinding &&
4372 "Expected a direct reference binding!");
4373 return true;
4374
4375 case OR_Ambiguous:
4376 ICS.setAmbiguous();
4377 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4378 Cand != CandidateSet.end(); ++Cand)
4379 if (Cand->Viable)
Richard Smithc2bebe92016-05-11 20:37:46 +00004380 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
Sebastian Redld92badf2010-06-30 18:13:39 +00004381 return true;
4382
4383 case OR_No_Viable_Function:
4384 case OR_Deleted:
4385 // There was no suitable conversion, or we found a deleted
4386 // conversion; continue with other checks.
4387 return false;
4388 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004389
David Blaikie8a40f702012-01-17 06:56:22 +00004390 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redld92badf2010-06-30 18:13:39 +00004391}
4392
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004393/// \brief Compute an implicit conversion sequence for reference
4394/// initialization.
4395static ImplicitConversionSequence
Sebastian Redldf888642011-12-03 14:54:30 +00004396TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004397 SourceLocation DeclLoc,
4398 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00004399 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004400 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4401
4402 // Most paths end in a failed conversion.
4403 ImplicitConversionSequence ICS;
4404 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4405
4406 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4407 QualType T2 = Init->getType();
4408
4409 // If the initializer is the address of an overloaded function, try
4410 // to resolve the overloaded function. If all goes well, T2 is the
4411 // type of the resulting function.
4412 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4413 DeclAccessPair Found;
4414 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4415 false, Found))
4416 T2 = Fn->getType();
4417 }
4418
4419 // Compute some basic properties of the types and the initializer.
4420 bool isRValRef = DeclType->isRValueReferenceType();
4421 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004422 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004423 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00004424 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004425 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004426 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004427 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004428
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004429
Sebastian Redld92badf2010-06-30 18:13:39 +00004430 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00004431 // A reference to type "cv1 T1" is initialized by an expression
4432 // of type "cv2 T2" as follows:
4433
Sebastian Redld92badf2010-06-30 18:13:39 +00004434 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00004435 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004436 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4437 // reference-compatible with "cv2 T2," or
4438 //
4439 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
Richard Smithce766292016-10-21 23:01:55 +00004440 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004441 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00004442 // When a parameter of reference type binds directly (8.5.3)
4443 // to an argument expression, the implicit conversion sequence
4444 // is the identity conversion, unless the argument expression
4445 // has a type that is a derived class of the parameter type,
4446 // in which case the implicit conversion sequence is a
4447 // derived-to-base Conversion (13.3.3.1).
4448 ICS.setStandard();
4449 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004450 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4451 : ObjCConversion? ICK_Compatible_Conversion
4452 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00004453 ICS.Standard.Third = ICK_Identity;
4454 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4455 ICS.Standard.setToType(0, T2);
4456 ICS.Standard.setToType(1, T1);
4457 ICS.Standard.setToType(2, T1);
4458 ICS.Standard.ReferenceBinding = true;
4459 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004460 ICS.Standard.IsLvalueReference = !isRValRef;
4461 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4462 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004463 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004464 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Craig Topperc3ec1492014-05-26 06:22:03 +00004465 ICS.Standard.CopyConstructor = nullptr;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004466 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004467
Sebastian Redld92badf2010-06-30 18:13:39 +00004468 // Nothing more to do: the inaccessibility/ambiguity check for
4469 // derived-to-base conversions is suppressed when we're
4470 // computing the implicit conversion sequence (C++
4471 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004472 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00004473 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004474
Sebastian Redld92badf2010-06-30 18:13:39 +00004475 // -- has a class type (i.e., T2 is a class type), where T1 is
4476 // not reference-related to T2, and can be implicitly
4477 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4478 // is reference-compatible with "cv3 T3" 92) (this
4479 // conversion is selected by enumerating the applicable
4480 // conversion functions (13.3.1.6) and choosing the best
4481 // one through overload resolution (13.3)),
4482 if (!SuppressUserConversions && T2->isRecordType() &&
Richard Smithdb0ac552015-12-18 22:40:25 +00004483 S.isCompleteType(DeclLoc, T2) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00004484 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00004485 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4486 Init, T2, /*AllowRvalues=*/false,
4487 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00004488 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004489 }
4490 }
4491
Sebastian Redld92badf2010-06-30 18:13:39 +00004492 // -- Otherwise, the reference shall be an lvalue reference to a
4493 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00004494 // shall be an rvalue reference.
Richard Smithce4f6082012-05-24 04:29:20 +00004495 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004496 return ICS;
4497
Douglas Gregorf143cd52011-01-24 16:14:37 +00004498 // -- If the initializer expression
4499 //
4500 // -- is an xvalue, class prvalue, array prvalue or function
John McCall31168b02011-06-15 23:02:42 +00004501 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Richard Smithce766292016-10-21 23:01:55 +00004502 if (RefRelationship == Sema::Ref_Compatible &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004503 (InitCategory.isXValue() ||
Richard Smithce766292016-10-21 23:01:55 +00004504 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4505 (InitCategory.isLValue() && T2->isFunctionType()))) {
Douglas Gregorf143cd52011-01-24 16:14:37 +00004506 ICS.setStandard();
4507 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004508 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004509 : ObjCConversion? ICK_Compatible_Conversion
4510 : ICK_Identity;
4511 ICS.Standard.Third = ICK_Identity;
4512 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4513 ICS.Standard.setToType(0, T2);
4514 ICS.Standard.setToType(1, T1);
4515 ICS.Standard.setToType(2, T1);
4516 ICS.Standard.ReferenceBinding = true;
4517 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4518 // binding unless we're binding to a class prvalue.
4519 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4520 // allow the use of rvalue references in C++98/03 for the benefit of
4521 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004522 ICS.Standard.DirectBinding =
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004523 S.getLangOpts().CPlusPlus11 ||
Richard Smithb94afe12014-07-14 19:54:05 +00004524 !(InitCategory.isPRValue() || T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00004525 ICS.Standard.IsLvalueReference = !isRValRef;
4526 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004527 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00004528 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004529 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Craig Topperc3ec1492014-05-26 06:22:03 +00004530 ICS.Standard.CopyConstructor = nullptr;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004531 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004532 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00004533 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004534
Douglas Gregorf143cd52011-01-24 16:14:37 +00004535 // -- has a class type (i.e., T2 is a class type), where T1 is not
4536 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004537 // an xvalue, class prvalue, or function lvalue of type
4538 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00004539 // "cv3 T3",
4540 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004541 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00004542 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004543 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004544 // class subobject).
4545 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
Richard Smithdb0ac552015-12-18 22:40:25 +00004546 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004547 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4548 Init, T2, /*AllowRvalues=*/true,
4549 AllowExplicit)) {
4550 // In the second case, if the reference is an rvalue reference
4551 // and the second standard conversion sequence of the
4552 // user-defined conversion sequence includes an lvalue-to-rvalue
4553 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004554 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004555 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4556 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4557
Douglas Gregor95273c32011-01-21 16:36:05 +00004558 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00004559 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004560
Richard Smith19172c42014-07-14 02:28:44 +00004561 // A temporary of function type cannot be created; don't even try.
4562 if (T1->isFunctionType())
4563 return ICS;
4564
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004565 // -- Otherwise, a temporary of type "cv1 T1" is created and
4566 // initialized from the initializer expression using the
4567 // rules for a non-reference copy initialization (8.5). The
4568 // reference is then bound to the temporary. If T1 is
4569 // reference-related to T2, cv1 must be the same
4570 // cv-qualification as, or greater cv-qualification than,
4571 // cv2; otherwise, the program is ill-formed.
4572 if (RefRelationship == Sema::Ref_Related) {
4573 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4574 // we would be reference-compatible or reference-compatible with
4575 // added qualification. But that wasn't the case, so the reference
4576 // initialization fails.
John McCall31168b02011-06-15 23:02:42 +00004577 //
4578 // Note that we only want to check address spaces and cvr-qualifiers here.
Andrey Bokhanko45d41322016-05-11 18:38:21 +00004579 // ObjC GC, lifetime and unaligned qualifiers aren't important.
John McCall31168b02011-06-15 23:02:42 +00004580 Qualifiers T1Quals = T1.getQualifiers();
4581 Qualifiers T2Quals = T2.getQualifiers();
4582 T1Quals.removeObjCGCAttr();
4583 T1Quals.removeObjCLifetime();
4584 T2Quals.removeObjCGCAttr();
4585 T2Quals.removeObjCLifetime();
Andrey Bokhanko45d41322016-05-11 18:38:21 +00004586 // MS compiler ignores __unaligned qualifier for references; do the same.
4587 T1Quals.removeUnaligned();
4588 T2Quals.removeUnaligned();
John McCall31168b02011-06-15 23:02:42 +00004589 if (!T1Quals.compatiblyIncludes(T2Quals))
4590 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004591 }
4592
4593 // If at least one of the types is a class type, the types are not
4594 // related, and we aren't allowed any user conversions, the
4595 // reference binding fails. This case is important for breaking
4596 // recursion, since TryImplicitConversion below will attempt to
4597 // create a temporary through the use of a copy constructor.
4598 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4599 (T1->isRecordType() || T2->isRecordType()))
4600 return ICS;
4601
Douglas Gregorcba72b12011-01-21 05:18:22 +00004602 // If T1 is reference-related to T2 and the reference is an rvalue
4603 // reference, the initializer expression shall not be an lvalue.
4604 if (RefRelationship >= Sema::Ref_Related &&
4605 isRValRef && Init->Classify(S.Context).isLValue())
4606 return ICS;
4607
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004608 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004609 // When a parameter of reference type is not bound directly to
4610 // an argument expression, the conversion sequence is the one
4611 // required to convert the argument expression to the
4612 // underlying type of the reference according to
4613 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4614 // to copy-initializing a temporary of the underlying type with
4615 // the argument expression. Any difference in top-level
4616 // cv-qualification is subsumed by the initialization itself
4617 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00004618 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4619 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004620 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004621 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004622 /*AllowObjCWritebackConversion=*/false,
4623 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004624
4625 // Of course, that's still a reference binding.
4626 if (ICS.isStandard()) {
4627 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004628 ICS.Standard.IsLvalueReference = !isRValRef;
Richard Smith19172c42014-07-14 02:28:44 +00004629 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004630 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004631 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004632 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004633 } else if (ICS.isUserDefined()) {
Richard Smith19172c42014-07-14 02:28:44 +00004634 const ReferenceType *LValRefType =
4635 ICS.UserDefined.ConversionFunction->getReturnType()
4636 ->getAs<LValueReferenceType>();
4637
4638 // C++ [over.ics.ref]p3:
4639 // Except for an implicit object parameter, for which see 13.3.1, a
4640 // standard conversion sequence cannot be formed if it requires [...]
4641 // binding an rvalue reference to an lvalue other than a function
4642 // lvalue.
4643 // Note that the function case is not possible here.
4644 if (DeclType->isRValueReferenceType() && LValRefType) {
4645 // FIXME: This is the wrong BadConversionSequence. The problem is binding
4646 // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4647 // reference to an rvalue!
4648 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4649 return ICS;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004650 }
Richard Smith19172c42014-07-14 02:28:44 +00004651
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004652 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004653 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
Richard Smith19172c42014-07-14 02:28:44 +00004654 ICS.UserDefined.After.BindsToFunctionLvalue = false;
4655 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004656 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4657 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004658 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00004659
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004660 return ICS;
4661}
4662
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004663static ImplicitConversionSequence
4664TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4665 bool SuppressUserConversions,
4666 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004667 bool AllowObjCWritebackConversion,
4668 bool AllowExplicit = false);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004669
4670/// TryListConversion - Try to copy-initialize a value of type ToType from the
4671/// initializer list From.
4672static ImplicitConversionSequence
4673TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4674 bool SuppressUserConversions,
4675 bool InOverloadResolution,
4676 bool AllowObjCWritebackConversion) {
4677 // C++11 [over.ics.list]p1:
4678 // When an argument is an initializer list, it is not an expression and
4679 // special rules apply for converting it to a parameter type.
4680
4681 ImplicitConversionSequence Result;
4682 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4683
Sebastian Redl09edce02012-01-23 22:09:39 +00004684 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004685 // initialized from init lists.
Richard Smithdb0ac552015-12-18 22:40:25 +00004686 if (!S.isCompleteType(From->getLocStart(), ToType))
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004687 return Result;
4688
Larisse Voufo19d08672015-01-27 18:47:05 +00004689 // Per DR1467:
4690 // If the parameter type is a class X and the initializer list has a single
4691 // element of type cv U, where U is X or a class derived from X, the
4692 // implicit conversion sequence is the one required to convert the element
4693 // to the parameter type.
4694 //
4695 // Otherwise, if the parameter type is a character array [... ]
4696 // and the initializer list has a single element that is an
4697 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4698 // implicit conversion sequence is the identity conversion.
4699 if (From->getNumInits() == 1) {
4700 if (ToType->isRecordType()) {
4701 QualType InitType = From->getInit(0)->getType();
4702 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00004703 S.IsDerivedFrom(From->getLocStart(), InitType, ToType))
Larisse Voufo19d08672015-01-27 18:47:05 +00004704 return TryCopyInitialization(S, From->getInit(0), ToType,
4705 SuppressUserConversions,
4706 InOverloadResolution,
4707 AllowObjCWritebackConversion);
4708 }
Richard Smith1bbaba82015-01-27 23:23:39 +00004709 // FIXME: Check the other conditions here: array of character type,
4710 // initializer is a string literal.
4711 if (ToType->isArrayType()) {
Larisse Voufo19d08672015-01-27 18:47:05 +00004712 InitializedEntity Entity =
4713 InitializedEntity::InitializeParameter(S.Context, ToType,
4714 /*Consumed=*/false);
4715 if (S.CanPerformCopyInitialization(Entity, From)) {
4716 Result.setStandard();
4717 Result.Standard.setAsIdentityConversion();
4718 Result.Standard.setFromType(ToType);
4719 Result.Standard.setAllToTypes(ToType);
4720 return Result;
4721 }
4722 }
4723 }
4724
4725 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004726 // C++11 [over.ics.list]p2:
4727 // If the parameter type is std::initializer_list<X> or "array of X" and
4728 // all the elements can be implicitly converted to X, the implicit
4729 // conversion sequence is the worst conversion necessary to convert an
4730 // element of the list to X.
Larisse Voufo19d08672015-01-27 18:47:05 +00004731 //
4732 // C++14 [over.ics.list]p3:
NAKAMURA Takumib01d86b2015-02-25 11:02:00 +00004733 // Otherwise, if the parameter type is "array of N X", if the initializer
Larisse Voufo19d08672015-01-27 18:47:05 +00004734 // list has exactly N elements or if it has fewer than N elements and X is
4735 // default-constructible, and if all the elements of the initializer list
4736 // can be implicitly converted to X, the implicit conversion sequence is
4737 // the worst conversion necessary to convert an element of the list to X.
Richard Smith1bbaba82015-01-27 23:23:39 +00004738 //
4739 // FIXME: We're missing a lot of these checks.
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004740 bool toStdInitializerList = false;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004741 QualType X;
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004742 if (ToType->isArrayType())
Richard Smith0db1ea52012-12-09 06:48:56 +00004743 X = S.Context.getAsArrayType(ToType)->getElementType();
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004744 else
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004745 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004746 if (!X.isNull()) {
4747 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4748 Expr *Init = From->getInit(i);
4749 ImplicitConversionSequence ICS =
4750 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4751 InOverloadResolution,
4752 AllowObjCWritebackConversion);
4753 // If a single element isn't convertible, fail.
4754 if (ICS.isBad()) {
4755 Result = ICS;
4756 break;
4757 }
4758 // Otherwise, look for the worst conversion.
4759 if (Result.isBad() ||
Richard Smith0f59cb32015-12-18 21:45:41 +00004760 CompareImplicitConversionSequences(S, From->getLocStart(), ICS,
4761 Result) ==
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004762 ImplicitConversionSequence::Worse)
4763 Result = ICS;
4764 }
Douglas Gregor0f5c1c02012-04-04 23:09:20 +00004765
4766 // For an empty list, we won't have computed any conversion sequence.
4767 // Introduce the identity conversion sequence.
4768 if (From->getNumInits() == 0) {
4769 Result.setStandard();
4770 Result.Standard.setAsIdentityConversion();
4771 Result.Standard.setFromType(ToType);
4772 Result.Standard.setAllToTypes(ToType);
4773 }
4774
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004775 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004776 return Result;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004777 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004778
Larisse Voufo19d08672015-01-27 18:47:05 +00004779 // C++14 [over.ics.list]p4:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004780 // C++11 [over.ics.list]p3:
4781 // Otherwise, if the parameter is a non-aggregate class X and overload
4782 // resolution chooses a single best constructor [...] the implicit
4783 // conversion sequence is a user-defined conversion sequence. If multiple
4784 // constructors are viable but none is better than the others, the
4785 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004786 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4787 // This function can deal with initializer lists.
Richard Smitha93f1022013-09-06 22:30:28 +00004788 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4789 /*AllowExplicit=*/false,
4790 InOverloadResolution, /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004791 AllowObjCWritebackConversion,
4792 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004793 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004794
Larisse Voufo19d08672015-01-27 18:47:05 +00004795 // C++14 [over.ics.list]p5:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004796 // C++11 [over.ics.list]p4:
4797 // Otherwise, if the parameter has an aggregate type which can be
4798 // initialized from the initializer list [...] the implicit conversion
4799 // sequence is a user-defined conversion sequence.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004800 if (ToType->isAggregateType()) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004801 // Type is an aggregate, argument is an init list. At this point it comes
4802 // down to checking whether the initialization works.
4803 // FIXME: Find out whether this parameter is consumed or not.
Richard Smithb8c0f552016-12-09 18:49:13 +00004804 // FIXME: Expose SemaInit's aggregate initialization code so that we don't
4805 // need to call into the initialization code here; overload resolution
4806 // should not be doing that.
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004807 InitializedEntity Entity =
4808 InitializedEntity::InitializeParameter(S.Context, ToType,
4809 /*Consumed=*/false);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004810 if (S.CanPerformCopyInitialization(Entity, From)) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004811 Result.setUserDefined();
4812 Result.UserDefined.Before.setAsIdentityConversion();
4813 // Initializer lists don't have a type.
4814 Result.UserDefined.Before.setFromType(QualType());
4815 Result.UserDefined.Before.setAllToTypes(QualType());
4816
4817 Result.UserDefined.After.setAsIdentityConversion();
4818 Result.UserDefined.After.setFromType(ToType);
4819 Result.UserDefined.After.setAllToTypes(ToType);
Craig Topperc3ec1492014-05-26 06:22:03 +00004820 Result.UserDefined.ConversionFunction = nullptr;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004821 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004822 return Result;
4823 }
4824
Larisse Voufo19d08672015-01-27 18:47:05 +00004825 // C++14 [over.ics.list]p6:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004826 // C++11 [over.ics.list]p5:
4827 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redldf888642011-12-03 14:54:30 +00004828 if (ToType->isReferenceType()) {
4829 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4830 // mention initializer lists in any way. So we go by what list-
4831 // initialization would do and try to extrapolate from that.
4832
4833 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4834
4835 // If the initializer list has a single element that is reference-related
4836 // to the parameter type, we initialize the reference from that.
4837 if (From->getNumInits() == 1) {
4838 Expr *Init = From->getInit(0);
4839
4840 QualType T2 = Init->getType();
4841
4842 // If the initializer is the address of an overloaded function, try
4843 // to resolve the overloaded function. If all goes well, T2 is the
4844 // type of the resulting function.
4845 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4846 DeclAccessPair Found;
4847 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4848 Init, ToType, false, Found))
4849 T2 = Fn->getType();
4850 }
4851
4852 // Compute some basic properties of the types and the initializer.
4853 bool dummy1 = false;
4854 bool dummy2 = false;
4855 bool dummy3 = false;
4856 Sema::ReferenceCompareResult RefRelationship
4857 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4858 dummy2, dummy3);
4859
Richard Smith4d2bbd72013-09-06 01:22:42 +00004860 if (RefRelationship >= Sema::Ref_Related) {
Richard Smitha93f1022013-09-06 22:30:28 +00004861 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4862 SuppressUserConversions,
4863 /*AllowExplicit=*/false);
Richard Smith4d2bbd72013-09-06 01:22:42 +00004864 }
Sebastian Redldf888642011-12-03 14:54:30 +00004865 }
4866
4867 // Otherwise, we bind the reference to a temporary created from the
4868 // initializer list.
4869 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4870 InOverloadResolution,
4871 AllowObjCWritebackConversion);
4872 if (Result.isFailure())
4873 return Result;
4874 assert(!Result.isEllipsis() &&
4875 "Sub-initialization cannot result in ellipsis conversion.");
4876
4877 // Can we even bind to a temporary?
4878 if (ToType->isRValueReferenceType() ||
4879 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4880 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4881 Result.UserDefined.After;
4882 SCS.ReferenceBinding = true;
4883 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4884 SCS.BindsToRvalue = true;
4885 SCS.BindsToFunctionLvalue = false;
4886 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4887 SCS.ObjCLifetimeConversionBinding = false;
4888 } else
4889 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4890 From, ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004891 return Result;
Sebastian Redldf888642011-12-03 14:54:30 +00004892 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004893
Larisse Voufo19d08672015-01-27 18:47:05 +00004894 // C++14 [over.ics.list]p7:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004895 // C++11 [over.ics.list]p6:
4896 // Otherwise, if the parameter type is not a class:
4897 if (!ToType->isRecordType()) {
Larisse Voufo19d08672015-01-27 18:47:05 +00004898 // - if the initializer list has one element that is not itself an
4899 // initializer list, the implicit conversion sequence is the one
4900 // required to convert the element to the parameter type.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004901 unsigned NumInits = From->getNumInits();
Richard Smith1bbaba82015-01-27 23:23:39 +00004902 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004903 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4904 SuppressUserConversions,
4905 InOverloadResolution,
4906 AllowObjCWritebackConversion);
4907 // - if the initializer list has no elements, the implicit conversion
4908 // sequence is the identity conversion.
4909 else if (NumInits == 0) {
4910 Result.setStandard();
4911 Result.Standard.setAsIdentityConversion();
John McCallb73bc9a2012-04-04 02:40:27 +00004912 Result.Standard.setFromType(ToType);
4913 Result.Standard.setAllToTypes(ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004914 }
4915 return Result;
4916 }
4917
Larisse Voufo19d08672015-01-27 18:47:05 +00004918 // C++14 [over.ics.list]p8:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004919 // C++11 [over.ics.list]p7:
4920 // In all cases other than those enumerated above, no conversion is possible
4921 return Result;
4922}
4923
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004924/// TryCopyInitialization - Try to copy-initialize a value of type
4925/// ToType from the expression From. Return the implicit conversion
4926/// sequence required to pass this argument, which may be a bad
4927/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00004928/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00004929/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004930static ImplicitConversionSequence
4931TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004932 bool SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004933 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004934 bool AllowObjCWritebackConversion,
4935 bool AllowExplicit) {
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004936 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4937 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4938 InOverloadResolution,AllowObjCWritebackConversion);
4939
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004940 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004941 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004942 /*FIXME:*/From->getLocStart(),
4943 SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004944 AllowExplicit);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004945
John McCall5c32be02010-08-24 20:38:10 +00004946 return TryImplicitConversion(S, From, ToType,
4947 SuppressUserConversions,
4948 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004949 InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00004950 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004951 AllowObjCWritebackConversion,
4952 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004953}
4954
Anna Zaks1b068122011-07-28 19:46:48 +00004955static bool TryCopyInitialization(const CanQualType FromQTy,
4956 const CanQualType ToQTy,
4957 Sema &S,
4958 SourceLocation Loc,
4959 ExprValueKind FromVK) {
4960 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4961 ImplicitConversionSequence ICS =
4962 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4963
4964 return !ICS.isBad();
4965}
4966
Douglas Gregor436424c2008-11-18 23:14:02 +00004967/// TryObjectArgumentInitialization - Try to initialize the object
4968/// parameter of the given member function (@c Method) from the
4969/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00004970static ImplicitConversionSequence
Richard Smith0f59cb32015-12-18 21:45:41 +00004971TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004972 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00004973 CXXMethodDecl *Method,
4974 CXXRecordDecl *ActingContext) {
4975 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00004976 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4977 // const volatile object.
4978 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4979 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00004980 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00004981
4982 // Set up the conversion sequence as a "bad" conversion, to allow us
4983 // to exit early.
4984 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00004985
4986 // We need to have an object of class type.
Douglas Gregor02824322011-01-26 19:30:28 +00004987 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004988 FromType = PT->getPointeeType();
4989
Douglas Gregor02824322011-01-26 19:30:28 +00004990 // When we had a pointer, it's implicitly dereferenced, so we
4991 // better have an lvalue.
4992 assert(FromClassification.isLValue());
4993 }
4994
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004995 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00004996
Douglas Gregor02824322011-01-26 19:30:28 +00004997 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004998 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00004999 // parameter is
5000 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005001 // - "lvalue reference to cv X" for functions declared without a
5002 // ref-qualifier or with the & ref-qualifier
5003 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00005004 // ref-qualifier
5005 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005006 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00005007 // cv-qualification on the member function declaration.
5008 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005009 // However, when finding an implicit conversion sequence for the argument, we
Richard Smith122f88d2016-12-06 23:52:28 +00005010 // are not allowed to perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00005011 // (C++ [over.match.funcs]p5). We perform a simplified version of
5012 // reference binding here, that allows class rvalues to bind to
5013 // non-constant references.
5014
Douglas Gregor02824322011-01-26 19:30:28 +00005015 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00005016 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005017 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005018 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00005019 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00005020 ICS.setBad(BadConversionSequence::bad_qualifiers,
Richard Smith03c66d32013-01-26 02:07:32 +00005021 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00005022 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00005023 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005024
5025 // Check that we have either the same type or a derived type. It
5026 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00005027 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00005028 ImplicitConversionKind SecondKind;
5029 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5030 SecondKind = ICK_Identity;
Richard Smith0f59cb32015-12-18 21:45:41 +00005031 } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00005032 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00005033 else {
John McCall65eb8792010-02-25 01:37:24 +00005034 ICS.setBad(BadConversionSequence::unrelated_class,
5035 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00005036 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00005037 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005038
Douglas Gregor02824322011-01-26 19:30:28 +00005039 // Check the ref-qualifier.
5040 switch (Method->getRefQualifier()) {
5041 case RQ_None:
5042 // Do nothing; we don't care about lvalueness or rvalueness.
5043 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005044
Douglas Gregor02824322011-01-26 19:30:28 +00005045 case RQ_LValue:
5046 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
5047 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005048 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00005049 ImplicitParamType);
5050 return ICS;
5051 }
5052 break;
5053
5054 case RQ_RValue:
5055 if (!FromClassification.isRValue()) {
5056 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005057 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00005058 ImplicitParamType);
5059 return ICS;
5060 }
5061 break;
5062 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005063
Douglas Gregor436424c2008-11-18 23:14:02 +00005064 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00005065 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00005066 ICS.Standard.setAsIdentityConversion();
5067 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00005068 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00005069 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00005070 ICS.Standard.ReferenceBinding = true;
5071 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005072 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00005073 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00005074 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5075 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5076 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00005077 return ICS;
5078}
5079
5080/// PerformObjectArgumentInitialization - Perform initialization of
5081/// the implicit object parameter for the given Method with the given
5082/// expression.
John Wiegley01296292011-04-08 18:41:53 +00005083ExprResult
5084Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005085 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00005086 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00005087 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005088 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00005089 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005090 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00005091
Douglas Gregor02824322011-01-26 19:30:28 +00005092 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005093 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005094 FromRecordType = PT->getPointeeType();
5095 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00005096 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005097 } else {
5098 FromRecordType = From->getType();
5099 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00005100 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005101 }
5102
John McCall6e9f8f62009-12-03 04:06:58 +00005103 // Note that we always use the true parent context when performing
5104 // the actual argument initialization.
Nico Weberb58e51c2014-11-19 05:21:39 +00005105 ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
Richard Smith0f59cb32015-12-18 21:45:41 +00005106 *this, From->getLocStart(), From->getType(), FromClassification, Method,
5107 Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005108 if (ICS.isBad()) {
5109 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
5110 Qualifiers FromQs = FromRecordType.getQualifiers();
5111 Qualifiers ToQs = DestType.getQualifiers();
5112 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5113 if (CVR) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005114 Diag(From->getLocStart(),
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005115 diag::err_member_function_call_bad_cvr)
5116 << Method->getDeclName() << FromRecordType << (CVR - 1)
5117 << From->getSourceRange();
5118 Diag(Method->getLocation(), diag::note_previous_decl)
5119 << Method->getDeclName();
John Wiegley01296292011-04-08 18:41:53 +00005120 return ExprError();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005121 }
5122 }
5123
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005124 return Diag(From->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00005125 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005126 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005127 }
Mike Stump11289f42009-09-09 15:08:12 +00005128
John Wiegley01296292011-04-08 18:41:53 +00005129 if (ICS.Standard.Second == ICK_Derived_To_Base) {
5130 ExprResult FromRes =
5131 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5132 if (FromRes.isInvalid())
5133 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005134 From = FromRes.get();
John Wiegley01296292011-04-08 18:41:53 +00005135 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005136
Douglas Gregorcc3f3252010-03-03 23:55:11 +00005137 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley01296292011-04-08 18:41:53 +00005138 From = ImpCastExprToType(From, DestType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005139 From->getValueKind()).get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005140 return From;
Douglas Gregor436424c2008-11-18 23:14:02 +00005141}
5142
Douglas Gregor5fb53972009-01-14 15:45:31 +00005143/// TryContextuallyConvertToBool - Attempt to contextually convert the
5144/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00005145static ImplicitConversionSequence
5146TryContextuallyConvertToBool(Sema &S, Expr *From) {
John McCall5c32be02010-08-24 20:38:10 +00005147 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00005148 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00005149 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00005150 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00005151 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005152 /*AllowObjCWritebackConversion=*/false,
5153 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00005154}
5155
5156/// PerformContextuallyConvertToBool - Perform a contextual conversion
5157/// of the expression From to bool (C++0x [conv]p3).
John Wiegley01296292011-04-08 18:41:53 +00005158ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00005159 if (checkPlaceholderForOverload(*this, From))
5160 return ExprError();
5161
John McCall5c32be02010-08-24 20:38:10 +00005162 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00005163 if (!ICS.isBad())
5164 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005165
Fariborz Jahanian76197412009-11-18 18:26:29 +00005166 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005167 return Diag(From->getLocStart(),
John McCall0009fcc2011-04-26 20:42:42 +00005168 diag::err_typecheck_bool_condition)
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00005169 << From->getType() << From->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00005170 return ExprError();
Douglas Gregor5fb53972009-01-14 15:45:31 +00005171}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005172
Richard Smithf8379a02012-01-18 23:55:52 +00005173/// Check that the specified conversion is permitted in a converted constant
5174/// expression, according to C++11 [expr.const]p3. Return true if the conversion
5175/// is acceptable.
5176static bool CheckConvertedConstantConversions(Sema &S,
5177 StandardConversionSequence &SCS) {
5178 // Since we know that the target type is an integral or unscoped enumeration
5179 // type, most conversion kinds are impossible. All possible First and Third
5180 // conversions are fine.
5181 switch (SCS.Second) {
5182 case ICK_Identity:
Richard Smith3c4f8d22016-10-16 17:54:23 +00005183 case ICK_Function_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005184 case ICK_Integral_Promotion:
Richard Smith410cc892014-11-26 03:26:53 +00005185 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
Egor Churaev89831422016-12-23 14:55:49 +00005186 case ICK_Zero_Queue_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005187 return true;
5188
5189 case ICK_Boolean_Conversion:
Richard Smithca24ed42012-09-13 22:00:12 +00005190 // Conversion from an integral or unscoped enumeration type to bool is
Richard Smith410cc892014-11-26 03:26:53 +00005191 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5192 // conversion, so we allow it in a converted constant expression.
5193 //
5194 // FIXME: Per core issue 1407, we should not allow this, but that breaks
5195 // a lot of popular code. We should at least add a warning for this
5196 // (non-conforming) extension.
Richard Smithca24ed42012-09-13 22:00:12 +00005197 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5198 SCS.getToType(2)->isBooleanType();
5199
Richard Smith410cc892014-11-26 03:26:53 +00005200 case ICK_Pointer_Conversion:
5201 case ICK_Pointer_Member:
5202 // C++1z: null pointer conversions and null member pointer conversions are
5203 // only permitted if the source type is std::nullptr_t.
5204 return SCS.getFromType()->isNullPtrType();
5205
5206 case ICK_Floating_Promotion:
5207 case ICK_Complex_Promotion:
5208 case ICK_Floating_Conversion:
5209 case ICK_Complex_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005210 case ICK_Floating_Integral:
Richard Smith410cc892014-11-26 03:26:53 +00005211 case ICK_Compatible_Conversion:
5212 case ICK_Derived_To_Base:
5213 case ICK_Vector_Conversion:
5214 case ICK_Vector_Splat:
Richard Smithf8379a02012-01-18 23:55:52 +00005215 case ICK_Complex_Real:
Richard Smith410cc892014-11-26 03:26:53 +00005216 case ICK_Block_Pointer_Conversion:
5217 case ICK_TransparentUnionConversion:
5218 case ICK_Writeback_Conversion:
5219 case ICK_Zero_Event_Conversion:
George Burgess IV45461812015-10-11 20:13:20 +00005220 case ICK_C_Only_Conversion:
George Burgess IV2099b542016-09-02 22:59:57 +00005221 case ICK_Incompatible_Pointer_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005222 return false;
5223
5224 case ICK_Lvalue_To_Rvalue:
5225 case ICK_Array_To_Pointer:
5226 case ICK_Function_To_Pointer:
Richard Smith410cc892014-11-26 03:26:53 +00005227 llvm_unreachable("found a first conversion kind in Second");
5228
Richard Smithf8379a02012-01-18 23:55:52 +00005229 case ICK_Qualification:
Richard Smith410cc892014-11-26 03:26:53 +00005230 llvm_unreachable("found a third conversion kind in Second");
Richard Smithf8379a02012-01-18 23:55:52 +00005231
5232 case ICK_Num_Conversion_Kinds:
5233 break;
5234 }
5235
5236 llvm_unreachable("unknown conversion kind");
5237}
5238
5239/// CheckConvertedConstantExpression - Check that the expression From is a
5240/// converted constant expression of type T, perform the conversion and produce
5241/// the converted expression, per C++11 [expr.const]p3.
Richard Smith410cc892014-11-26 03:26:53 +00005242static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5243 QualType T, APValue &Value,
5244 Sema::CCEKind CCE,
5245 bool RequireInt) {
5246 assert(S.getLangOpts().CPlusPlus11 &&
5247 "converted constant expression outside C++11");
Richard Smithf8379a02012-01-18 23:55:52 +00005248
Richard Smith410cc892014-11-26 03:26:53 +00005249 if (checkPlaceholderForOverload(S, From))
Richard Smithf8379a02012-01-18 23:55:52 +00005250 return ExprError();
5251
Richard Smith410cc892014-11-26 03:26:53 +00005252 // C++1z [expr.const]p3:
5253 // A converted constant expression of type T is an expression,
5254 // implicitly converted to type T, where the converted
5255 // expression is a constant expression and the implicit conversion
5256 // sequence contains only [... list of conversions ...].
Ismail Pazarbasi4a007742016-09-07 18:24:54 +00005257 // C++1z [stmt.if]p2:
5258 // If the if statement is of the form if constexpr, the value of the
5259 // condition shall be a contextually converted constant expression of type
5260 // bool.
Richard Smithf8379a02012-01-18 23:55:52 +00005261 ImplicitConversionSequence ICS =
Ismail Pazarbasi4a007742016-09-07 18:24:54 +00005262 CCE == Sema::CCEK_ConstexprIf
5263 ? TryContextuallyConvertToBool(S, From)
5264 : TryCopyInitialization(S, From, T,
5265 /*SuppressUserConversions=*/false,
5266 /*InOverloadResolution=*/false,
5267 /*AllowObjcWritebackConversion=*/false,
5268 /*AllowExplicit=*/false);
Craig Topperc3ec1492014-05-26 06:22:03 +00005269 StandardConversionSequence *SCS = nullptr;
Richard Smithf8379a02012-01-18 23:55:52 +00005270 switch (ICS.getKind()) {
5271 case ImplicitConversionSequence::StandardConversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005272 SCS = &ICS.Standard;
5273 break;
5274 case ImplicitConversionSequence::UserDefinedConversion:
Richard Smith410cc892014-11-26 03:26:53 +00005275 // We are converting to a non-class type, so the Before sequence
5276 // must be trivial.
Richard Smithf8379a02012-01-18 23:55:52 +00005277 SCS = &ICS.UserDefined.After;
5278 break;
5279 case ImplicitConversionSequence::AmbiguousConversion:
5280 case ImplicitConversionSequence::BadConversion:
Richard Smith410cc892014-11-26 03:26:53 +00005281 if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5282 return S.Diag(From->getLocStart(),
5283 diag::err_typecheck_converted_constant_expression)
5284 << From->getType() << From->getSourceRange() << T;
Richard Smithf8379a02012-01-18 23:55:52 +00005285 return ExprError();
5286
5287 case ImplicitConversionSequence::EllipsisConversion:
5288 llvm_unreachable("ellipsis conversion in converted constant expression");
5289 }
5290
Richard Smith410cc892014-11-26 03:26:53 +00005291 // Check that we would only use permitted conversions.
5292 if (!CheckConvertedConstantConversions(S, *SCS)) {
5293 return S.Diag(From->getLocStart(),
5294 diag::err_typecheck_converted_constant_expression_disallowed)
5295 << From->getType() << From->getSourceRange() << T;
5296 }
5297 // [...] and where the reference binding (if any) binds directly.
5298 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5299 return S.Diag(From->getLocStart(),
5300 diag::err_typecheck_converted_constant_expression_indirect)
5301 << From->getType() << From->getSourceRange() << T;
5302 }
5303
5304 ExprResult Result =
5305 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
Richard Smithf8379a02012-01-18 23:55:52 +00005306 if (Result.isInvalid())
5307 return Result;
5308
5309 // Check for a narrowing implicit conversion.
5310 APValue PreNarrowingValue;
Richard Smith5614ca72012-03-23 23:55:39 +00005311 QualType PreNarrowingType;
Richard Smith410cc892014-11-26 03:26:53 +00005312 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
Richard Smith5614ca72012-03-23 23:55:39 +00005313 PreNarrowingType)) {
Richard Smith52e624f2016-12-21 21:42:57 +00005314 case NK_Dependent_Narrowing:
5315 // Implicit conversion to a narrower type, but the expression is
5316 // value-dependent so we can't tell whether it's actually narrowing.
Richard Smithf8379a02012-01-18 23:55:52 +00005317 case NK_Variable_Narrowing:
5318 // Implicit conversion to a narrower type, and the value is not a constant
5319 // expression. We'll diagnose this in a moment.
5320 case NK_Not_Narrowing:
5321 break;
5322
5323 case NK_Constant_Narrowing:
Richard Smith410cc892014-11-26 03:26:53 +00005324 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00005325 << CCE << /*Constant*/1
Richard Smith410cc892014-11-26 03:26:53 +00005326 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
Richard Smithf8379a02012-01-18 23:55:52 +00005327 break;
5328
5329 case NK_Type_Narrowing:
Richard Smith410cc892014-11-26 03:26:53 +00005330 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00005331 << CCE << /*Constant*/0 << From->getType() << T;
5332 break;
5333 }
5334
Richard Smith52e624f2016-12-21 21:42:57 +00005335 if (Result.get()->isValueDependent()) {
5336 Value = APValue();
5337 return Result;
5338 }
5339
Richard Smithf8379a02012-01-18 23:55:52 +00005340 // Check the expression is a constant expression.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005341 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithf8379a02012-01-18 23:55:52 +00005342 Expr::EvalResult Eval;
5343 Eval.Diag = &Notes;
5344
Richard Smith410cc892014-11-26 03:26:53 +00005345 if ((T->isReferenceType()
5346 ? !Result.get()->EvaluateAsLValue(Eval, S.Context)
5347 : !Result.get()->EvaluateAsRValue(Eval, S.Context)) ||
5348 (RequireInt && !Eval.Val.isInt())) {
Richard Smithf8379a02012-01-18 23:55:52 +00005349 // The expression can't be folded, so we can't keep it at this position in
5350 // the AST.
5351 Result = ExprError();
Richard Smith911e1422012-01-30 22:27:01 +00005352 } else {
Richard Smith410cc892014-11-26 03:26:53 +00005353 Value = Eval.Val;
Richard Smith911e1422012-01-30 22:27:01 +00005354
5355 if (Notes.empty()) {
5356 // It's a constant expression.
5357 return Result;
5358 }
Richard Smithf8379a02012-01-18 23:55:52 +00005359 }
5360
5361 // It's not a constant expression. Produce an appropriate diagnostic.
5362 if (Notes.size() == 1 &&
5363 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
Richard Smith410cc892014-11-26 03:26:53 +00005364 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
Richard Smithf8379a02012-01-18 23:55:52 +00005365 else {
Richard Smith410cc892014-11-26 03:26:53 +00005366 S.Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smithf8379a02012-01-18 23:55:52 +00005367 << CCE << From->getSourceRange();
5368 for (unsigned I = 0; I < Notes.size(); ++I)
Richard Smith410cc892014-11-26 03:26:53 +00005369 S.Diag(Notes[I].first, Notes[I].second);
Richard Smithf8379a02012-01-18 23:55:52 +00005370 }
Richard Smith410cc892014-11-26 03:26:53 +00005371 return ExprError();
Richard Smithf8379a02012-01-18 23:55:52 +00005372}
5373
Richard Smith410cc892014-11-26 03:26:53 +00005374ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5375 APValue &Value, CCEKind CCE) {
5376 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5377}
5378
5379ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5380 llvm::APSInt &Value,
5381 CCEKind CCE) {
5382 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5383
5384 APValue V;
5385 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
Richard Smith01bfa682016-12-27 02:02:09 +00005386 if (!R.isInvalid() && !R.get()->isValueDependent())
Richard Smith410cc892014-11-26 03:26:53 +00005387 Value = V.getInt();
5388 return R;
5389}
5390
5391
John McCallfec112d2011-09-09 06:11:02 +00005392/// dropPointerConversions - If the given standard conversion sequence
5393/// involves any pointer conversions, remove them. This may change
5394/// the result type of the conversion sequence.
5395static void dropPointerConversion(StandardConversionSequence &SCS) {
5396 if (SCS.Second == ICK_Pointer_Conversion) {
5397 SCS.Second = ICK_Identity;
5398 SCS.Third = ICK_Identity;
5399 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5400 }
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005401}
John McCall5c32be02010-08-24 20:38:10 +00005402
John McCallfec112d2011-09-09 06:11:02 +00005403/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5404/// convert the expression From to an Objective-C pointer type.
5405static ImplicitConversionSequence
5406TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5407 // Do an implicit conversion to 'id'.
5408 QualType Ty = S.Context.getObjCIdType();
5409 ImplicitConversionSequence ICS
5410 = TryImplicitConversion(S, From, Ty,
5411 // FIXME: Are these flags correct?
5412 /*SuppressUserConversions=*/false,
5413 /*AllowExplicit=*/true,
5414 /*InOverloadResolution=*/false,
5415 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005416 /*AllowObjCWritebackConversion=*/false,
5417 /*AllowObjCConversionOnExplicit=*/true);
John McCallfec112d2011-09-09 06:11:02 +00005418
5419 // Strip off any final conversions to 'id'.
5420 switch (ICS.getKind()) {
5421 case ImplicitConversionSequence::BadConversion:
5422 case ImplicitConversionSequence::AmbiguousConversion:
5423 case ImplicitConversionSequence::EllipsisConversion:
5424 break;
5425
5426 case ImplicitConversionSequence::UserDefinedConversion:
5427 dropPointerConversion(ICS.UserDefined.After);
5428 break;
5429
5430 case ImplicitConversionSequence::StandardConversion:
5431 dropPointerConversion(ICS.Standard);
5432 break;
5433 }
5434
5435 return ICS;
5436}
5437
5438/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5439/// conversion of the expression From to an Objective-C pointer type.
Richard Smithe15a3702016-10-06 23:12:58 +00005440/// Returns a valid but null ExprResult if no conversion sequence exists.
John McCallfec112d2011-09-09 06:11:02 +00005441ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00005442 if (checkPlaceholderForOverload(*this, From))
5443 return ExprError();
5444
John McCall8b07ec22010-05-15 11:32:37 +00005445 QualType Ty = Context.getObjCIdType();
John McCallfec112d2011-09-09 06:11:02 +00005446 ImplicitConversionSequence ICS =
5447 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005448 if (!ICS.isBad())
5449 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
Richard Smithe15a3702016-10-06 23:12:58 +00005450 return ExprResult();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005451}
Douglas Gregor5fb53972009-01-14 15:45:31 +00005452
Richard Smith8dd34252012-02-04 07:07:42 +00005453/// Determine whether the provided type is an integral type, or an enumeration
5454/// type of a permitted flavor.
Richard Smithccc11812013-05-21 19:05:48 +00005455bool Sema::ICEConvertDiagnoser::match(QualType T) {
5456 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5457 : T->isIntegralOrUnscopedEnumerationType();
Richard Smith8dd34252012-02-04 07:07:42 +00005458}
5459
Larisse Voufo236bec22013-06-10 06:50:24 +00005460static ExprResult
5461diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5462 Sema::ContextualImplicitConverter &Converter,
5463 QualType T, UnresolvedSetImpl &ViableConversions) {
5464
5465 if (Converter.Suppress)
5466 return ExprError();
5467
5468 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5469 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5470 CXXConversionDecl *Conv =
5471 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5472 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5473 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5474 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005475 return From;
Larisse Voufo236bec22013-06-10 06:50:24 +00005476}
5477
5478static bool
5479diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5480 Sema::ContextualImplicitConverter &Converter,
5481 QualType T, bool HadMultipleCandidates,
5482 UnresolvedSetImpl &ExplicitConversions) {
5483 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5484 DeclAccessPair Found = ExplicitConversions[0];
5485 CXXConversionDecl *Conversion =
5486 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5487
5488 // The user probably meant to invoke the given explicit
5489 // conversion; use it.
5490 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5491 std::string TypeStr;
5492 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5493
5494 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5495 << FixItHint::CreateInsertion(From->getLocStart(),
5496 "static_cast<" + TypeStr + ">(")
5497 << FixItHint::CreateInsertion(
Alp Tokerb6cc5922014-05-03 03:45:55 +00005498 SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
Larisse Voufo236bec22013-06-10 06:50:24 +00005499 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5500
5501 // If we aren't in a SFINAE context, build a call to the
5502 // explicit conversion function.
5503 if (SemaRef.isSFINAEContext())
5504 return true;
5505
Craig Topperc3ec1492014-05-26 06:22:03 +00005506 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
Larisse Voufo236bec22013-06-10 06:50:24 +00005507 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5508 HadMultipleCandidates);
5509 if (Result.isInvalid())
5510 return true;
5511 // Record usage of conversion in an implicit cast.
5512 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005513 CK_UserDefinedConversion, Result.get(),
5514 nullptr, Result.get()->getValueKind());
Larisse Voufo236bec22013-06-10 06:50:24 +00005515 }
5516 return false;
5517}
5518
5519static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5520 Sema::ContextualImplicitConverter &Converter,
5521 QualType T, bool HadMultipleCandidates,
5522 DeclAccessPair &Found) {
5523 CXXConversionDecl *Conversion =
5524 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00005525 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
Larisse Voufo236bec22013-06-10 06:50:24 +00005526
5527 QualType ToType = Conversion->getConversionType().getNonReferenceType();
5528 if (!Converter.SuppressConversion) {
5529 if (SemaRef.isSFINAEContext())
5530 return true;
5531
5532 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5533 << From->getSourceRange();
5534 }
5535
5536 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5537 HadMultipleCandidates);
5538 if (Result.isInvalid())
5539 return true;
5540 // Record usage of conversion in an implicit cast.
5541 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005542 CK_UserDefinedConversion, Result.get(),
5543 nullptr, Result.get()->getValueKind());
Larisse Voufo236bec22013-06-10 06:50:24 +00005544 return false;
5545}
5546
5547static ExprResult finishContextualImplicitConversion(
5548 Sema &SemaRef, SourceLocation Loc, Expr *From,
5549 Sema::ContextualImplicitConverter &Converter) {
5550 if (!Converter.match(From->getType()) && !Converter.Suppress)
5551 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5552 << From->getSourceRange();
5553
5554 return SemaRef.DefaultLvalueConversion(From);
5555}
5556
5557static void
5558collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5559 UnresolvedSetImpl &ViableConversions,
5560 OverloadCandidateSet &CandidateSet) {
5561 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5562 DeclAccessPair FoundDecl = ViableConversions[I];
5563 NamedDecl *D = FoundDecl.getDecl();
5564 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5565 if (isa<UsingShadowDecl>(D))
5566 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5567
5568 CXXConversionDecl *Conv;
5569 FunctionTemplateDecl *ConvTemplate;
5570 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5571 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5572 else
5573 Conv = cast<CXXConversionDecl>(D);
5574
5575 if (ConvTemplate)
5576 SemaRef.AddTemplateConversionCandidate(
Douglas Gregor4b60a152013-11-07 22:34:54 +00005577 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5578 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005579 else
5580 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005581 ToType, CandidateSet,
5582 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005583 }
5584}
5585
Richard Smithccc11812013-05-21 19:05:48 +00005586/// \brief Attempt to convert the given expression to a type which is accepted
5587/// by the given converter.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005588///
Richard Smithccc11812013-05-21 19:05:48 +00005589/// This routine will attempt to convert an expression of class type to a
5590/// type accepted by the specified converter. In C++11 and before, the class
5591/// must have a single non-explicit conversion function converting to a matching
5592/// type. In C++1y, there can be multiple such conversion functions, but only
5593/// one target type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005594///
Douglas Gregor4799d032010-06-30 00:20:43 +00005595/// \param Loc The source location of the construct that requires the
5596/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005597///
James Dennett18348b62012-06-22 08:52:37 +00005598/// \param From The expression we're converting from.
Douglas Gregor4799d032010-06-30 00:20:43 +00005599///
Richard Smithccc11812013-05-21 19:05:48 +00005600/// \param Converter Used to control and diagnose the conversion process.
Richard Smith8dd34252012-02-04 07:07:42 +00005601///
Douglas Gregor4799d032010-06-30 00:20:43 +00005602/// \returns The expression, converted to an integral or enumeration type if
5603/// successful.
Richard Smithccc11812013-05-21 19:05:48 +00005604ExprResult Sema::PerformContextualImplicitConversion(
5605 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005606 // We can't perform any more checking for type-dependent expressions.
5607 if (From->isTypeDependent())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005608 return From;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005609
Eli Friedman1da70392012-01-26 00:26:18 +00005610 // Process placeholders immediately.
5611 if (From->hasPlaceholderType()) {
5612 ExprResult result = CheckPlaceholderExpr(From);
Larisse Voufo236bec22013-06-10 06:50:24 +00005613 if (result.isInvalid())
5614 return result;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005615 From = result.get();
Eli Friedman1da70392012-01-26 00:26:18 +00005616 }
5617
Richard Smithccc11812013-05-21 19:05:48 +00005618 // If the expression already has a matching type, we're golden.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005619 QualType T = From->getType();
Richard Smithccc11812013-05-21 19:05:48 +00005620 if (Converter.match(T))
Eli Friedman1da70392012-01-26 00:26:18 +00005621 return DefaultLvalueConversion(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005622
5623 // FIXME: Check for missing '()' if T is a function type?
5624
Richard Smithccc11812013-05-21 19:05:48 +00005625 // We can only perform contextual implicit conversions on objects of class
5626 // type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005627 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikiebbafb8a2012-03-11 07:00:24 +00005628 if (!RecordTy || !getLangOpts().CPlusPlus) {
Richard Smithccc11812013-05-21 19:05:48 +00005629 if (!Converter.Suppress)
5630 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005631 return From;
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005632 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005633
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005634 // We must have a complete class type.
Douglas Gregora6c5abb2012-05-04 16:48:41 +00005635 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
Richard Smithccc11812013-05-21 19:05:48 +00005636 ContextualImplicitConverter &Converter;
Douglas Gregore2b37442012-05-04 22:38:52 +00005637 Expr *From;
Richard Smithccc11812013-05-21 19:05:48 +00005638
5639 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
Richard Smithdb0ac552015-12-18 22:40:25 +00005640 : Converter(Converter), From(From) {}
Richard Smithccc11812013-05-21 19:05:48 +00005641
Craig Toppere14c0f82014-03-12 04:55:44 +00005642 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00005643 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005644 }
Richard Smithccc11812013-05-21 19:05:48 +00005645 } IncompleteDiagnoser(Converter, From);
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005646
Richard Smithdb0ac552015-12-18 22:40:25 +00005647 if (Converter.Suppress ? !isCompleteType(Loc, T)
5648 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005649 return From;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005650
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005651 // Look for a conversion to an integral or enumeration type.
Larisse Voufo236bec22013-06-10 06:50:24 +00005652 UnresolvedSet<4>
5653 ViableConversions; // These are *potentially* viable in C++1y.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005654 UnresolvedSet<4> ExplicitConversions;
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005655 const auto &Conversions =
Larisse Voufo236bec22013-06-10 06:50:24 +00005656 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005657
Larisse Voufo236bec22013-06-10 06:50:24 +00005658 bool HadMultipleCandidates =
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005659 (std::distance(Conversions.begin(), Conversions.end()) > 1);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005660
Larisse Voufo236bec22013-06-10 06:50:24 +00005661 // To check that there is only one target type, in C++1y:
5662 QualType ToType;
5663 bool HasUniqueTargetType = true;
5664
5665 // Collect explicit or viable (potentially in C++1y) conversions.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005666 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005667 NamedDecl *D = (*I)->getUnderlyingDecl();
5668 CXXConversionDecl *Conversion;
5669 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5670 if (ConvTemplate) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005671 if (getLangOpts().CPlusPlus14)
Larisse Voufo236bec22013-06-10 06:50:24 +00005672 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5673 else
5674 continue; // C++11 does not consider conversion operator templates(?).
5675 } else
5676 Conversion = cast<CXXConversionDecl>(D);
5677
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005678 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
Larisse Voufo236bec22013-06-10 06:50:24 +00005679 "Conversion operator templates are considered potentially "
5680 "viable in C++1y");
5681
5682 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5683 if (Converter.match(CurToType) || ConvTemplate) {
5684
5685 if (Conversion->isExplicit()) {
5686 // FIXME: For C++1y, do we need this restriction?
5687 // cf. diagnoseNoViableConversion()
5688 if (!ConvTemplate)
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005689 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
Larisse Voufo236bec22013-06-10 06:50:24 +00005690 } else {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005691 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005692 if (ToType.isNull())
5693 ToType = CurToType.getUnqualifiedType();
5694 else if (HasUniqueTargetType &&
5695 (CurToType.getUnqualifiedType() != ToType))
5696 HasUniqueTargetType = false;
5697 }
5698 ViableConversions.addDecl(I.getDecl(), I.getAccess());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005699 }
Richard Smith8dd34252012-02-04 07:07:42 +00005700 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005701 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005702
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005703 if (getLangOpts().CPlusPlus14) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005704 // C++1y [conv]p6:
5705 // ... An expression e of class type E appearing in such a context
5706 // is said to be contextually implicitly converted to a specified
5707 // type T and is well-formed if and only if e can be implicitly
5708 // converted to a type T that is determined as follows: E is searched
Larisse Voufo67170bd2013-06-10 08:25:58 +00005709 // for conversion functions whose return type is cv T or reference to
5710 // cv T such that T is allowed by the context. There shall be
Larisse Voufo236bec22013-06-10 06:50:24 +00005711 // exactly one such T.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005712
Larisse Voufo236bec22013-06-10 06:50:24 +00005713 // If no unique T is found:
5714 if (ToType.isNull()) {
5715 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5716 HadMultipleCandidates,
5717 ExplicitConversions))
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005718 return ExprError();
Larisse Voufo236bec22013-06-10 06:50:24 +00005719 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005720 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005721
Larisse Voufo236bec22013-06-10 06:50:24 +00005722 // If more than one unique Ts are found:
5723 if (!HasUniqueTargetType)
5724 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5725 ViableConversions);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005726
Larisse Voufo236bec22013-06-10 06:50:24 +00005727 // If one unique T is found:
5728 // First, build a candidate set from the previously recorded
5729 // potentially viable conversions.
Richard Smith100b24a2014-04-17 01:52:14 +00005730 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Larisse Voufo236bec22013-06-10 06:50:24 +00005731 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5732 CandidateSet);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005733
Larisse Voufo236bec22013-06-10 06:50:24 +00005734 // Then, perform overload resolution over the candidate set.
5735 OverloadCandidateSet::iterator Best;
5736 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5737 case OR_Success: {
5738 // Apply this conversion.
5739 DeclAccessPair Found =
5740 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5741 if (recordConversion(*this, Loc, From, Converter, T,
5742 HadMultipleCandidates, Found))
5743 return ExprError();
5744 break;
5745 }
5746 case OR_Ambiguous:
5747 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5748 ViableConversions);
5749 case OR_No_Viable_Function:
5750 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5751 HadMultipleCandidates,
5752 ExplicitConversions))
5753 return ExprError();
5754 // fall through 'OR_Deleted' case.
5755 case OR_Deleted:
5756 // We'll complain below about a non-integral condition type.
5757 break;
5758 }
5759 } else {
5760 switch (ViableConversions.size()) {
5761 case 0: {
5762 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5763 HadMultipleCandidates,
5764 ExplicitConversions))
Douglas Gregor4799d032010-06-30 00:20:43 +00005765 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005766
Larisse Voufo236bec22013-06-10 06:50:24 +00005767 // We'll complain below about a non-integral condition type.
5768 break;
Douglas Gregor4799d032010-06-30 00:20:43 +00005769 }
Larisse Voufo236bec22013-06-10 06:50:24 +00005770 case 1: {
5771 // Apply this conversion.
5772 DeclAccessPair Found = ViableConversions[0];
5773 if (recordConversion(*this, Loc, From, Converter, T,
5774 HadMultipleCandidates, Found))
5775 return ExprError();
5776 break;
5777 }
5778 default:
5779 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5780 ViableConversions);
5781 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005782 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005783
Larisse Voufo236bec22013-06-10 06:50:24 +00005784 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005785}
5786
Richard Smith100b24a2014-04-17 01:52:14 +00005787/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5788/// an acceptable non-member overloaded operator for a call whose
5789/// arguments have types T1 (and, if non-empty, T2). This routine
5790/// implements the check in C++ [over.match.oper]p3b2 concerning
5791/// enumeration types.
5792static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5793 FunctionDecl *Fn,
5794 ArrayRef<Expr *> Args) {
5795 QualType T1 = Args[0]->getType();
5796 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5797
5798 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5799 return true;
5800
5801 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5802 return true;
5803
5804 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5805 if (Proto->getNumParams() < 1)
5806 return false;
5807
5808 if (T1->isEnumeralType()) {
5809 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5810 if (Context.hasSameUnqualifiedType(T1, ArgType))
5811 return true;
5812 }
5813
5814 if (Proto->getNumParams() < 2)
5815 return false;
5816
5817 if (!T2.isNull() && T2->isEnumeralType()) {
5818 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5819 if (Context.hasSameUnqualifiedType(T2, ArgType))
5820 return true;
5821 }
5822
5823 return false;
5824}
5825
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005826/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00005827/// candidate functions, using the given function call arguments. If
5828/// @p SuppressUserConversions, then don't allow user-defined
5829/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00005830///
James Dennett2a4d13c2012-06-15 07:13:21 +00005831/// \param PartialOverloading true if we are performing "partial" overloading
Douglas Gregorcabea402009-09-22 15:41:20 +00005832/// based on an incomplete set of function arguments. This feature is used by
5833/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00005834void
5835Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00005836 DeclAccessPair FoundDecl,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005837 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005838 OverloadCandidateSet &CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00005839 bool SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005840 bool PartialOverloading,
Richard Smith6eedfe72017-01-09 08:01:21 +00005841 bool AllowExplicit,
5842 ConversionSequenceList EarlyConversions) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005843 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00005844 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005845 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00005846 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005847 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00005848
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005849 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005850 if (!isa<CXXConstructorDecl>(Method)) {
5851 // If we get here, it's because we're calling a member function
5852 // that is named without a member access expression (e.g.,
5853 // "this->f") that was either written explicitly or created
5854 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00005855 // function, e.g., X::f(). We use an empty type for the implied
5856 // object argument (C++ [over.call.func]p3), and the acting context
5857 // is irrelevant.
Richard Smith6eedfe72017-01-09 08:01:21 +00005858 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
George Burgess IVce6284b2017-01-28 02:19:40 +00005859 Expr::Classification::makeSimpleLValue(), Args,
5860 CandidateSet, SuppressUserConversions,
5861 PartialOverloading, EarlyConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005862 return;
5863 }
5864 // We treat a constructor like a non-member function, since its object
5865 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005866 }
5867
Douglas Gregorff7028a2009-11-13 23:59:09 +00005868 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005869 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00005870
Richard Smith100b24a2014-04-17 01:52:14 +00005871 // C++ [over.match.oper]p3:
5872 // if no operand has a class type, only those non-member functions in the
5873 // lookup set that have a first parameter of type T1 or "reference to
5874 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5875 // is a right operand) a second parameter of type T2 or "reference to
5876 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
5877 // candidate functions.
5878 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5879 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5880 return;
5881
Richard Smith8b86f2d2013-11-04 01:48:18 +00005882 // C++11 [class.copy]p11: [DR1402]
5883 // A defaulted move constructor that is defined as deleted is ignored by
5884 // overload resolution.
5885 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5886 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5887 Constructor->isMoveConstructor())
5888 return;
5889
Douglas Gregor27381f32009-11-23 12:27:39 +00005890 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005891 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005892
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005893 // Add this candidate
Richard Smith6eedfe72017-01-09 08:01:21 +00005894 OverloadCandidate &Candidate =
5895 CandidateSet.addCandidate(Args.size(), EarlyConversions);
John McCalla0296f72010-03-19 07:35:19 +00005896 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005897 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005898 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005899 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005900 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005901 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005902
John McCall578a1f82014-12-14 01:46:53 +00005903 if (Constructor) {
5904 // C++ [class.copy]p3:
5905 // A member function template is never instantiated to perform the copy
5906 // of a class object to an object of its class type.
5907 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
Richard Smith0f59cb32015-12-18 21:45:41 +00005908 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
John McCall578a1f82014-12-14 01:46:53 +00005909 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00005910 IsDerivedFrom(Args[0]->getLocStart(), Args[0]->getType(),
5911 ClassType))) {
John McCall578a1f82014-12-14 01:46:53 +00005912 Candidate.Viable = false;
5913 Candidate.FailureKind = ovl_fail_illegal_constructor;
5914 return;
5915 }
Richard Smith836a3b42017-01-13 20:46:54 +00005916
5917 // C++ [over.match.funcs]p8: (proposed DR resolution)
5918 // A constructor inherited from class type C that has a first parameter
5919 // of type "reference to P" (including such a constructor instantiated
5920 // from a template) is excluded from the set of candidate functions when
5921 // constructing an object of type cv D if the argument list has exactly
5922 // one argument and D is reference-related to P and P is reference-related
5923 // to C.
5924 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
5925 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
5926 Constructor->getParamDecl(0)->getType()->isReferenceType()) {
5927 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
5928 QualType C = Context.getRecordType(Constructor->getParent());
5929 QualType D = Context.getRecordType(Shadow->getParent());
5930 SourceLocation Loc = Args.front()->getExprLoc();
5931 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
5932 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
5933 Candidate.Viable = false;
5934 Candidate.FailureKind = ovl_fail_inhctor_slice;
5935 return;
5936 }
5937 }
John McCall578a1f82014-12-14 01:46:53 +00005938 }
5939
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005940 unsigned NumParams = Proto->getNumParams();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005941
5942 // (C++ 13.3.2p2): A candidate function having fewer than m
5943 // parameters is viable only if it has an ellipsis in its parameter
5944 // list (8.3.5).
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005945 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
Douglas Gregor2a920012009-09-23 14:56:09 +00005946 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005947 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005948 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005949 return;
5950 }
5951
5952 // (C++ 13.3.2p2): A candidate function having more than m parameters
5953 // is viable only if the (m+1)st parameter has a default argument
5954 // (8.3.6). For the purposes of overload resolution, the
5955 // parameter list is truncated on the right, so that there are
5956 // exactly m parameters.
5957 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005958 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005959 // Not enough arguments.
5960 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005961 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005962 return;
5963 }
5964
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005965 // (CUDA B.1): Check for invalid calls between targets.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005966 if (getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005967 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
Eli Bendersky9a220fc2014-09-29 20:38:29 +00005968 // Skip the check for callers that are implicit members, because in this
5969 // case we may not yet know what the member's target is; the target is
5970 // inferred for the member automatically, based on the bases and fields of
5971 // the class.
Justin Lebarb0080032016-08-10 01:09:11 +00005972 if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005973 Candidate.Viable = false;
5974 Candidate.FailureKind = ovl_fail_bad_target;
5975 return;
5976 }
5977
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005978 // Determine the implicit conversion sequences for each of the
5979 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005980 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Richard Smith6eedfe72017-01-09 08:01:21 +00005981 if (Candidate.Conversions[ArgIdx].isInitialized()) {
5982 // We already formed a conversion sequence for this parameter during
5983 // template argument deduction.
5984 } else if (ArgIdx < NumParams) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005985 // (C++ 13.3.2p3): for F to be a viable function, there shall
5986 // exist for each argument an implicit conversion sequence
5987 // (13.3.3.1) that converts that argument to the corresponding
5988 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00005989 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005990 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005991 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005992 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00005993 /*InOverloadResolution=*/true,
5994 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005995 getLangOpts().ObjCAutoRefCount,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005996 AllowExplicit);
John McCall0d1da222010-01-12 00:44:57 +00005997 if (Candidate.Conversions[ArgIdx].isBad()) {
5998 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005999 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006000 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00006001 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006002 } else {
6003 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6004 // argument for which there is no corresponding parameter is
6005 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006006 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006007 }
6008 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006009
6010 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
6011 Candidate.Viable = false;
6012 Candidate.FailureKind = ovl_fail_enable_if;
6013 Candidate.DeductionFailure.Data = FailedAttr;
6014 return;
6015 }
Yaxun Liu5b746652016-12-18 05:18:55 +00006016
6017 if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) {
6018 Candidate.Viable = false;
6019 Candidate.FailureKind = ovl_fail_ext_disabled;
6020 return;
6021 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006022}
6023
Manman Rend2a3cd72016-04-07 19:30:20 +00006024ObjCMethodDecl *
6025Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
6026 SmallVectorImpl<ObjCMethodDecl *> &Methods) {
6027 if (Methods.size() <= 1)
Fariborz Jahanian0ded4242014-08-13 21:24:14 +00006028 return nullptr;
Manman Rend2a3cd72016-04-07 19:30:20 +00006029
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006030 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6031 bool Match = true;
6032 ObjCMethodDecl *Method = Methods[b];
6033 unsigned NumNamedArgs = Sel.getNumArgs();
6034 // Method might have more arguments than selector indicates. This is due
6035 // to addition of c-style arguments in method.
6036 if (Method->param_size() > NumNamedArgs)
6037 NumNamedArgs = Method->param_size();
6038 if (Args.size() < NumNamedArgs)
6039 continue;
6040
6041 for (unsigned i = 0; i < NumNamedArgs; i++) {
6042 // We can't do any type-checking on a type-dependent argument.
6043 if (Args[i]->isTypeDependent()) {
6044 Match = false;
6045 break;
6046 }
6047
6048 ParmVarDecl *param = Method->parameters()[i];
6049 Expr *argExpr = Args[i];
6050 assert(argExpr && "SelectBestMethod(): missing expression");
6051
6052 // Strip the unbridged-cast placeholder expression off unless it's
6053 // a consumed argument.
6054 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
6055 !param->hasAttr<CFConsumedAttr>())
6056 argExpr = stripARCUnbridgedCast(argExpr);
6057
6058 // If the parameter is __unknown_anytype, move on to the next method.
6059 if (param->getType() == Context.UnknownAnyTy) {
6060 Match = false;
6061 break;
6062 }
George Burgess IV45461812015-10-11 20:13:20 +00006063
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006064 ImplicitConversionSequence ConversionState
6065 = TryCopyInitialization(*this, argExpr, param->getType(),
6066 /*SuppressUserConversions*/false,
6067 /*InOverloadResolution=*/true,
6068 /*AllowObjCWritebackConversion=*/
6069 getLangOpts().ObjCAutoRefCount,
6070 /*AllowExplicit*/false);
George Burgess IV2099b542016-09-02 22:59:57 +00006071 // This function looks for a reasonably-exact match, so we consider
6072 // incompatible pointer conversions to be a failure here.
6073 if (ConversionState.isBad() ||
6074 (ConversionState.isStandard() &&
6075 ConversionState.Standard.Second ==
6076 ICK_Incompatible_Pointer_Conversion)) {
6077 Match = false;
6078 break;
6079 }
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006080 }
6081 // Promote additional arguments to variadic methods.
6082 if (Match && Method->isVariadic()) {
6083 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6084 if (Args[i]->isTypeDependent()) {
6085 Match = false;
6086 break;
6087 }
6088 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6089 nullptr);
6090 if (Arg.isInvalid()) {
6091 Match = false;
6092 break;
6093 }
6094 }
Fariborz Jahanian180d76b2014-08-27 16:38:47 +00006095 } else {
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006096 // Check for extra arguments to non-variadic methods.
6097 if (Args.size() != NumNamedArgs)
6098 Match = false;
Fariborz Jahanian180d76b2014-08-27 16:38:47 +00006099 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6100 // Special case when selectors have no argument. In this case, select
6101 // one with the most general result type of 'id'.
6102 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6103 QualType ReturnT = Methods[b]->getReturnType();
6104 if (ReturnT->isObjCIdType())
6105 return Methods[b];
6106 }
6107 }
6108 }
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006109
6110 if (Match)
6111 return Method;
6112 }
6113 return nullptr;
6114}
6115
George Burgess IV2a6150d2015-10-16 01:17:38 +00006116// specific_attr_iterator iterates over enable_if attributes in reverse, and
6117// enable_if is order-sensitive. As a result, we need to reverse things
6118// sometimes. Size of 4 elements is arbitrary.
6119static SmallVector<EnableIfAttr *, 4>
6120getOrderedEnableIfAttrs(const FunctionDecl *Function) {
6121 SmallVector<EnableIfAttr *, 4> Result;
6122 if (!Function->hasAttrs())
6123 return Result;
6124
6125 const auto &FuncAttrs = Function->getAttrs();
6126 for (Attr *Attr : FuncAttrs)
6127 if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr))
6128 Result.push_back(EnableIf);
6129
6130 std::reverse(Result.begin(), Result.end());
6131 return Result;
6132}
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006133
George Burgess IV177399e2017-01-09 04:12:14 +00006134static bool
6135convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg,
6136 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap,
6137 bool MissingImplicitThis, Expr *&ConvertedThis,
6138 SmallVectorImpl<Expr *> &ConvertedArgs) {
6139 if (ThisArg) {
6140 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6141 assert(!isa<CXXConstructorDecl>(Method) &&
6142 "Shouldn't have `this` for ctors!");
6143 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
6144 ExprResult R = S.PerformObjectArgumentInitialization(
6145 ThisArg, /*Qualifier=*/nullptr, Method, Method);
6146 if (R.isInvalid())
6147 return false;
6148 ConvertedThis = R.get();
6149 } else {
6150 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
6151 (void)MD;
6152 assert((MissingImplicitThis || MD->isStatic() ||
6153 isa<CXXConstructorDecl>(MD)) &&
6154 "Expected `this` for non-ctor instance methods");
6155 }
6156 ConvertedThis = nullptr;
6157 }
Nick Lewyckye283c552015-08-25 22:33:16 +00006158
George Burgess IV458b3f32016-08-12 04:19:35 +00006159 // Ignore any variadic arguments. Converting them is pointless, since the
George Burgess IV177399e2017-01-09 04:12:14 +00006160 // user can't refer to them in the function condition.
George Burgess IV53b938d2016-08-12 04:12:31 +00006161 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6162
Nick Lewyckye283c552015-08-25 22:33:16 +00006163 // Convert the arguments.
George Burgess IV53b938d2016-08-12 04:12:31 +00006164 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
George Burgess IVe96abf72016-02-24 22:31:14 +00006165 ExprResult R;
George Burgess IV177399e2017-01-09 04:12:14 +00006166 R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6167 S.Context, Function->getParamDecl(I)),
George Burgess IVe96abf72016-02-24 22:31:14 +00006168 SourceLocation(), Args[I]);
George Burgess IVe96abf72016-02-24 22:31:14 +00006169
George Burgess IV177399e2017-01-09 04:12:14 +00006170 if (R.isInvalid())
6171 return false;
George Burgess IVe96abf72016-02-24 22:31:14 +00006172
George Burgess IVe96abf72016-02-24 22:31:14 +00006173 ConvertedArgs.push_back(R.get());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006174 }
6175
George Burgess IV177399e2017-01-09 04:12:14 +00006176 if (Trap.hasErrorOccurred())
6177 return false;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006178
Nick Lewyckye283c552015-08-25 22:33:16 +00006179 // Push default arguments if needed.
6180 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6181 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6182 ParmVarDecl *P = Function->getParamDecl(i);
George Burgess IV177399e2017-01-09 04:12:14 +00006183 ExprResult R = S.PerformCopyInitialization(
6184 InitializedEntity::InitializeParameter(S.Context,
Nick Lewyckye283c552015-08-25 22:33:16 +00006185 Function->getParamDecl(i)),
6186 SourceLocation(),
6187 P->hasUninstantiatedDefaultArg() ? P->getUninstantiatedDefaultArg()
6188 : P->getDefaultArg());
George Burgess IV177399e2017-01-09 04:12:14 +00006189 if (R.isInvalid())
6190 return false;
Nick Lewyckye283c552015-08-25 22:33:16 +00006191 ConvertedArgs.push_back(R.get());
6192 }
6193
George Burgess IV177399e2017-01-09 04:12:14 +00006194 if (Trap.hasErrorOccurred())
6195 return false;
Nick Lewyckye283c552015-08-25 22:33:16 +00006196 }
George Burgess IV177399e2017-01-09 04:12:14 +00006197 return true;
6198}
6199
6200EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
6201 bool MissingImplicitThis) {
6202 SmallVector<EnableIfAttr *, 4> EnableIfAttrs =
6203 getOrderedEnableIfAttrs(Function);
6204 if (EnableIfAttrs.empty())
6205 return nullptr;
6206
6207 SFINAETrap Trap(*this);
6208 SmallVector<Expr *, 16> ConvertedArgs;
6209 // FIXME: We should look into making enable_if late-parsed.
6210 Expr *DiscardedThis;
6211 if (!convertArgsForAvailabilityChecks(
6212 *this, Function, /*ThisArg=*/nullptr, Args, Trap,
6213 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
6214 return EnableIfAttrs[0];
Nick Lewyckye283c552015-08-25 22:33:16 +00006215
George Burgess IV2a6150d2015-10-16 01:17:38 +00006216 for (auto *EIA : EnableIfAttrs) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006217 APValue Result;
George Burgess IVe8f10cc2016-05-11 01:38:27 +00006218 // FIXME: This doesn't consider value-dependent cases, because doing so is
6219 // very difficult. Ideally, we should handle them more gracefully.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006220 if (!EIA->getCond()->EvaluateWithSubstitution(
George Burgess IVe8f10cc2016-05-11 01:38:27 +00006221 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006222 return EIA;
George Burgess IVe8f10cc2016-05-11 01:38:27 +00006223
6224 if (!Result.isInt() || !Result.getInt().getBoolValue())
6225 return EIA;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006226 }
Craig Topperc3ec1492014-05-26 06:22:03 +00006227 return nullptr;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006228}
6229
George Burgess IV177399e2017-01-09 04:12:14 +00006230template <typename CheckFn>
George Burgess IVce6284b2017-01-28 02:19:40 +00006231static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const FunctionDecl *FD,
6232 bool ArgDependent, SourceLocation Loc,
6233 CheckFn &&IsSuccessful) {
6234 SmallVector<const DiagnoseIfAttr *, 8> Attrs;
6235 for (const auto *DIA : FD->specific_attrs<DiagnoseIfAttr>()) {
6236 if (ArgDependent == DIA->getArgDependent())
6237 Attrs.push_back(DIA);
6238 }
6239
6240 // Common case: No diagnose_if attributes, so we can quit early.
6241 if (Attrs.empty())
6242 return false;
6243
6244 auto WarningBegin = std::stable_partition(
6245 Attrs.begin(), Attrs.end(),
6246 [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
6247
George Burgess IV177399e2017-01-09 04:12:14 +00006248 // Note that diagnose_if attributes are late-parsed, so they appear in the
6249 // correct order (unlike enable_if attributes).
George Burgess IVce6284b2017-01-28 02:19:40 +00006250 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
6251 IsSuccessful);
6252 if (ErrAttr != WarningBegin) {
6253 const DiagnoseIfAttr *DIA = *ErrAttr;
6254 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
6255 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6256 << DIA->getParent() << DIA->getCond()->getSourceRange();
6257 return true;
6258 }
George Burgess IV177399e2017-01-09 04:12:14 +00006259
George Burgess IVce6284b2017-01-28 02:19:40 +00006260 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
6261 if (IsSuccessful(DIA)) {
6262 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
6263 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6264 << DIA->getParent() << DIA->getCond()->getSourceRange();
6265 }
6266
6267 return false;
George Burgess IV177399e2017-01-09 04:12:14 +00006268}
6269
George Burgess IVce6284b2017-01-28 02:19:40 +00006270bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
6271 const Expr *ThisArg,
6272 ArrayRef<const Expr *> Args,
6273 SourceLocation Loc) {
6274 return diagnoseDiagnoseIfAttrsWith(
6275 *this, Function, /*ArgDependent=*/true, Loc,
6276 [&](const DiagnoseIfAttr *DIA) {
6277 APValue Result;
6278 // It's sane to use the same Args for any redecl of this function, since
6279 // EvaluateWithSubstitution only cares about the position of each
6280 // argument in the arg list, not the ParmVarDecl* it maps to.
6281 if (!DIA->getCond()->EvaluateWithSubstitution(
6282 Result, Context, DIA->getParent(), Args, ThisArg))
6283 return false;
6284 return Result.isInt() && Result.getInt().getBoolValue();
6285 });
George Burgess IV177399e2017-01-09 04:12:14 +00006286}
6287
George Burgess IVce6284b2017-01-28 02:19:40 +00006288bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const FunctionDecl *Function,
6289 SourceLocation Loc) {
6290 return diagnoseDiagnoseIfAttrsWith(
6291 *this, Function, /*ArgDependent=*/false, Loc,
6292 [&](const DiagnoseIfAttr *DIA) {
6293 bool Result;
6294 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
6295 Result;
6296 });
George Burgess IV177399e2017-01-09 04:12:14 +00006297}
6298
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006299/// \brief Add all of the function declarations in the given function set to
Nick Lewyckyed4265c2013-09-22 10:06:01 +00006300/// the overload candidate set.
John McCall4c4c1df2010-01-26 03:27:55 +00006301void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006302 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006303 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006304 TemplateArgumentListInfo *ExplicitTemplateArgs,
Richard Smithbcc22fc2012-03-09 08:00:36 +00006305 bool SuppressUserConversions,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006306 bool PartialOverloading) {
John McCall4c4c1df2010-01-26 03:27:55 +00006307 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00006308 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6309 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006310 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00006311 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00006312 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00006313 Args[0]->getType(), Args[0]->Classify(Context),
George Burgess IVce6284b2017-01-28 02:19:40 +00006314 Args.slice(1), CandidateSet, SuppressUserConversions,
6315 PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006316 else
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006317 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006318 SuppressUserConversions, PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006319 } else {
John McCalla0296f72010-03-19 07:35:19 +00006320 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006321 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
6322 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
George Burgess IV177399e2017-01-09 04:12:14 +00006323 AddMethodTemplateCandidate(
6324 FunTmpl, F.getPair(),
6325 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
6326 ExplicitTemplateArgs, Args[0]->getType(),
George Burgess IVce6284b2017-01-28 02:19:40 +00006327 Args[0]->Classify(Context), Args.slice(1), CandidateSet,
George Burgess IV177399e2017-01-09 04:12:14 +00006328 SuppressUserConversions, PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006329 else
John McCalla0296f72010-03-19 07:35:19 +00006330 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smithbcc22fc2012-03-09 08:00:36 +00006331 ExplicitTemplateArgs, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006332 CandidateSet, SuppressUserConversions,
6333 PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006334 }
Douglas Gregor15448f82009-06-27 21:05:07 +00006335 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006336}
6337
John McCallf0f1cf02009-11-17 07:50:12 +00006338/// AddMethodCandidate - Adds a named decl (which is some kind of
6339/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00006340void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006341 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006342 Expr::Classification ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00006343 ArrayRef<Expr *> Args,
John McCallf0f1cf02009-11-17 07:50:12 +00006344 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006345 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00006346 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00006347 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00006348
6349 if (isa<UsingShadowDecl>(Decl))
6350 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006351
John McCallf0f1cf02009-11-17 07:50:12 +00006352 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6353 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6354 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00006355 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
George Burgess IVce6284b2017-01-28 02:19:40 +00006356 /*ExplicitArgs*/ nullptr, ObjectType,
6357 ObjectClassification, Args, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006358 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00006359 } else {
John McCalla0296f72010-03-19 07:35:19 +00006360 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
George Burgess IVce6284b2017-01-28 02:19:40 +00006361 ObjectType, ObjectClassification, Args, CandidateSet,
6362 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00006363 }
6364}
6365
Douglas Gregor436424c2008-11-18 23:14:02 +00006366/// AddMethodCandidate - Adds the given C++ member function to the set
6367/// of candidate functions, using the given function call arguments
6368/// and the object argument (@c Object). For example, in a call
6369/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6370/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6371/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00006372/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00006373void
John McCalla0296f72010-03-19 07:35:19 +00006374Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00006375 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006376 Expr::Classification ObjectClassification,
George Burgess IVce6284b2017-01-28 02:19:40 +00006377 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006378 OverloadCandidateSet &CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006379 bool SuppressUserConversions,
Richard Smith6eedfe72017-01-09 08:01:21 +00006380 bool PartialOverloading,
6381 ConversionSequenceList EarlyConversions) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006382 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00006383 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00006384 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00006385 assert(!isa<CXXConstructorDecl>(Method) &&
6386 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00006387
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006388 if (!CandidateSet.isNewCandidate(Method))
6389 return;
6390
Richard Smith8b86f2d2013-11-04 01:48:18 +00006391 // C++11 [class.copy]p23: [DR1402]
6392 // A defaulted move assignment operator that is defined as deleted is
6393 // ignored by overload resolution.
6394 if (Method->isDefaulted() && Method->isDeleted() &&
6395 Method->isMoveAssignmentOperator())
6396 return;
6397
Douglas Gregor27381f32009-11-23 12:27:39 +00006398 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006399 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006400
Douglas Gregor436424c2008-11-18 23:14:02 +00006401 // Add this candidate
Richard Smith6eedfe72017-01-09 08:01:21 +00006402 OverloadCandidate &Candidate =
6403 CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
John McCalla0296f72010-03-19 07:35:19 +00006404 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00006405 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006406 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006407 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006408 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor436424c2008-11-18 23:14:02 +00006409
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006410 unsigned NumParams = Proto->getNumParams();
Douglas Gregor436424c2008-11-18 23:14:02 +00006411
6412 // (C++ 13.3.2p2): A candidate function having fewer than m
6413 // parameters is viable only if it has an ellipsis in its parameter
6414 // list (8.3.5).
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006415 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6416 !Proto->isVariadic()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006417 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006418 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00006419 return;
6420 }
6421
6422 // (C++ 13.3.2p2): A candidate function having more than m parameters
6423 // is viable only if the (m+1)st parameter has a default argument
6424 // (8.3.6). For the purposes of overload resolution, the
6425 // parameter list is truncated on the right, so that there are
6426 // exactly m parameters.
6427 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006428 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006429 // Not enough arguments.
6430 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006431 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00006432 return;
6433 }
6434
6435 Candidate.Viable = true;
Douglas Gregor436424c2008-11-18 23:14:02 +00006436
John McCall6e9f8f62009-12-03 04:06:58 +00006437 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006438 // The implicit object argument is ignored.
6439 Candidate.IgnoreObjectArgument = true;
6440 else {
6441 // Determine the implicit conversion sequence for the object
6442 // parameter.
Richard Smith0f59cb32015-12-18 21:45:41 +00006443 Candidate.Conversions[0] = TryObjectArgumentInitialization(
6444 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6445 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00006446 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006447 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006448 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006449 return;
6450 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006451 }
6452
Eli Bendersky291a57e2014-09-25 23:59:08 +00006453 // (CUDA B.1): Check for invalid calls between targets.
6454 if (getLangOpts().CUDA)
6455 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
Justin Lebarb0080032016-08-10 01:09:11 +00006456 if (!IsAllowedCUDACall(Caller, Method)) {
Eli Bendersky291a57e2014-09-25 23:59:08 +00006457 Candidate.Viable = false;
6458 Candidate.FailureKind = ovl_fail_bad_target;
6459 return;
6460 }
6461
Douglas Gregor436424c2008-11-18 23:14:02 +00006462 // Determine the implicit conversion sequences for each of the
6463 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006464 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Richard Smith6eedfe72017-01-09 08:01:21 +00006465 if (Candidate.Conversions[ArgIdx + 1].isInitialized()) {
6466 // We already formed a conversion sequence for this parameter during
6467 // template argument deduction.
6468 } else if (ArgIdx < NumParams) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006469 // (C++ 13.3.2p3): for F to be a viable function, there shall
6470 // exist for each argument an implicit conversion sequence
6471 // (13.3.3.1) that converts that argument to the corresponding
6472 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00006473 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00006474 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006475 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006476 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00006477 /*InOverloadResolution=*/true,
6478 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006479 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00006480 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006481 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006482 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006483 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00006484 }
6485 } else {
6486 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6487 // argument for which there is no corresponding parameter is
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006488 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006489 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00006490 }
6491 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006492
6493 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6494 Candidate.Viable = false;
6495 Candidate.FailureKind = ovl_fail_enable_if;
6496 Candidate.DeductionFailure.Data = FailedAttr;
6497 return;
6498 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006499}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006500
Douglas Gregor97628d62009-08-21 00:16:32 +00006501/// \brief Add a C++ member function template as a candidate to the candidate
6502/// set, using template argument deduction to produce an appropriate member
6503/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00006504void
Douglas Gregor97628d62009-08-21 00:16:32 +00006505Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00006506 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006507 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006508 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006509 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006510 Expr::Classification ObjectClassification,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006511 ArrayRef<Expr *> Args,
Douglas Gregor97628d62009-08-21 00:16:32 +00006512 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006513 bool SuppressUserConversions,
6514 bool PartialOverloading) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006515 if (!CandidateSet.isNewCandidate(MethodTmpl))
6516 return;
6517
Douglas Gregor97628d62009-08-21 00:16:32 +00006518 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00006519 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00006520 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00006521 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00006522 // candidate functions in the usual way.113) A given name can refer to one
6523 // or more function templates and also to a set of overloaded non-template
6524 // functions. In such a case, the candidate functions generated from each
6525 // function template are combined with the set of non-template candidate
6526 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00006527 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006528 FunctionDecl *Specialization = nullptr;
Richard Smith6eedfe72017-01-09 08:01:21 +00006529 ConversionSequenceList Conversions;
6530 if (TemplateDeductionResult Result = DeduceTemplateArguments(
6531 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
6532 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6533 return CheckNonDependentConversions(
6534 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
6535 SuppressUserConversions, ActingContext, ObjectType,
6536 ObjectClassification);
6537 })) {
6538 OverloadCandidate &Candidate =
6539 CandidateSet.addCandidate(Conversions.size(), Conversions);
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006540 Candidate.FoundDecl = FoundDecl;
6541 Candidate.Function = MethodTmpl->getTemplatedDecl();
6542 Candidate.Viable = false;
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006543 Candidate.IsSurrogate = false;
Richard Smith9d05e152017-01-10 20:52:50 +00006544 Candidate.IgnoreObjectArgument =
6545 cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
6546 ObjectType.isNull();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006547 Candidate.ExplicitCallArguments = Args.size();
Richard Smith6eedfe72017-01-09 08:01:21 +00006548 if (Result == TDK_NonDependentConversionFailure)
6549 Candidate.FailureKind = ovl_fail_bad_conversion;
6550 else {
6551 Candidate.FailureKind = ovl_fail_bad_deduction;
6552 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6553 Info);
6554 }
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006555 return;
6556 }
Mike Stump11289f42009-09-09 15:08:12 +00006557
Douglas Gregor97628d62009-08-21 00:16:32 +00006558 // Add the function template specialization produced by template argument
6559 // deduction as a candidate.
6560 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00006561 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00006562 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00006563 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
George Burgess IVce6284b2017-01-28 02:19:40 +00006564 ActingContext, ObjectType, ObjectClassification, Args,
6565 CandidateSet, SuppressUserConversions, PartialOverloading,
6566 Conversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00006567}
6568
Douglas Gregor05155d82009-08-21 23:19:43 +00006569/// \brief Add a C++ function template specialization as a candidate
6570/// in the candidate set, using template argument deduction to produce
6571/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00006572void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006573Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00006574 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006575 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006576 ArrayRef<Expr *> Args,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006577 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006578 bool SuppressUserConversions,
6579 bool PartialOverloading) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006580 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6581 return;
6582
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006583 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00006584 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006585 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00006586 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006587 // candidate functions in the usual way.113) A given name can refer to one
6588 // or more function templates and also to a set of overloaded non-template
6589 // functions. In such a case, the candidate functions generated from each
6590 // function template are combined with the set of non-template candidate
6591 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00006592 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006593 FunctionDecl *Specialization = nullptr;
Richard Smith6eedfe72017-01-09 08:01:21 +00006594 ConversionSequenceList Conversions;
6595 if (TemplateDeductionResult Result = DeduceTemplateArguments(
6596 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
6597 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6598 return CheckNonDependentConversions(FunctionTemplate, ParamTypes,
6599 Args, CandidateSet, Conversions,
6600 SuppressUserConversions);
6601 })) {
6602 OverloadCandidate &Candidate =
6603 CandidateSet.addCandidate(Conversions.size(), Conversions);
John McCalla0296f72010-03-19 07:35:19 +00006604 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00006605 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6606 Candidate.Viable = false;
6607 Candidate.IsSurrogate = false;
Richard Smith9d05e152017-01-10 20:52:50 +00006608 // Ignore the object argument if there is one, since we don't have an object
6609 // type.
6610 Candidate.IgnoreObjectArgument =
6611 isa<CXXMethodDecl>(Candidate.Function) &&
6612 !isa<CXXConstructorDecl>(Candidate.Function);
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006613 Candidate.ExplicitCallArguments = Args.size();
Richard Smith6eedfe72017-01-09 08:01:21 +00006614 if (Result == TDK_NonDependentConversionFailure)
6615 Candidate.FailureKind = ovl_fail_bad_conversion;
6616 else {
6617 Candidate.FailureKind = ovl_fail_bad_deduction;
6618 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6619 Info);
6620 }
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006621 return;
6622 }
Mike Stump11289f42009-09-09 15:08:12 +00006623
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006624 // Add the function template specialization produced by template argument
6625 // deduction as a candidate.
6626 assert(Specialization && "Missing function template specialization?");
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006627 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Richard Smith6eedfe72017-01-09 08:01:21 +00006628 SuppressUserConversions, PartialOverloading,
6629 /*AllowExplicit*/false, Conversions);
6630}
6631
6632/// Check that implicit conversion sequences can be formed for each argument
6633/// whose corresponding parameter has a non-dependent type, per DR1391's
6634/// [temp.deduct.call]p10.
6635bool Sema::CheckNonDependentConversions(
6636 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
6637 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
6638 ConversionSequenceList &Conversions, bool SuppressUserConversions,
6639 CXXRecordDecl *ActingContext, QualType ObjectType,
6640 Expr::Classification ObjectClassification) {
6641 // FIXME: The cases in which we allow explicit conversions for constructor
6642 // arguments never consider calling a constructor template. It's not clear
6643 // that is correct.
6644 const bool AllowExplicit = false;
6645
6646 auto *FD = FunctionTemplate->getTemplatedDecl();
6647 auto *Method = dyn_cast<CXXMethodDecl>(FD);
6648 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
6649 unsigned ThisConversions = HasThisConversion ? 1 : 0;
6650
6651 Conversions =
6652 CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
6653
6654 // Overload resolution is always an unevaluated context.
6655 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6656
6657 // For a method call, check the 'this' conversion here too. DR1391 doesn't
6658 // require that, but this check should never result in a hard error, and
6659 // overload resolution is permitted to sidestep instantiations.
6660 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
6661 !ObjectType.isNull()) {
6662 Conversions[0] = TryObjectArgumentInitialization(
6663 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6664 Method, ActingContext);
6665 if (Conversions[0].isBad())
6666 return true;
6667 }
6668
6669 for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N;
6670 ++I) {
6671 QualType ParamType = ParamTypes[I];
6672 if (!ParamType->isDependentType()) {
6673 Conversions[ThisConversions + I]
6674 = TryCopyInitialization(*this, Args[I], ParamType,
6675 SuppressUserConversions,
6676 /*InOverloadResolution=*/true,
6677 /*AllowObjCWritebackConversion=*/
6678 getLangOpts().ObjCAutoRefCount,
6679 AllowExplicit);
6680 if (Conversions[ThisConversions + I].isBad())
6681 return true;
6682 }
6683 }
6684
6685 return false;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006686}
Mike Stump11289f42009-09-09 15:08:12 +00006687
Douglas Gregor4b60a152013-11-07 22:34:54 +00006688/// Determine whether this is an allowable conversion from the result
6689/// of an explicit conversion operator to the expected type, per C++
6690/// [over.match.conv]p1 and [over.match.ref]p1.
6691///
6692/// \param ConvType The return type of the conversion function.
6693///
6694/// \param ToType The type we are converting to.
6695///
6696/// \param AllowObjCPointerConversion Allow a conversion from one
6697/// Objective-C pointer to another.
6698///
6699/// \returns true if the conversion is allowable, false otherwise.
6700static bool isAllowableExplicitConversion(Sema &S,
6701 QualType ConvType, QualType ToType,
6702 bool AllowObjCPointerConversion) {
6703 QualType ToNonRefType = ToType.getNonReferenceType();
6704
6705 // Easy case: the types are the same.
6706 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6707 return true;
6708
6709 // Allow qualification conversions.
6710 bool ObjCLifetimeConversion;
6711 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6712 ObjCLifetimeConversion))
6713 return true;
6714
6715 // If we're not allowed to consider Objective-C pointer conversions,
6716 // we're done.
6717 if (!AllowObjCPointerConversion)
6718 return false;
6719
6720 // Is this an Objective-C pointer conversion?
6721 bool IncompatibleObjC = false;
6722 QualType ConvertedType;
6723 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6724 IncompatibleObjC);
6725}
6726
Douglas Gregora1f013e2008-11-07 22:36:19 +00006727/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00006728/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00006729/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00006730/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00006731/// (which may or may not be the same type as the type that the
6732/// conversion function produces).
6733void
6734Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006735 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006736 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00006737 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006738 OverloadCandidateSet& CandidateSet,
6739 bool AllowObjCConversionOnExplicit) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006740 assert(!Conversion->getDescribedFunctionTemplate() &&
6741 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00006742 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006743 if (!CandidateSet.isNewCandidate(Conversion))
6744 return;
6745
Richard Smith2a7d4812013-05-04 07:00:32 +00006746 // If the conversion function has an undeduced return type, trigger its
6747 // deduction now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006748 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00006749 if (DeduceReturnType(Conversion, From->getExprLoc()))
6750 return;
6751 ConvType = Conversion->getConversionType().getNonReferenceType();
6752 }
6753
Richard Smith089c3162013-09-21 21:55:46 +00006754 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6755 // operator is only a candidate if its return type is the target type or
6756 // can be converted to the target type with a qualification conversion.
Douglas Gregor4b60a152013-11-07 22:34:54 +00006757 if (Conversion->isExplicit() &&
6758 !isAllowableExplicitConversion(*this, ConvType, ToType,
6759 AllowObjCConversionOnExplicit))
Richard Smith089c3162013-09-21 21:55:46 +00006760 return;
6761
Douglas Gregor27381f32009-11-23 12:27:39 +00006762 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006763 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006764
Douglas Gregora1f013e2008-11-07 22:36:19 +00006765 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006766 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCalla0296f72010-03-19 07:35:19 +00006767 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006768 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006769 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006770 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006771 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00006772 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00006773 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00006774 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006775 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006776
Douglas Gregor6affc782010-08-19 15:37:02 +00006777 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006778 // For conversion functions, the function is considered to be a member of
6779 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00006780 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006781 //
6782 // Determine the implicit conversion sequence for the implicit
6783 // object parameter.
6784 QualType ImplicitParamType = From->getType();
6785 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6786 ImplicitParamType = FromPtrType->getPointeeType();
6787 CXXRecordDecl *ConversionContext
6788 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006789
Richard Smith0f59cb32015-12-18 21:45:41 +00006790 Candidate.Conversions[0] = TryObjectArgumentInitialization(
6791 *this, CandidateSet.getLocation(), From->getType(),
6792 From->Classify(Context), Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006793
John McCall0d1da222010-01-12 00:44:57 +00006794 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006795 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006796 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006797 return;
6798 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006799
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006800 // We won't go through a user-defined type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006801 // derived to base as such conversions are given Conversion Rank. They only
6802 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6803 QualType FromCanon
6804 = Context.getCanonicalType(From->getType().getUnqualifiedType());
6805 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
Richard Smith0f59cb32015-12-18 21:45:41 +00006806 if (FromCanon == ToCanon ||
6807 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006808 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006809 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006810 return;
6811 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006812
Douglas Gregora1f013e2008-11-07 22:36:19 +00006813 // To determine what the conversion from the result of calling the
6814 // conversion function to the type we're eventually trying to
6815 // convert to (ToType), we need to synthesize a call to the
6816 // conversion function and attempt copy initialization from it. This
6817 // makes sure that we get the right semantics with respect to
6818 // lvalues/rvalues and the type. Fortunately, we can allocate this
6819 // call on the stack and we don't need its arguments to be
6820 // well-formed.
John McCall113bee02012-03-10 09:33:50 +00006821 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00006822 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00006823 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6824 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00006825 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00006826 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00006827
Richard Smith48d24642011-07-13 22:53:21 +00006828 QualType ConversionType = Conversion->getConversionType();
Richard Smithdb0ac552015-12-18 22:40:25 +00006829 if (!isCompleteType(From->getLocStart(), ConversionType)) {
Douglas Gregor72ebdab2010-11-13 19:36:57 +00006830 Candidate.Viable = false;
6831 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6832 return;
6833 }
6834
Richard Smith48d24642011-07-13 22:53:21 +00006835 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCall7decc9e2010-11-18 06:31:45 +00006836
Mike Stump11289f42009-09-09 15:08:12 +00006837 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00006838 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6839 // allocator).
Richard Smith48d24642011-07-13 22:53:21 +00006840 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00006841 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00006842 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00006843 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006844 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00006845 /*SuppressUserConversions=*/true,
John McCall31168b02011-06-15 23:02:42 +00006846 /*InOverloadResolution=*/false,
6847 /*AllowObjCWritebackConversion=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00006848
John McCall0d1da222010-01-12 00:44:57 +00006849 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006850 case ImplicitConversionSequence::StandardConversion:
6851 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006852
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006853 // C++ [over.ics.user]p3:
6854 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006855 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006856 // shall have exact match rank.
6857 if (Conversion->getPrimaryTemplate() &&
6858 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6859 Candidate.Viable = false;
6860 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006861 return;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006862 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006863
Douglas Gregorcba72b12011-01-21 05:18:22 +00006864 // C++0x [dcl.init.ref]p5:
6865 // In the second case, if the reference is an rvalue reference and
6866 // the second standard conversion sequence of the user-defined
6867 // conversion sequence includes an lvalue-to-rvalue conversion, the
6868 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006869 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00006870 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6871 Candidate.Viable = false;
6872 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006873 return;
Douglas Gregorcba72b12011-01-21 05:18:22 +00006874 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00006875 break;
6876
6877 case ImplicitConversionSequence::BadConversion:
6878 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006879 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006880 return;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006881
6882 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006883 llvm_unreachable(
Douglas Gregora1f013e2008-11-07 22:36:19 +00006884 "Can only end up with a standard conversion sequence or failure");
6885 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006886
Craig Topper5fc8fc22014-08-27 06:28:36 +00006887 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006888 Candidate.Viable = false;
6889 Candidate.FailureKind = ovl_fail_enable_if;
6890 Candidate.DeductionFailure.Data = FailedAttr;
6891 return;
6892 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00006893}
6894
Douglas Gregor05155d82009-08-21 23:19:43 +00006895/// \brief Adds a conversion function template specialization
6896/// candidate to the overload set, using template argument deduction
6897/// to deduce the template arguments of the conversion function
6898/// template from the type that we are converting to (C++
6899/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00006900void
Douglas Gregor05155d82009-08-21 23:19:43 +00006901Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00006902 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006903 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00006904 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006905 OverloadCandidateSet &CandidateSet,
6906 bool AllowObjCConversionOnExplicit) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006907 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
6908 "Only conversion function templates permitted here");
6909
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006910 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6911 return;
6912
Craig Toppere6706e42012-09-19 02:26:47 +00006913 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006914 CXXConversionDecl *Specialization = nullptr;
Douglas Gregor05155d82009-08-21 23:19:43 +00006915 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00006916 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00006917 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006918 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006919 Candidate.FoundDecl = FoundDecl;
6920 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6921 Candidate.Viable = false;
6922 Candidate.FailureKind = ovl_fail_bad_deduction;
6923 Candidate.IsSurrogate = false;
6924 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006925 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006926 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006927 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00006928 return;
6929 }
Mike Stump11289f42009-09-09 15:08:12 +00006930
Douglas Gregor05155d82009-08-21 23:19:43 +00006931 // Add the conversion function template specialization produced by
6932 // template argument deduction as a candidate.
6933 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00006934 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006935 CandidateSet, AllowObjCConversionOnExplicit);
Douglas Gregor05155d82009-08-21 23:19:43 +00006936}
6937
Douglas Gregorab7897a2008-11-19 22:57:39 +00006938/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
6939/// converts the given @c Object to a function pointer via the
6940/// conversion function @c Conversion, and then attempts to call it
6941/// with the given arguments (C++ [over.call.object]p2-4). Proto is
6942/// the type of function that we'll eventually be calling.
6943void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006944 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006945 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006946 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00006947 Expr *Object,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006948 ArrayRef<Expr *> Args,
Douglas Gregorab7897a2008-11-19 22:57:39 +00006949 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006950 if (!CandidateSet.isNewCandidate(Conversion))
6951 return;
6952
Douglas Gregor27381f32009-11-23 12:27:39 +00006953 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006954 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006955
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006956 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00006957 Candidate.FoundDecl = FoundDecl;
Craig Topperc3ec1492014-05-26 06:22:03 +00006958 Candidate.Function = nullptr;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006959 Candidate.Surrogate = Conversion;
6960 Candidate.Viable = true;
6961 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006962 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006963 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006964
6965 // Determine the implicit conversion sequence for the implicit
6966 // object parameter.
Richard Smith0f59cb32015-12-18 21:45:41 +00006967 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
6968 *this, CandidateSet.getLocation(), Object->getType(),
6969 Object->Classify(Context), Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00006970 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006971 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006972 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00006973 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006974 return;
6975 }
6976
6977 // The first conversion is actually a user-defined conversion whose
6978 // first conversion is ObjectInit's standard conversion (which is
6979 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00006980 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006981 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00006982 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006983 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006984 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00006985 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump11289f42009-09-09 15:08:12 +00006986 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00006987 = Candidate.Conversions[0].UserDefined.Before;
6988 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
6989
Mike Stump11289f42009-09-09 15:08:12 +00006990 // Find the
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006991 unsigned NumParams = Proto->getNumParams();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006992
6993 // (C++ 13.3.2p2): A candidate function having fewer than m
6994 // parameters is viable only if it has an ellipsis in its parameter
6995 // list (8.3.5).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006996 if (Args.size() > NumParams && !Proto->isVariadic()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006997 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006998 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006999 return;
7000 }
7001
7002 // Function types don't have any default arguments, so just check if
7003 // we have enough arguments.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00007004 if (Args.size() < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00007005 // Not enough arguments.
7006 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00007007 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00007008 return;
7009 }
7010
7011 // Determine the implicit conversion sequences for each of the
7012 // arguments.
Richard Smithe54c3072013-05-05 15:51:06 +00007013 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00007014 if (ArgIdx < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00007015 // (C++ 13.3.2p3): for F to be a viable function, there shall
7016 // exist for each argument an implicit conversion sequence
7017 // (13.3.3.1) that converts that argument to the corresponding
7018 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00007019 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00007020 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00007021 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00007022 /*SuppressUserConversions=*/false,
John McCall31168b02011-06-15 23:02:42 +00007023 /*InOverloadResolution=*/false,
7024 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00007025 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00007026 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00007027 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00007028 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007029 return;
Douglas Gregorab7897a2008-11-19 22:57:39 +00007030 }
7031 } else {
7032 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7033 // argument for which there is no corresponding parameter is
7034 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00007035 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00007036 }
7037 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007038
Craig Topper5fc8fc22014-08-27 06:28:36 +00007039 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007040 Candidate.Viable = false;
7041 Candidate.FailureKind = ovl_fail_enable_if;
7042 Candidate.DeductionFailure.Data = FailedAttr;
7043 return;
7044 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00007045}
7046
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007047/// \brief Add overload candidates for overloaded operators that are
7048/// member functions.
7049///
7050/// Add the overloaded operator candidates that are member functions
7051/// for the operator Op that was used in an operator expression such
7052/// as "x Op y". , Args/NumArgs provides the operator arguments, and
7053/// CandidateSet will store the added overload candidates. (C++
7054/// [over.match.oper]).
7055void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
7056 SourceLocation OpLoc,
Richard Smithe54c3072013-05-05 15:51:06 +00007057 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007058 OverloadCandidateSet& CandidateSet,
7059 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00007060 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7061
7062 // C++ [over.match.oper]p3:
7063 // For a unary operator @ with an operand of a type whose
7064 // cv-unqualified version is T1, and for a binary operator @ with
7065 // a left operand of a type whose cv-unqualified version is T1 and
7066 // a right operand of a type whose cv-unqualified version is T2,
7067 // three sets of candidate functions, designated member
7068 // candidates, non-member candidates and built-in candidates, are
7069 // constructed as follows:
7070 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00007071
Richard Smith0feaf0c2013-04-20 12:41:22 +00007072 // -- If T1 is a complete class type or a class currently being
7073 // defined, the set of member candidates is the result of the
7074 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
7075 // the set of member candidates is empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007076 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Richard Smith0feaf0c2013-04-20 12:41:22 +00007077 // Complete the type if it can be completed.
Richard Smithdb0ac552015-12-18 22:40:25 +00007078 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
Richard Smith82b8d4e2015-12-18 22:19:11 +00007079 return;
Richard Smith0feaf0c2013-04-20 12:41:22 +00007080 // If the type is neither complete nor being defined, bail out now.
7081 if (!T1Rec->getDecl()->getDefinition())
Douglas Gregor6a1f9652009-08-27 23:35:55 +00007082 return;
Mike Stump11289f42009-09-09 15:08:12 +00007083
John McCall27b18f82009-11-17 02:14:36 +00007084 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
7085 LookupQualifiedName(Operators, T1Rec->getDecl());
7086 Operators.suppressDiagnostics();
7087
Mike Stump11289f42009-09-09 15:08:12 +00007088 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00007089 OperEnd = Operators.end();
7090 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00007091 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00007092 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
George Burgess IVce6284b2017-01-28 02:19:40 +00007093 Args[0]->Classify(Context), Args.slice(1),
George Burgess IV177399e2017-01-09 04:12:14 +00007094 CandidateSet, /*SuppressUserConversions=*/false);
Douglas Gregor436424c2008-11-18 23:14:02 +00007095 }
Douglas Gregor436424c2008-11-18 23:14:02 +00007096}
7097
Douglas Gregora11693b2008-11-12 17:17:38 +00007098/// AddBuiltinCandidate - Add a candidate for a built-in
7099/// operator. ResultTy and ParamTys are the result and parameter types
7100/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00007101/// arguments being passed to the candidate. IsAssignmentOperator
7102/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00007103/// operator. NumContextualBoolArguments is the number of arguments
7104/// (at the beginning of the argument list) that will be contextually
7105/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00007106void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Richard Smithe54c3072013-05-05 15:51:06 +00007107 ArrayRef<Expr *> Args,
Douglas Gregorc5e61072009-01-13 00:52:54 +00007108 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00007109 bool IsAssignmentOperator,
7110 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00007111 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00007112 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00007113
Douglas Gregora11693b2008-11-12 17:17:38 +00007114 // Add this candidate
Richard Smithe54c3072013-05-05 15:51:06 +00007115 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
Craig Topperc3ec1492014-05-26 06:22:03 +00007116 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
7117 Candidate.Function = nullptr;
Douglas Gregor1d248c52008-12-12 02:00:36 +00007118 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007119 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00007120 Candidate.BuiltinTypes.ResultTy = ResultTy;
Richard Smithe54c3072013-05-05 15:51:06 +00007121 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Douglas Gregora11693b2008-11-12 17:17:38 +00007122 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
7123
7124 // Determine the implicit conversion sequences for each of the
7125 // arguments.
7126 Candidate.Viable = true;
Richard Smithe54c3072013-05-05 15:51:06 +00007127 Candidate.ExplicitCallArguments = Args.size();
7128 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00007129 // C++ [over.match.oper]p4:
7130 // For the built-in assignment operators, conversions of the
7131 // left operand are restricted as follows:
7132 // -- no temporaries are introduced to hold the left operand, and
7133 // -- no user-defined conversions are applied to the left
7134 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00007135 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00007136 //
7137 // We block these conversions by turning off user-defined
7138 // conversions, since that is the only way that initialization of
7139 // a reference to a non-class type can occur from something that
7140 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00007141 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00007142 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00007143 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00007144 Candidate.Conversions[ArgIdx]
7145 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00007146 } else {
Mike Stump11289f42009-09-09 15:08:12 +00007147 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00007148 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00007149 ArgIdx == 0 && IsAssignmentOperator,
John McCall31168b02011-06-15 23:02:42 +00007150 /*InOverloadResolution=*/false,
7151 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00007152 getLangOpts().ObjCAutoRefCount);
Douglas Gregor5fb53972009-01-14 15:45:31 +00007153 }
John McCall0d1da222010-01-12 00:44:57 +00007154 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007155 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00007156 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00007157 break;
7158 }
Douglas Gregora11693b2008-11-12 17:17:38 +00007159 }
7160}
7161
Craig Toppercd7b0332013-07-01 06:29:40 +00007162namespace {
7163
Douglas Gregora11693b2008-11-12 17:17:38 +00007164/// BuiltinCandidateTypeSet - A set of types that will be used for the
7165/// candidate operator functions for built-in operators (C++
7166/// [over.built]). The types are separated into pointer types and
7167/// enumeration types.
7168class BuiltinCandidateTypeSet {
7169 /// TypeSet - A set of types.
Richard Smith95853072016-03-25 00:08:53 +00007170 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
7171 llvm::SmallPtrSet<QualType, 8>> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00007172
7173 /// PointerTypes - The set of pointer types that will be used in the
7174 /// built-in candidates.
7175 TypeSet PointerTypes;
7176
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007177 /// MemberPointerTypes - The set of member pointer types that will be
7178 /// used in the built-in candidates.
7179 TypeSet MemberPointerTypes;
7180
Douglas Gregora11693b2008-11-12 17:17:38 +00007181 /// EnumerationTypes - The set of enumeration types that will be
7182 /// used in the built-in candidates.
7183 TypeSet EnumerationTypes;
7184
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007185 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007186 /// candidates.
7187 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00007188
7189 /// \brief A flag indicating non-record types are viable candidates
7190 bool HasNonRecordTypes;
7191
7192 /// \brief A flag indicating whether either arithmetic or enumeration types
7193 /// were present in the candidate set.
7194 bool HasArithmeticOrEnumeralTypes;
7195
Douglas Gregor80af3132011-05-21 23:15:46 +00007196 /// \brief A flag indicating whether the nullptr type was present in the
7197 /// candidate set.
7198 bool HasNullPtrType;
7199
Douglas Gregor8a2e6012009-08-24 15:23:48 +00007200 /// Sema - The semantic analysis instance where we are building the
7201 /// candidate type set.
7202 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00007203
Douglas Gregora11693b2008-11-12 17:17:38 +00007204 /// Context - The AST context in which we will build the type sets.
7205 ASTContext &Context;
7206
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007207 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7208 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007209 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00007210
7211public:
7212 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00007213 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00007214
Mike Stump11289f42009-09-09 15:08:12 +00007215 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00007216 : HasNonRecordTypes(false),
7217 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor80af3132011-05-21 23:15:46 +00007218 HasNullPtrType(false),
Chandler Carruth00a38332010-12-13 01:44:01 +00007219 SemaRef(SemaRef),
7220 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00007221
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007222 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007223 SourceLocation Loc,
7224 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007225 bool AllowExplicitConversions,
7226 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00007227
7228 /// pointer_begin - First pointer type found;
7229 iterator pointer_begin() { return PointerTypes.begin(); }
7230
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007231 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00007232 iterator pointer_end() { return PointerTypes.end(); }
7233
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007234 /// member_pointer_begin - First member pointer type found;
7235 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
7236
7237 /// member_pointer_end - Past the last member pointer type found;
7238 iterator member_pointer_end() { return MemberPointerTypes.end(); }
7239
Douglas Gregora11693b2008-11-12 17:17:38 +00007240 /// enumeration_begin - First enumeration type found;
7241 iterator enumeration_begin() { return EnumerationTypes.begin(); }
7242
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007243 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00007244 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007245
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007246 iterator vector_begin() { return VectorTypes.begin(); }
7247 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00007248
7249 bool hasNonRecordTypes() { return HasNonRecordTypes; }
7250 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor80af3132011-05-21 23:15:46 +00007251 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregora11693b2008-11-12 17:17:38 +00007252};
7253
Craig Toppercd7b0332013-07-01 06:29:40 +00007254} // end anonymous namespace
7255
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007256/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00007257/// the set of pointer types along with any more-qualified variants of
7258/// that type. For example, if @p Ty is "int const *", this routine
7259/// will add "int const *", "int const volatile *", "int const
7260/// restrict *", and "int const volatile restrict *" to the set of
7261/// pointer types. Returns true if the add of @p Ty itself succeeded,
7262/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00007263///
7264/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007265bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007266BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7267 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00007268
Douglas Gregora11693b2008-11-12 17:17:38 +00007269 // Insert this type.
Richard Smith95853072016-03-25 00:08:53 +00007270 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00007271 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007272
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00007273 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00007274 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00007275 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00007276 if (!PointerTy) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00007277 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7278 PointeeTy = PTy->getPointeeType();
7279 buildObjCPtr = true;
7280 } else {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00007281 PointeeTy = PointerTy->getPointeeType();
Douglas Gregor5bee2582012-06-04 00:15:09 +00007282 }
7283
Sebastian Redl4990a632009-11-18 20:39:26 +00007284 // Don't add qualified variants of arrays. For one, they're not allowed
7285 // (the qualifier would sink to the element type), and for another, the
7286 // only overload situation where it matters is subscript or pointer +- int,
7287 // and those shouldn't have qualifier variants anyway.
7288 if (PointeeTy->isArrayType())
7289 return true;
Douglas Gregor5bee2582012-06-04 00:15:09 +00007290
John McCall8ccfcb52009-09-24 19:53:00 +00007291 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007292 bool hasVolatile = VisibleQuals.hasVolatile();
7293 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007294
John McCall8ccfcb52009-09-24 19:53:00 +00007295 // Iterate through all strict supersets of BaseCVR.
7296 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7297 if ((CVR | BaseCVR) != CVR) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00007298 // Skip over volatile if no volatile found anywhere in the types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007299 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00007300
7301 // Skip over restrict if no restrict found anywhere in the types, or if
7302 // the type cannot be restrict-qualified.
7303 if ((CVR & Qualifiers::Restrict) &&
7304 (!hasRestrict ||
7305 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7306 continue;
7307
7308 // Build qualified pointee type.
John McCall8ccfcb52009-09-24 19:53:00 +00007309 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007310
7311 // Build qualified pointer type.
7312 QualType QPointerTy;
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00007313 if (!buildObjCPtr)
Douglas Gregor5bee2582012-06-04 00:15:09 +00007314 QPointerTy = Context.getPointerType(QPointeeTy);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00007315 else
Douglas Gregor5bee2582012-06-04 00:15:09 +00007316 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
7317
7318 // Insert qualified pointer type.
7319 PointerTypes.insert(QPointerTy);
Douglas Gregora11693b2008-11-12 17:17:38 +00007320 }
7321
7322 return true;
7323}
7324
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007325/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7326/// to the set of pointer types along with any more-qualified variants of
7327/// that type. For example, if @p Ty is "int const *", this routine
7328/// will add "int const *", "int const volatile *", "int const
7329/// restrict *", and "int const volatile restrict *" to the set of
7330/// pointer types. Returns true if the add of @p Ty itself succeeded,
7331/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00007332///
7333/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007334bool
7335BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7336 QualType Ty) {
7337 // Insert this type.
Richard Smith95853072016-03-25 00:08:53 +00007338 if (!MemberPointerTypes.insert(Ty))
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007339 return false;
7340
John McCall8ccfcb52009-09-24 19:53:00 +00007341 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
7342 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007343
John McCall8ccfcb52009-09-24 19:53:00 +00007344 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00007345 // Don't add qualified variants of arrays. For one, they're not allowed
7346 // (the qualifier would sink to the element type), and for another, the
7347 // only overload situation where it matters is subscript or pointer +- int,
7348 // and those shouldn't have qualifier variants anyway.
7349 if (PointeeTy->isArrayType())
7350 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00007351 const Type *ClassTy = PointerTy->getClass();
7352
7353 // Iterate through all strict supersets of the pointee type's CVR
7354 // qualifiers.
7355 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7356 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7357 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007358
John McCall8ccfcb52009-09-24 19:53:00 +00007359 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00007360 MemberPointerTypes.insert(
7361 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007362 }
7363
7364 return true;
7365}
7366
Douglas Gregora11693b2008-11-12 17:17:38 +00007367/// AddTypesConvertedFrom - Add each of the types to which the type @p
7368/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007369/// primarily interested in pointer types and enumeration types. We also
7370/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00007371/// AllowUserConversions is true if we should look at the conversion
7372/// functions of a class type, and AllowExplicitConversions if we
7373/// should also include the explicit conversion functions of a class
7374/// type.
Mike Stump11289f42009-09-09 15:08:12 +00007375void
Douglas Gregor5fb53972009-01-14 15:45:31 +00007376BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007377 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00007378 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007379 bool AllowExplicitConversions,
7380 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007381 // Only deal with canonical types.
7382 Ty = Context.getCanonicalType(Ty);
7383
7384 // Look through reference types; they aren't part of the type of an
7385 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007386 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00007387 Ty = RefTy->getPointeeType();
7388
John McCall33ddac02011-01-19 10:06:00 +00007389 // If we're dealing with an array type, decay to the pointer.
7390 if (Ty->isArrayType())
7391 Ty = SemaRef.Context.getArrayDecayedType(Ty);
7392
7393 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007394 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00007395
Chandler Carruth00a38332010-12-13 01:44:01 +00007396 // Flag if we ever add a non-record type.
7397 const RecordType *TyRec = Ty->getAs<RecordType>();
7398 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7399
Chandler Carruth00a38332010-12-13 01:44:01 +00007400 // Flag if we encounter an arithmetic type.
7401 HasArithmeticOrEnumeralTypes =
7402 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7403
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00007404 if (Ty->isObjCIdType() || Ty->isObjCClassType())
7405 PointerTypes.insert(Ty);
7406 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007407 // Insert our type, and its more-qualified variants, into the set
7408 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007409 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00007410 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007411 } else if (Ty->isMemberPointerType()) {
7412 // Member pointers are far easier, since the pointee can't be converted.
7413 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7414 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00007415 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007416 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00007417 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007418 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007419 // We treat vector types as arithmetic types in many contexts as an
7420 // extension.
7421 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007422 VectorTypes.insert(Ty);
Douglas Gregor80af3132011-05-21 23:15:46 +00007423 } else if (Ty->isNullPtrType()) {
7424 HasNullPtrType = true;
Chandler Carruth00a38332010-12-13 01:44:01 +00007425 } else if (AllowUserConversions && TyRec) {
7426 // No conversion functions in incomplete types.
Richard Smithdb0ac552015-12-18 22:40:25 +00007427 if (!SemaRef.isCompleteType(Loc, Ty))
Chandler Carruth00a38332010-12-13 01:44:01 +00007428 return;
Mike Stump11289f42009-09-09 15:08:12 +00007429
Chandler Carruth00a38332010-12-13 01:44:01 +00007430 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00007431 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007432 if (isa<UsingShadowDecl>(D))
7433 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00007434
Chandler Carruth00a38332010-12-13 01:44:01 +00007435 // Skip conversion function templates; they don't tell us anything
7436 // about which builtin types we can convert to.
7437 if (isa<FunctionTemplateDecl>(D))
7438 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00007439
Chandler Carruth00a38332010-12-13 01:44:01 +00007440 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7441 if (AllowExplicitConversions || !Conv->isExplicit()) {
7442 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7443 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00007444 }
7445 }
7446 }
7447}
7448
Douglas Gregor84605ae2009-08-24 13:43:27 +00007449/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
7450/// the volatile- and non-volatile-qualified assignment operators for the
7451/// given type to the candidate set.
7452static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7453 QualType T,
Richard Smithe54c3072013-05-05 15:51:06 +00007454 ArrayRef<Expr *> Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00007455 OverloadCandidateSet &CandidateSet) {
7456 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00007457
Douglas Gregor84605ae2009-08-24 13:43:27 +00007458 // T& operator=(T&, T)
7459 ParamTypes[0] = S.Context.getLValueReferenceType(T);
7460 ParamTypes[1] = T;
Richard Smithe54c3072013-05-05 15:51:06 +00007461 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor84605ae2009-08-24 13:43:27 +00007462 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00007463
Douglas Gregor84605ae2009-08-24 13:43:27 +00007464 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7465 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00007466 ParamTypes[0]
7467 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00007468 ParamTypes[1] = T;
Richard Smithe54c3072013-05-05 15:51:06 +00007469 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00007470 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00007471 }
7472}
Mike Stump11289f42009-09-09 15:08:12 +00007473
Sebastian Redl1054fae2009-10-25 17:03:50 +00007474/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7475/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007476static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7477 Qualifiers VRQuals;
7478 const RecordType *TyRec;
7479 if (const MemberPointerType *RHSMPType =
7480 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00007481 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007482 else
7483 TyRec = ArgExpr->getType()->getAs<RecordType>();
7484 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007485 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007486 VRQuals.addVolatile();
7487 VRQuals.addRestrict();
7488 return VRQuals;
7489 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007490
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007491 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00007492 if (!ClassDecl->hasDefinition())
7493 return VRQuals;
7494
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00007495 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
John McCallda4458e2010-03-31 01:36:47 +00007496 if (isa<UsingShadowDecl>(D))
7497 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7498 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007499 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7500 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7501 CanTy = ResTypeRef->getPointeeType();
7502 // Need to go down the pointer/mempointer chain and add qualifiers
7503 // as see them.
7504 bool done = false;
7505 while (!done) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00007506 if (CanTy.isRestrictQualified())
7507 VRQuals.addRestrict();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007508 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7509 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007510 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007511 CanTy->getAs<MemberPointerType>())
7512 CanTy = ResTypeMPtr->getPointeeType();
7513 else
7514 done = true;
7515 if (CanTy.isVolatileQualified())
7516 VRQuals.addVolatile();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007517 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7518 return VRQuals;
7519 }
7520 }
7521 }
7522 return VRQuals;
7523}
John McCall52872982010-11-13 05:51:15 +00007524
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007525namespace {
John McCall52872982010-11-13 05:51:15 +00007526
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007527/// \brief Helper class to manage the addition of builtin operator overload
7528/// candidates. It provides shared state and utility methods used throughout
7529/// the process, as well as a helper method to add each group of builtin
7530/// operator overloads from the standard to a candidate set.
7531class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007532 // Common instance state available to all overload candidate addition methods.
7533 Sema &S;
Richard Smithe54c3072013-05-05 15:51:06 +00007534 ArrayRef<Expr *> Args;
Chandler Carruthc6586e52010-12-12 10:35:00 +00007535 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00007536 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007537 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruthc6586e52010-12-12 10:35:00 +00007538 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007539
Chandler Carruthc6586e52010-12-12 10:35:00 +00007540 // Define some constants used to index and iterate over the arithemetic types
7541 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00007542 // The "promoted arithmetic types" are the arithmetic
7543 // types are that preserved by promotion (C++ [over.built]p2).
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00007544 static const unsigned FirstIntegralType = 4;
7545 static const unsigned LastIntegralType = 21;
7546 static const unsigned FirstPromotedIntegralType = 4,
7547 LastPromotedIntegralType = 12;
John McCall52872982010-11-13 05:51:15 +00007548 static const unsigned FirstPromotedArithmeticType = 0,
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00007549 LastPromotedArithmeticType = 12;
7550 static const unsigned NumArithmeticTypes = 21;
John McCall52872982010-11-13 05:51:15 +00007551
Chandler Carruthc6586e52010-12-12 10:35:00 +00007552 /// \brief Get the canonical type for a given arithmetic type index.
7553 CanQualType getArithmeticType(unsigned index) {
7554 assert(index < NumArithmeticTypes);
7555 static CanQualType ASTContext::* const
7556 ArithmeticTypes[NumArithmeticTypes] = {
7557 // Start of promoted types.
7558 &ASTContext::FloatTy,
7559 &ASTContext::DoubleTy,
7560 &ASTContext::LongDoubleTy,
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00007561 &ASTContext::Float128Ty,
John McCall52872982010-11-13 05:51:15 +00007562
Chandler Carruthc6586e52010-12-12 10:35:00 +00007563 // Start of integral types.
7564 &ASTContext::IntTy,
7565 &ASTContext::LongTy,
7566 &ASTContext::LongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00007567 &ASTContext::Int128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00007568 &ASTContext::UnsignedIntTy,
7569 &ASTContext::UnsignedLongTy,
7570 &ASTContext::UnsignedLongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00007571 &ASTContext::UnsignedInt128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00007572 // End of promoted types.
7573
7574 &ASTContext::BoolTy,
7575 &ASTContext::CharTy,
7576 &ASTContext::WCharTy,
7577 &ASTContext::Char16Ty,
7578 &ASTContext::Char32Ty,
7579 &ASTContext::SignedCharTy,
7580 &ASTContext::ShortTy,
7581 &ASTContext::UnsignedCharTy,
7582 &ASTContext::UnsignedShortTy,
7583 // End of integral types.
Richard Smith521ecc12012-06-10 08:00:26 +00007584 // FIXME: What about complex? What about half?
Chandler Carruthc6586e52010-12-12 10:35:00 +00007585 };
7586 return S.Context.*ArithmeticTypes[index];
7587 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007588
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007589 /// \brief Gets the canonical type resulting from the usual arithemetic
7590 /// converions for the given arithmetic types.
7591 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
7592 // Accelerator table for performing the usual arithmetic conversions.
7593 // The rules are basically:
7594 // - if either is floating-point, use the wider floating-point
7595 // - if same signedness, use the higher rank
7596 // - if same size, use unsigned of the higher rank
7597 // - use the larger type
7598 // These rules, together with the axiom that higher ranks are
7599 // never smaller, are sufficient to precompute all of these results
7600 // *except* when dealing with signed types of higher rank.
7601 // (we could precompute SLL x UI for all known platforms, but it's
7602 // better not to make any assumptions).
Richard Smith521ecc12012-06-10 08:00:26 +00007603 // We assume that int128 has a higher rank than long long on all platforms.
George Burgess IVf23ce362016-04-29 21:32:53 +00007604 enum PromotedType : int8_t {
Richard Smith521ecc12012-06-10 08:00:26 +00007605 Dep=-1,
7606 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007607 };
Nuno Lopes9af6b032012-04-21 14:45:25 +00007608 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007609 [LastPromotedArithmeticType] = {
Richard Smith521ecc12012-06-10 08:00:26 +00007610/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
7611/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
7612/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
7613/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
7614/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
7615/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
7616/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
7617/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
7618/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
7619/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
7620/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007621 };
7622
7623 assert(L < LastPromotedArithmeticType);
7624 assert(R < LastPromotedArithmeticType);
7625 int Idx = ConversionsTable[L][R];
7626
7627 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007628 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007629
7630 // Slow path: we need to compare widths.
7631 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007632 CanQualType LT = getArithmeticType(L),
7633 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007634 unsigned LW = S.Context.getIntWidth(LT),
7635 RW = S.Context.getIntWidth(RT);
7636
7637 // If they're different widths, use the signed type.
7638 if (LW > RW) return LT;
7639 else if (LW < RW) return RT;
7640
7641 // Otherwise, use the unsigned type of the signed type's rank.
7642 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
7643 assert(L == SLL || R == SLL);
7644 return S.Context.UnsignedLongLongTy;
7645 }
7646
Chandler Carruth5659c0c2010-12-12 09:22:45 +00007647 /// \brief Helper method to factor out the common pattern of adding overloads
7648 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007649 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007650 bool HasVolatile,
7651 bool HasRestrict) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007652 QualType ParamTypes[2] = {
7653 S.Context.getLValueReferenceType(CandidateTy),
7654 S.Context.IntTy
7655 };
7656
7657 // Non-volatile version.
Richard Smithe54c3072013-05-05 15:51:06 +00007658 if (Args.size() == 1)
7659 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007660 else
Richard Smithe54c3072013-05-05 15:51:06 +00007661 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007662
7663 // Use a heuristic to reduce number of builtin candidates in the set:
7664 // add volatile version only if there are conversions to a volatile type.
7665 if (HasVolatile) {
7666 ParamTypes[0] =
7667 S.Context.getLValueReferenceType(
7668 S.Context.getVolatileType(CandidateTy));
Richard Smithe54c3072013-05-05 15:51:06 +00007669 if (Args.size() == 1)
7670 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007671 else
Richard Smithe54c3072013-05-05 15:51:06 +00007672 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007673 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007674
7675 // Add restrict version only if there are conversions to a restrict type
7676 // and our candidate type is a non-restrict-qualified pointer.
7677 if (HasRestrict && CandidateTy->isAnyPointerType() &&
7678 !CandidateTy.isRestrictQualified()) {
7679 ParamTypes[0]
7680 = S.Context.getLValueReferenceType(
7681 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
Richard Smithe54c3072013-05-05 15:51:06 +00007682 if (Args.size() == 1)
7683 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007684 else
Richard Smithe54c3072013-05-05 15:51:06 +00007685 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007686
7687 if (HasVolatile) {
7688 ParamTypes[0]
7689 = S.Context.getLValueReferenceType(
7690 S.Context.getCVRQualifiedType(CandidateTy,
7691 (Qualifiers::Volatile |
7692 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007693 if (Args.size() == 1)
7694 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007695 else
Richard Smithe54c3072013-05-05 15:51:06 +00007696 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007697 }
7698 }
7699
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007700 }
7701
7702public:
7703 BuiltinOperatorOverloadBuilder(
Richard Smithe54c3072013-05-05 15:51:06 +00007704 Sema &S, ArrayRef<Expr *> Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007705 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00007706 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007707 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007708 OverloadCandidateSet &CandidateSet)
Richard Smithe54c3072013-05-05 15:51:06 +00007709 : S(S), Args(Args),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007710 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00007711 HasArithmeticOrEnumeralCandidateType(
7712 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007713 CandidateTypes(CandidateTypes),
7714 CandidateSet(CandidateSet) {
7715 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007716 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007717 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007718 assert(getArithmeticType(LastPromotedIntegralType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00007719 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007720 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007721 assert(getArithmeticType(FirstPromotedArithmeticType)
7722 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007723 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007724 assert(getArithmeticType(LastPromotedArithmeticType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00007725 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007726 "Invalid last promoted arithmetic type");
7727 }
7728
7729 // C++ [over.built]p3:
7730 //
7731 // For every pair (T, VQ), where T is an arithmetic type, and VQ
7732 // is either volatile or empty, there exist candidate operator
7733 // functions of the form
7734 //
7735 // VQ T& operator++(VQ T&);
7736 // T operator++(VQ T&, int);
7737 //
7738 // C++ [over.built]p4:
7739 //
7740 // For every pair (T, VQ), where T is an arithmetic type other
7741 // than bool, and VQ is either volatile or empty, there exist
7742 // candidate operator functions of the form
7743 //
7744 // VQ T& operator--(VQ T&);
7745 // T operator--(VQ T&, int);
7746 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007747 if (!HasArithmeticOrEnumeralCandidateType)
7748 return;
7749
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007750 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
7751 Arith < NumArithmeticTypes; ++Arith) {
7752 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00007753 getArithmeticType(Arith),
Douglas Gregor5bee2582012-06-04 00:15:09 +00007754 VisibleTypeConversionsQuals.hasVolatile(),
7755 VisibleTypeConversionsQuals.hasRestrict());
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007756 }
7757 }
7758
7759 // C++ [over.built]p5:
7760 //
7761 // For every pair (T, VQ), where T is a cv-qualified or
7762 // cv-unqualified object type, and VQ is either volatile or
7763 // empty, there exist candidate operator functions of the form
7764 //
7765 // T*VQ& operator++(T*VQ&);
7766 // T*VQ& operator--(T*VQ&);
7767 // T* operator++(T*VQ&, int);
7768 // T* operator--(T*VQ&, int);
7769 void addPlusPlusMinusMinusPointerOverloads() {
7770 for (BuiltinCandidateTypeSet::iterator
7771 Ptr = CandidateTypes[0].pointer_begin(),
7772 PtrEnd = CandidateTypes[0].pointer_end();
7773 Ptr != PtrEnd; ++Ptr) {
7774 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00007775 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007776 continue;
7777
7778 addPlusPlusMinusMinusStyleOverloads(*Ptr,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007779 (!(*Ptr).isVolatileQualified() &&
7780 VisibleTypeConversionsQuals.hasVolatile()),
7781 (!(*Ptr).isRestrictQualified() &&
7782 VisibleTypeConversionsQuals.hasRestrict()));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007783 }
7784 }
7785
7786 // C++ [over.built]p6:
7787 // For every cv-qualified or cv-unqualified object type T, there
7788 // exist candidate operator functions of the form
7789 //
7790 // T& operator*(T*);
7791 //
7792 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007793 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00007794 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007795 // T& operator*(T*);
7796 void addUnaryStarPointerOverloads() {
7797 for (BuiltinCandidateTypeSet::iterator
7798 Ptr = CandidateTypes[0].pointer_begin(),
7799 PtrEnd = CandidateTypes[0].pointer_end();
7800 Ptr != PtrEnd; ++Ptr) {
7801 QualType ParamTy = *Ptr;
7802 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007803 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7804 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007805
Douglas Gregor02824322011-01-26 19:30:28 +00007806 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7807 if (Proto->getTypeQuals() || Proto->getRefQualifier())
7808 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007809
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007810 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
Richard Smithe54c3072013-05-05 15:51:06 +00007811 &ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007812 }
7813 }
7814
7815 // C++ [over.built]p9:
7816 // For every promoted arithmetic type T, there exist candidate
7817 // operator functions of the form
7818 //
7819 // T operator+(T);
7820 // T operator-(T);
7821 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007822 if (!HasArithmeticOrEnumeralCandidateType)
7823 return;
7824
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007825 for (unsigned Arith = FirstPromotedArithmeticType;
7826 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007827 QualType ArithTy = getArithmeticType(Arith);
Richard Smithe54c3072013-05-05 15:51:06 +00007828 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007829 }
7830
7831 // Extension: We also add these operators for vector types.
7832 for (BuiltinCandidateTypeSet::iterator
7833 Vec = CandidateTypes[0].vector_begin(),
7834 VecEnd = CandidateTypes[0].vector_end();
7835 Vec != VecEnd; ++Vec) {
7836 QualType VecTy = *Vec;
Richard Smithe54c3072013-05-05 15:51:06 +00007837 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007838 }
7839 }
7840
7841 // C++ [over.built]p8:
7842 // For every type T, there exist candidate operator functions of
7843 // the form
7844 //
7845 // T* operator+(T*);
7846 void addUnaryPlusPointerOverloads() {
7847 for (BuiltinCandidateTypeSet::iterator
7848 Ptr = CandidateTypes[0].pointer_begin(),
7849 PtrEnd = CandidateTypes[0].pointer_end();
7850 Ptr != PtrEnd; ++Ptr) {
7851 QualType ParamTy = *Ptr;
Richard Smithe54c3072013-05-05 15:51:06 +00007852 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007853 }
7854 }
7855
7856 // C++ [over.built]p10:
7857 // For every promoted integral type T, there exist candidate
7858 // operator functions of the form
7859 //
7860 // T operator~(T);
7861 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007862 if (!HasArithmeticOrEnumeralCandidateType)
7863 return;
7864
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007865 for (unsigned Int = FirstPromotedIntegralType;
7866 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007867 QualType IntTy = getArithmeticType(Int);
Richard Smithe54c3072013-05-05 15:51:06 +00007868 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007869 }
7870
7871 // Extension: We also add this operator for vector types.
7872 for (BuiltinCandidateTypeSet::iterator
7873 Vec = CandidateTypes[0].vector_begin(),
7874 VecEnd = CandidateTypes[0].vector_end();
7875 Vec != VecEnd; ++Vec) {
7876 QualType VecTy = *Vec;
Richard Smithe54c3072013-05-05 15:51:06 +00007877 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007878 }
7879 }
7880
7881 // C++ [over.match.oper]p16:
Richard Smith5e9746f2016-10-21 22:00:42 +00007882 // For every pointer to member type T or type std::nullptr_t, there
7883 // exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007884 //
7885 // bool operator==(T,T);
7886 // bool operator!=(T,T);
Richard Smith5e9746f2016-10-21 22:00:42 +00007887 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007888 /// Set of (canonical) types that we've already handled.
7889 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7890
Richard Smithe54c3072013-05-05 15:51:06 +00007891 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007892 for (BuiltinCandidateTypeSet::iterator
7893 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7894 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7895 MemPtr != MemPtrEnd;
7896 ++MemPtr) {
7897 // Don't add the same builtin candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007898 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007899 continue;
7900
7901 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smithe54c3072013-05-05 15:51:06 +00007902 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007903 }
Richard Smith5e9746f2016-10-21 22:00:42 +00007904
7905 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7906 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7907 if (AddedTypes.insert(NullPtrTy).second) {
7908 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
7909 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
7910 CandidateSet);
7911 }
7912 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007913 }
7914 }
7915
7916 // C++ [over.built]p15:
7917 //
Richard Smith5e9746f2016-10-21 22:00:42 +00007918 // For every T, where T is an enumeration type or a pointer type,
7919 // there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007920 //
7921 // bool operator<(T, T);
7922 // bool operator>(T, T);
7923 // bool operator<=(T, T);
7924 // bool operator>=(T, T);
7925 // bool operator==(T, T);
7926 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007927 void addRelationalPointerOrEnumeralOverloads() {
Eli Friedman14f082b2012-09-18 21:52:24 +00007928 // C++ [over.match.oper]p3:
7929 // [...]the built-in candidates include all of the candidate operator
7930 // functions defined in 13.6 that, compared to the given operator, [...]
7931 // do not have the same parameter-type-list as any non-template non-member
7932 // candidate.
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007933 //
Eli Friedman14f082b2012-09-18 21:52:24 +00007934 // Note that in practice, this only affects enumeration types because there
7935 // aren't any built-in candidates of record type, and a user-defined operator
7936 // must have an operand of record or enumeration type. Also, the only other
7937 // overloaded operator with enumeration arguments, operator=,
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007938 // cannot be overloaded for enumeration types, so this is the only place
7939 // where we must suppress candidates like this.
7940 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7941 UserDefinedBinaryOperators;
7942
Richard Smithe54c3072013-05-05 15:51:06 +00007943 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007944 if (CandidateTypes[ArgIdx].enumeration_begin() !=
7945 CandidateTypes[ArgIdx].enumeration_end()) {
7946 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7947 CEnd = CandidateSet.end();
7948 C != CEnd; ++C) {
7949 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7950 continue;
7951
Eli Friedman14f082b2012-09-18 21:52:24 +00007952 if (C->Function->isFunctionTemplateSpecialization())
7953 continue;
7954
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007955 QualType FirstParamType =
7956 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7957 QualType SecondParamType =
7958 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7959
7960 // Skip if either parameter isn't of enumeral type.
7961 if (!FirstParamType->isEnumeralType() ||
7962 !SecondParamType->isEnumeralType())
7963 continue;
7964
7965 // Add this operator to the set of known user-defined operators.
7966 UserDefinedBinaryOperators.insert(
7967 std::make_pair(S.Context.getCanonicalType(FirstParamType),
7968 S.Context.getCanonicalType(SecondParamType)));
7969 }
7970 }
7971 }
7972
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007973 /// Set of (canonical) types that we've already handled.
7974 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7975
Richard Smithe54c3072013-05-05 15:51:06 +00007976 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007977 for (BuiltinCandidateTypeSet::iterator
7978 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7979 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7980 Ptr != PtrEnd; ++Ptr) {
7981 // Don't add the same builtin candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007982 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007983 continue;
7984
7985 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smithe54c3072013-05-05 15:51:06 +00007986 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007987 }
7988 for (BuiltinCandidateTypeSet::iterator
7989 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7990 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7991 Enum != EnumEnd; ++Enum) {
7992 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
7993
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007994 // Don't add the same builtin candidate twice, or if a user defined
7995 // candidate exists.
David Blaikie82e95a32014-11-19 07:49:47 +00007996 if (!AddedTypes.insert(CanonType).second ||
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007997 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
7998 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007999 continue;
8000
8001 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smithe54c3072013-05-05 15:51:06 +00008002 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008003 }
8004 }
8005 }
8006
8007 // C++ [over.built]p13:
8008 //
8009 // For every cv-qualified or cv-unqualified object type T
8010 // there exist candidate operator functions of the form
8011 //
8012 // T* operator+(T*, ptrdiff_t);
8013 // T& operator[](T*, ptrdiff_t); [BELOW]
8014 // T* operator-(T*, ptrdiff_t);
8015 // T* operator+(ptrdiff_t, T*);
8016 // T& operator[](ptrdiff_t, T*); [BELOW]
8017 //
8018 // C++ [over.built]p14:
8019 //
8020 // For every T, where T is a pointer to object type, there
8021 // exist candidate operator functions of the form
8022 //
8023 // ptrdiff_t operator-(T, T);
8024 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
8025 /// Set of (canonical) types that we've already handled.
8026 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8027
8028 for (int Arg = 0; Arg < 2; ++Arg) {
Eric Christopher9207a522015-08-21 16:24:01 +00008029 QualType AsymmetricParamTypes[2] = {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008030 S.Context.getPointerDiffType(),
8031 S.Context.getPointerDiffType(),
8032 };
8033 for (BuiltinCandidateTypeSet::iterator
8034 Ptr = CandidateTypes[Arg].pointer_begin(),
8035 PtrEnd = CandidateTypes[Arg].pointer_end();
8036 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00008037 QualType PointeeTy = (*Ptr)->getPointeeType();
8038 if (!PointeeTy->isObjectType())
8039 continue;
8040
Eric Christopher9207a522015-08-21 16:24:01 +00008041 AsymmetricParamTypes[Arg] = *Ptr;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008042 if (Arg == 0 || Op == OO_Plus) {
8043 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
8044 // T* operator+(ptrdiff_t, T*);
Eric Christopher9207a522015-08-21 16:24:01 +00008045 S.AddBuiltinCandidate(*Ptr, AsymmetricParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008046 }
8047 if (Op == OO_Minus) {
8048 // ptrdiff_t operator-(T, T);
David Blaikie82e95a32014-11-19 07:49:47 +00008049 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008050 continue;
8051
8052 QualType ParamTypes[2] = { *Ptr, *Ptr };
8053 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
Richard Smithe54c3072013-05-05 15:51:06 +00008054 Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008055 }
8056 }
8057 }
8058 }
8059
8060 // C++ [over.built]p12:
8061 //
8062 // For every pair of promoted arithmetic types L and R, there
8063 // exist candidate operator functions of the form
8064 //
8065 // LR operator*(L, R);
8066 // LR operator/(L, R);
8067 // LR operator+(L, R);
8068 // LR operator-(L, R);
8069 // bool operator<(L, R);
8070 // bool operator>(L, R);
8071 // bool operator<=(L, R);
8072 // bool operator>=(L, R);
8073 // bool operator==(L, R);
8074 // bool operator!=(L, R);
8075 //
8076 // where LR is the result of the usual arithmetic conversions
8077 // between types L and R.
8078 //
8079 // C++ [over.built]p24:
8080 //
8081 // For every pair of promoted arithmetic types L and R, there exist
8082 // candidate operator functions of the form
8083 //
8084 // LR operator?(bool, L, R);
8085 //
8086 // where LR is the result of the usual arithmetic conversions
8087 // between types L and R.
8088 // Our candidates ignore the first parameter.
8089 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00008090 if (!HasArithmeticOrEnumeralCandidateType)
8091 return;
8092
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008093 for (unsigned Left = FirstPromotedArithmeticType;
8094 Left < LastPromotedArithmeticType; ++Left) {
8095 for (unsigned Right = FirstPromotedArithmeticType;
8096 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00008097 QualType LandR[2] = { getArithmeticType(Left),
8098 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008099 QualType Result =
8100 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00008101 : getUsualArithmeticConversions(Left, Right);
Richard Smithe54c3072013-05-05 15:51:06 +00008102 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008103 }
8104 }
8105
8106 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
8107 // conditional operator for vector types.
8108 for (BuiltinCandidateTypeSet::iterator
8109 Vec1 = CandidateTypes[0].vector_begin(),
8110 Vec1End = CandidateTypes[0].vector_end();
8111 Vec1 != Vec1End; ++Vec1) {
8112 for (BuiltinCandidateTypeSet::iterator
8113 Vec2 = CandidateTypes[1].vector_begin(),
8114 Vec2End = CandidateTypes[1].vector_end();
8115 Vec2 != Vec2End; ++Vec2) {
8116 QualType LandR[2] = { *Vec1, *Vec2 };
8117 QualType Result = S.Context.BoolTy;
8118 if (!isComparison) {
8119 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
8120 Result = *Vec1;
8121 else
8122 Result = *Vec2;
8123 }
8124
Richard Smithe54c3072013-05-05 15:51:06 +00008125 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008126 }
8127 }
8128 }
8129
8130 // C++ [over.built]p17:
8131 //
8132 // For every pair of promoted integral types L and R, there
8133 // exist candidate operator functions of the form
8134 //
8135 // LR operator%(L, R);
8136 // LR operator&(L, R);
8137 // LR operator^(L, R);
8138 // LR operator|(L, R);
8139 // L operator<<(L, R);
8140 // L operator>>(L, R);
8141 //
8142 // where LR is the result of the usual arithmetic conversions
8143 // between types L and R.
8144 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00008145 if (!HasArithmeticOrEnumeralCandidateType)
8146 return;
8147
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008148 for (unsigned Left = FirstPromotedIntegralType;
8149 Left < LastPromotedIntegralType; ++Left) {
8150 for (unsigned Right = FirstPromotedIntegralType;
8151 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00008152 QualType LandR[2] = { getArithmeticType(Left),
8153 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008154 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
8155 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00008156 : getUsualArithmeticConversions(Left, Right);
Richard Smithe54c3072013-05-05 15:51:06 +00008157 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008158 }
8159 }
8160 }
8161
8162 // C++ [over.built]p20:
8163 //
8164 // For every pair (T, VQ), where T is an enumeration or
8165 // pointer to member type and VQ is either volatile or
8166 // empty, there exist candidate operator functions of the form
8167 //
8168 // VQ T& operator=(VQ T&, T);
8169 void addAssignmentMemberPointerOrEnumeralOverloads() {
8170 /// Set of (canonical) types that we've already handled.
8171 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8172
8173 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8174 for (BuiltinCandidateTypeSet::iterator
8175 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8176 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8177 Enum != EnumEnd; ++Enum) {
David Blaikie82e95a32014-11-19 07:49:47 +00008178 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008179 continue;
8180
Richard Smithe54c3072013-05-05 15:51:06 +00008181 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008182 }
8183
8184 for (BuiltinCandidateTypeSet::iterator
8185 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8186 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8187 MemPtr != MemPtrEnd; ++MemPtr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008188 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008189 continue;
8190
Richard Smithe54c3072013-05-05 15:51:06 +00008191 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008192 }
8193 }
8194 }
8195
8196 // C++ [over.built]p19:
8197 //
8198 // For every pair (T, VQ), where T is any type and VQ is either
8199 // volatile or empty, there exist candidate operator functions
8200 // of the form
8201 //
8202 // T*VQ& operator=(T*VQ&, T*);
8203 //
8204 // C++ [over.built]p21:
8205 //
8206 // For every pair (T, VQ), where T is a cv-qualified or
8207 // cv-unqualified object type and VQ is either volatile or
8208 // empty, there exist candidate operator functions of the form
8209 //
8210 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
8211 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
8212 void addAssignmentPointerOverloads(bool isEqualOp) {
8213 /// Set of (canonical) types that we've already handled.
8214 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8215
8216 for (BuiltinCandidateTypeSet::iterator
8217 Ptr = CandidateTypes[0].pointer_begin(),
8218 PtrEnd = CandidateTypes[0].pointer_end();
8219 Ptr != PtrEnd; ++Ptr) {
8220 // If this is operator=, keep track of the builtin candidates we added.
8221 if (isEqualOp)
8222 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00008223 else if (!(*Ptr)->getPointeeType()->isObjectType())
8224 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008225
8226 // non-volatile version
8227 QualType ParamTypes[2] = {
8228 S.Context.getLValueReferenceType(*Ptr),
8229 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
8230 };
Richard Smithe54c3072013-05-05 15:51:06 +00008231 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008232 /*IsAssigmentOperator=*/ isEqualOp);
8233
Douglas Gregor5bee2582012-06-04 00:15:09 +00008234 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8235 VisibleTypeConversionsQuals.hasVolatile();
8236 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008237 // volatile version
8238 ParamTypes[0] =
8239 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00008240 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008241 /*IsAssigmentOperator=*/isEqualOp);
8242 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00008243
8244 if (!(*Ptr).isRestrictQualified() &&
8245 VisibleTypeConversionsQuals.hasRestrict()) {
8246 // restrict version
8247 ParamTypes[0]
8248 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00008249 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00008250 /*IsAssigmentOperator=*/isEqualOp);
8251
8252 if (NeedVolatile) {
8253 // volatile restrict version
8254 ParamTypes[0]
8255 = S.Context.getLValueReferenceType(
8256 S.Context.getCVRQualifiedType(*Ptr,
8257 (Qualifiers::Volatile |
8258 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00008259 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00008260 /*IsAssigmentOperator=*/isEqualOp);
8261 }
8262 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008263 }
8264
8265 if (isEqualOp) {
8266 for (BuiltinCandidateTypeSet::iterator
8267 Ptr = CandidateTypes[1].pointer_begin(),
8268 PtrEnd = CandidateTypes[1].pointer_end();
8269 Ptr != PtrEnd; ++Ptr) {
8270 // Make sure we don't add the same candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00008271 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008272 continue;
8273
Chandler Carruth8e543b32010-12-12 08:17:55 +00008274 QualType ParamTypes[2] = {
8275 S.Context.getLValueReferenceType(*Ptr),
8276 *Ptr,
8277 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008278
8279 // non-volatile version
Richard Smithe54c3072013-05-05 15:51:06 +00008280 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008281 /*IsAssigmentOperator=*/true);
8282
Douglas Gregor5bee2582012-06-04 00:15:09 +00008283 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8284 VisibleTypeConversionsQuals.hasVolatile();
8285 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008286 // volatile version
8287 ParamTypes[0] =
8288 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00008289 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8290 /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008291 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00008292
8293 if (!(*Ptr).isRestrictQualified() &&
8294 VisibleTypeConversionsQuals.hasRestrict()) {
8295 // restrict version
8296 ParamTypes[0]
8297 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00008298 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8299 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00008300
8301 if (NeedVolatile) {
8302 // volatile restrict version
8303 ParamTypes[0]
8304 = S.Context.getLValueReferenceType(
8305 S.Context.getCVRQualifiedType(*Ptr,
8306 (Qualifiers::Volatile |
8307 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00008308 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8309 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00008310 }
8311 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008312 }
8313 }
8314 }
8315
8316 // C++ [over.built]p18:
8317 //
8318 // For every triple (L, VQ, R), where L is an arithmetic type,
8319 // VQ is either volatile or empty, and R is a promoted
8320 // arithmetic type, there exist candidate operator functions of
8321 // the form
8322 //
8323 // VQ L& operator=(VQ L&, R);
8324 // VQ L& operator*=(VQ L&, R);
8325 // VQ L& operator/=(VQ L&, R);
8326 // VQ L& operator+=(VQ L&, R);
8327 // VQ L& operator-=(VQ L&, R);
8328 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00008329 if (!HasArithmeticOrEnumeralCandidateType)
8330 return;
8331
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008332 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
8333 for (unsigned Right = FirstPromotedArithmeticType;
8334 Right < LastPromotedArithmeticType; ++Right) {
8335 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00008336 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008337
8338 // Add this built-in operator as a candidate (VQ is empty).
8339 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00008340 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smithe54c3072013-05-05 15:51:06 +00008341 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008342 /*IsAssigmentOperator=*/isEqualOp);
8343
8344 // Add this built-in operator as a candidate (VQ is 'volatile').
8345 if (VisibleTypeConversionsQuals.hasVolatile()) {
8346 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00008347 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008348 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00008349 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008350 /*IsAssigmentOperator=*/isEqualOp);
8351 }
8352 }
8353 }
8354
8355 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8356 for (BuiltinCandidateTypeSet::iterator
8357 Vec1 = CandidateTypes[0].vector_begin(),
8358 Vec1End = CandidateTypes[0].vector_end();
8359 Vec1 != Vec1End; ++Vec1) {
8360 for (BuiltinCandidateTypeSet::iterator
8361 Vec2 = CandidateTypes[1].vector_begin(),
8362 Vec2End = CandidateTypes[1].vector_end();
8363 Vec2 != Vec2End; ++Vec2) {
8364 QualType ParamTypes[2];
8365 ParamTypes[1] = *Vec2;
8366 // Add this built-in operator as a candidate (VQ is empty).
8367 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
Richard Smithe54c3072013-05-05 15:51:06 +00008368 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008369 /*IsAssigmentOperator=*/isEqualOp);
8370
8371 // Add this built-in operator as a candidate (VQ is 'volatile').
8372 if (VisibleTypeConversionsQuals.hasVolatile()) {
8373 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
8374 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00008375 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008376 /*IsAssigmentOperator=*/isEqualOp);
8377 }
8378 }
8379 }
8380 }
8381
8382 // C++ [over.built]p22:
8383 //
8384 // For every triple (L, VQ, R), where L is an integral type, VQ
8385 // is either volatile or empty, and R is a promoted integral
8386 // type, there exist candidate operator functions of the form
8387 //
8388 // VQ L& operator%=(VQ L&, R);
8389 // VQ L& operator<<=(VQ L&, R);
8390 // VQ L& operator>>=(VQ L&, R);
8391 // VQ L& operator&=(VQ L&, R);
8392 // VQ L& operator^=(VQ L&, R);
8393 // VQ L& operator|=(VQ L&, R);
8394 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00008395 if (!HasArithmeticOrEnumeralCandidateType)
8396 return;
8397
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008398 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8399 for (unsigned Right = FirstPromotedIntegralType;
8400 Right < LastPromotedIntegralType; ++Right) {
8401 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00008402 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008403
8404 // Add this built-in operator as a candidate (VQ is empty).
8405 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00008406 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smithe54c3072013-05-05 15:51:06 +00008407 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008408 if (VisibleTypeConversionsQuals.hasVolatile()) {
8409 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00008410 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008411 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8412 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00008413 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008414 }
8415 }
8416 }
8417 }
8418
8419 // C++ [over.operator]p23:
8420 //
8421 // There also exist candidate operator functions of the form
8422 //
8423 // bool operator!(bool);
8424 // bool operator&&(bool, bool);
8425 // bool operator||(bool, bool);
8426 void addExclaimOverload() {
8427 QualType ParamTy = S.Context.BoolTy;
Richard Smithe54c3072013-05-05 15:51:06 +00008428 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008429 /*IsAssignmentOperator=*/false,
8430 /*NumContextualBoolArguments=*/1);
8431 }
8432 void addAmpAmpOrPipePipeOverload() {
8433 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
Richard Smithe54c3072013-05-05 15:51:06 +00008434 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008435 /*IsAssignmentOperator=*/false,
8436 /*NumContextualBoolArguments=*/2);
8437 }
8438
8439 // C++ [over.built]p13:
8440 //
8441 // For every cv-qualified or cv-unqualified object type T there
8442 // exist candidate operator functions of the form
8443 //
8444 // T* operator+(T*, ptrdiff_t); [ABOVE]
8445 // T& operator[](T*, ptrdiff_t);
8446 // T* operator-(T*, ptrdiff_t); [ABOVE]
8447 // T* operator+(ptrdiff_t, T*); [ABOVE]
8448 // T& operator[](ptrdiff_t, T*);
8449 void addSubscriptOverloads() {
8450 for (BuiltinCandidateTypeSet::iterator
8451 Ptr = CandidateTypes[0].pointer_begin(),
8452 PtrEnd = CandidateTypes[0].pointer_end();
8453 Ptr != PtrEnd; ++Ptr) {
8454 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8455 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00008456 if (!PointeeType->isObjectType())
8457 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008458
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008459 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8460
8461 // T& operator[](T*, ptrdiff_t)
Richard Smithe54c3072013-05-05 15:51:06 +00008462 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008463 }
8464
8465 for (BuiltinCandidateTypeSet::iterator
8466 Ptr = CandidateTypes[1].pointer_begin(),
8467 PtrEnd = CandidateTypes[1].pointer_end();
8468 Ptr != PtrEnd; ++Ptr) {
8469 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8470 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00008471 if (!PointeeType->isObjectType())
8472 continue;
8473
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008474 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8475
8476 // T& operator[](ptrdiff_t, T*)
Richard Smithe54c3072013-05-05 15:51:06 +00008477 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008478 }
8479 }
8480
8481 // C++ [over.built]p11:
8482 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8483 // C1 is the same type as C2 or is a derived class of C2, T is an object
8484 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8485 // there exist candidate operator functions of the form
8486 //
8487 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8488 //
8489 // where CV12 is the union of CV1 and CV2.
8490 void addArrowStarOverloads() {
8491 for (BuiltinCandidateTypeSet::iterator
8492 Ptr = CandidateTypes[0].pointer_begin(),
8493 PtrEnd = CandidateTypes[0].pointer_end();
8494 Ptr != PtrEnd; ++Ptr) {
8495 QualType C1Ty = (*Ptr);
8496 QualType C1;
8497 QualifierCollector Q1;
8498 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8499 if (!isa<RecordType>(C1))
8500 continue;
8501 // heuristic to reduce number of builtin candidates in the set.
8502 // Add volatile/restrict version only if there are conversions to a
8503 // volatile/restrict type.
8504 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8505 continue;
8506 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8507 continue;
8508 for (BuiltinCandidateTypeSet::iterator
8509 MemPtr = CandidateTypes[1].member_pointer_begin(),
8510 MemPtrEnd = CandidateTypes[1].member_pointer_end();
8511 MemPtr != MemPtrEnd; ++MemPtr) {
8512 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8513 QualType C2 = QualType(mptr->getClass(), 0);
8514 C2 = C2.getUnqualifiedType();
Richard Smith0f59cb32015-12-18 21:45:41 +00008515 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008516 break;
8517 QualType ParamTypes[2] = { *Ptr, *MemPtr };
8518 // build CV12 T&
8519 QualType T = mptr->getPointeeType();
8520 if (!VisibleTypeConversionsQuals.hasVolatile() &&
8521 T.isVolatileQualified())
8522 continue;
8523 if (!VisibleTypeConversionsQuals.hasRestrict() &&
8524 T.isRestrictQualified())
8525 continue;
8526 T = Q1.apply(S.Context, T);
8527 QualType ResultTy = S.Context.getLValueReferenceType(T);
Richard Smithe54c3072013-05-05 15:51:06 +00008528 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008529 }
8530 }
8531 }
8532
8533 // Note that we don't consider the first argument, since it has been
8534 // contextually converted to bool long ago. The candidates below are
8535 // therefore added as binary.
8536 //
8537 // C++ [over.built]p25:
8538 // For every type T, where T is a pointer, pointer-to-member, or scoped
8539 // enumeration type, there exist candidate operator functions of the form
8540 //
8541 // T operator?(bool, T, T);
8542 //
8543 void addConditionalOperatorOverloads() {
8544 /// Set of (canonical) types that we've already handled.
8545 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8546
8547 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8548 for (BuiltinCandidateTypeSet::iterator
8549 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8550 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8551 Ptr != PtrEnd; ++Ptr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008552 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008553 continue;
8554
8555 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smithe54c3072013-05-05 15:51:06 +00008556 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008557 }
8558
8559 for (BuiltinCandidateTypeSet::iterator
8560 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8561 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8562 MemPtr != MemPtrEnd; ++MemPtr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008563 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008564 continue;
8565
8566 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smithe54c3072013-05-05 15:51:06 +00008567 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008568 }
8569
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008570 if (S.getLangOpts().CPlusPlus11) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008571 for (BuiltinCandidateTypeSet::iterator
8572 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8573 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8574 Enum != EnumEnd; ++Enum) {
8575 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8576 continue;
8577
David Blaikie82e95a32014-11-19 07:49:47 +00008578 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008579 continue;
8580
8581 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smithe54c3072013-05-05 15:51:06 +00008582 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008583 }
8584 }
8585 }
8586 }
8587};
8588
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008589} // end anonymous namespace
8590
8591/// AddBuiltinOperatorCandidates - Add the appropriate built-in
8592/// operator overloads to the candidate set (C++ [over.built]), based
8593/// on the operator @p Op and the arguments given. For example, if the
8594/// operator is a binary '+', this routine might add "int
8595/// operator+(int, int)" to cover integer addition.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00008596void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8597 SourceLocation OpLoc,
8598 ArrayRef<Expr *> Args,
8599 OverloadCandidateSet &CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00008600 // Find all of the types that the arguments can convert to, but only
8601 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00008602 // that make use of these types. Also record whether we encounter non-record
8603 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00008604 Qualifiers VisibleTypeConversionsQuals;
8605 VisibleTypeConversionsQuals.addConst();
Richard Smithe54c3072013-05-05 15:51:06 +00008606 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00008607 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00008608
8609 bool HasNonRecordCandidateType = false;
8610 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008611 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Richard Smithe54c3072013-05-05 15:51:06 +00008612 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Benjamin Kramer57dddd482015-02-17 21:55:18 +00008613 CandidateTypes.emplace_back(*this);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00008614 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8615 OpLoc,
8616 true,
8617 (Op == OO_Exclaim ||
8618 Op == OO_AmpAmp ||
8619 Op == OO_PipePipe),
8620 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00008621 HasNonRecordCandidateType = HasNonRecordCandidateType ||
8622 CandidateTypes[ArgIdx].hasNonRecordTypes();
8623 HasArithmeticOrEnumeralCandidateType =
8624 HasArithmeticOrEnumeralCandidateType ||
8625 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00008626 }
Douglas Gregora11693b2008-11-12 17:17:38 +00008627
Chandler Carruth00a38332010-12-13 01:44:01 +00008628 // Exit early when no non-record types have been added to the candidate set
8629 // for any of the arguments to the operator.
Douglas Gregor877d4eb2011-10-10 14:05:31 +00008630 //
8631 // We can't exit early for !, ||, or &&, since there we have always have
8632 // 'bool' overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00008633 if (!HasNonRecordCandidateType &&
Douglas Gregor877d4eb2011-10-10 14:05:31 +00008634 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth00a38332010-12-13 01:44:01 +00008635 return;
8636
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008637 // Setup an object to manage the common state for building overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00008638 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008639 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00008640 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008641 CandidateTypes, CandidateSet);
8642
8643 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00008644 switch (Op) {
8645 case OO_None:
8646 case NUM_OVERLOADED_OPERATORS:
David Blaikie83d382b2011-09-23 05:06:16 +00008647 llvm_unreachable("Expected an overloaded operator");
Douglas Gregora11693b2008-11-12 17:17:38 +00008648
Chandler Carruth5184de02010-12-12 08:51:33 +00008649 case OO_New:
8650 case OO_Delete:
8651 case OO_Array_New:
8652 case OO_Array_Delete:
8653 case OO_Call:
David Blaikie83d382b2011-09-23 05:06:16 +00008654 llvm_unreachable(
8655 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruth5184de02010-12-12 08:51:33 +00008656
8657 case OO_Comma:
8658 case OO_Arrow:
Richard Smith9f690bd2015-10-27 06:02:45 +00008659 case OO_Coawait:
Chandler Carruth5184de02010-12-12 08:51:33 +00008660 // C++ [over.match.oper]p3:
Richard Smith9f690bd2015-10-27 06:02:45 +00008661 // -- For the operator ',', the unary operator '&', the
8662 // operator '->', or the operator 'co_await', the
8663 // built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00008664 break;
8665
8666 case OO_Plus: // '+' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008667 if (Args.size() == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008668 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00008669 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00008670
8671 case OO_Minus: // '-' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008672 if (Args.size() == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008673 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008674 } else {
8675 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8676 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8677 }
Douglas Gregord08452f2008-11-19 15:42:04 +00008678 break;
8679
Chandler Carruth5184de02010-12-12 08:51:33 +00008680 case OO_Star: // '*' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008681 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008682 OpBuilder.addUnaryStarPointerOverloads();
8683 else
8684 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8685 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008686
Chandler Carruth5184de02010-12-12 08:51:33 +00008687 case OO_Slash:
8688 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008689 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008690
8691 case OO_PlusPlus:
8692 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008693 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8694 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00008695 break;
8696
Douglas Gregor84605ae2009-08-24 13:43:27 +00008697 case OO_EqualEqual:
8698 case OO_ExclaimEqual:
Richard Smith5e9746f2016-10-21 22:00:42 +00008699 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00008700 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008701
Douglas Gregora11693b2008-11-12 17:17:38 +00008702 case OO_Less:
8703 case OO_Greater:
8704 case OO_LessEqual:
8705 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00008706 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00008707 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
8708 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008709
Douglas Gregora11693b2008-11-12 17:17:38 +00008710 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00008711 case OO_Caret:
8712 case OO_Pipe:
8713 case OO_LessLess:
8714 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008715 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00008716 break;
8717
Chandler Carruth5184de02010-12-12 08:51:33 +00008718 case OO_Amp: // '&' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008719 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008720 // C++ [over.match.oper]p3:
8721 // -- For the operator ',', the unary operator '&', or the
8722 // operator '->', the built-in candidates set is empty.
8723 break;
8724
8725 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8726 break;
8727
8728 case OO_Tilde:
8729 OpBuilder.addUnaryTildePromotedIntegralOverloads();
8730 break;
8731
Douglas Gregora11693b2008-11-12 17:17:38 +00008732 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008733 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00008734 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00008735
8736 case OO_PlusEqual:
8737 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008738 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008739 // Fall through.
8740
8741 case OO_StarEqual:
8742 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008743 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008744 break;
8745
8746 case OO_PercentEqual:
8747 case OO_LessLessEqual:
8748 case OO_GreaterGreaterEqual:
8749 case OO_AmpEqual:
8750 case OO_CaretEqual:
8751 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008752 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008753 break;
8754
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008755 case OO_Exclaim:
8756 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00008757 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008758
Douglas Gregora11693b2008-11-12 17:17:38 +00008759 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008760 case OO_PipePipe:
8761 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00008762 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008763
8764 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008765 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008766 break;
8767
8768 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008769 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008770 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00008771
8772 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008773 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008774 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8775 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008776 }
8777}
8778
Douglas Gregore254f902009-02-04 00:32:51 +00008779/// \brief Add function candidates found via argument-dependent lookup
8780/// to the set of overloading candidates.
8781///
8782/// This routine performs argument-dependent name lookup based on the
8783/// given function name (which may also be an operator name) and adds
8784/// all of the overload candidates found by ADL to the overload
8785/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00008786void
Douglas Gregore254f902009-02-04 00:32:51 +00008787Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smith100b24a2014-04-17 01:52:14 +00008788 SourceLocation Loc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008789 ArrayRef<Expr *> Args,
Douglas Gregor739b107a2011-03-03 02:41:12 +00008790 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008791 OverloadCandidateSet& CandidateSet,
Richard Smithb6626742012-10-18 17:56:02 +00008792 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00008793 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00008794
John McCall91f61fc2010-01-26 06:04:06 +00008795 // FIXME: This approach for uniquing ADL results (and removing
8796 // redundant candidates from the set) relies on pointer-equality,
8797 // which means we need to key off the canonical decl. However,
8798 // always going back to the canonical decl might not get us the
8799 // right set of default arguments. What default arguments are
8800 // we supposed to consider on ADL candidates, anyway?
8801
Douglas Gregorcabea402009-09-22 15:41:20 +00008802 // FIXME: Pass in the explicit template arguments?
Richard Smith100b24a2014-04-17 01:52:14 +00008803 ArgumentDependentLookup(Name, Loc, Args, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00008804
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008805 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008806 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8807 CandEnd = CandidateSet.end();
8808 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00008809 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00008810 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00008811 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00008812 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00008813 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008814
8815 // For each of the ADL candidates we found, add it to the overload
8816 // set.
John McCall8fe68082010-01-26 07:16:45 +00008817 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00008818 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00008819 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00008820 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00008821 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008822
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008823 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8824 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00008825 } else
John McCall4c4c1df2010-01-26 03:27:55 +00008826 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00008827 FoundDecl, ExplicitTemplateArgs,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00008828 Args, CandidateSet, PartialOverloading);
Douglas Gregor15448f82009-06-27 21:05:07 +00008829 }
Douglas Gregore254f902009-02-04 00:32:51 +00008830}
8831
George Burgess IV3dc166912016-05-10 01:59:34 +00008832namespace {
8833enum class Comparison { Equal, Better, Worse };
8834}
8835
8836/// Compares the enable_if attributes of two FunctionDecls, for the purposes of
8837/// overload resolution.
8838///
8839/// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
8840/// Cand1's first N enable_if attributes have precisely the same conditions as
8841/// Cand2's first N enable_if attributes (where N = the number of enable_if
8842/// attributes on Cand2), and Cand1 has more than N enable_if attributes.
8843///
8844/// Note that you can have a pair of candidates such that Cand1's enable_if
8845/// attributes are worse than Cand2's, and Cand2's enable_if attributes are
8846/// worse than Cand1's.
8847static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
8848 const FunctionDecl *Cand2) {
8849 // Common case: One (or both) decls don't have enable_if attrs.
8850 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
8851 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
8852 if (!Cand1Attr || !Cand2Attr) {
8853 if (Cand1Attr == Cand2Attr)
8854 return Comparison::Equal;
8855 return Cand1Attr ? Comparison::Better : Comparison::Worse;
8856 }
George Burgess IV2a6150d2015-10-16 01:17:38 +00008857
8858 // FIXME: The next several lines are just
8859 // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8860 // instead of reverse order which is how they're stored in the AST.
8861 auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1);
8862 auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2);
8863
George Burgess IV3dc166912016-05-10 01:59:34 +00008864 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
8865 // has fewer enable_if attributes than Cand2.
8866 if (Cand1Attrs.size() < Cand2Attrs.size())
8867 return Comparison::Worse;
George Burgess IV2a6150d2015-10-16 01:17:38 +00008868
8869 auto Cand1I = Cand1Attrs.begin();
8870 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
8871 for (auto &Cand2A : Cand2Attrs) {
8872 Cand1ID.clear();
8873 Cand2ID.clear();
8874
8875 auto &Cand1A = *Cand1I++;
8876 Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true);
8877 Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true);
8878 if (Cand1ID != Cand2ID)
George Burgess IV3dc166912016-05-10 01:59:34 +00008879 return Comparison::Worse;
George Burgess IV2a6150d2015-10-16 01:17:38 +00008880 }
8881
George Burgess IV3dc166912016-05-10 01:59:34 +00008882 return Cand1I == Cand1Attrs.end() ? Comparison::Equal : Comparison::Better;
George Burgess IV2a6150d2015-10-16 01:17:38 +00008883}
8884
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008885/// isBetterOverloadCandidate - Determines whether the first overload
8886/// candidate is a better candidate than the second (C++ 13.3.3p1).
Richard Smith17c00b42014-11-12 01:24:00 +00008887bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1,
8888 const OverloadCandidate &Cand2,
8889 SourceLocation Loc,
8890 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008891 // Define viable functions to be better candidates than non-viable
8892 // functions.
8893 if (!Cand2.Viable)
8894 return Cand1.Viable;
8895 else if (!Cand1.Viable)
8896 return false;
8897
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008898 // C++ [over.match.best]p1:
8899 //
8900 // -- if F is a static member function, ICS1(F) is defined such
8901 // that ICS1(F) is neither better nor worse than ICS1(G) for
8902 // any function G, and, symmetrically, ICS1(G) is neither
8903 // better nor worse than ICS1(F).
8904 unsigned StartArg = 0;
8905 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8906 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008907
George Burgess IVfbad5b22016-09-07 20:03:19 +00008908 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
8909 // We don't allow incompatible pointer conversions in C++.
8910 if (!S.getLangOpts().CPlusPlus)
8911 return ICS.isStandard() &&
8912 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
8913
8914 // The only ill-formed conversion we allow in C++ is the string literal to
8915 // char* conversion, which is only considered ill-formed after C++11.
8916 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
8917 hasDeprecatedStringLiteralToCharPtrConversion(ICS);
8918 };
8919
8920 // Define functions that don't require ill-formed conversions for a given
8921 // argument to be better candidates than functions that do.
Richard Smith6eedfe72017-01-09 08:01:21 +00008922 unsigned NumArgs = Cand1.Conversions.size();
8923 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
George Burgess IVfbad5b22016-09-07 20:03:19 +00008924 bool HasBetterConversion = false;
8925 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
8926 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
8927 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
8928 if (Cand1Bad != Cand2Bad) {
8929 if (Cand1Bad)
8930 return false;
8931 HasBetterConversion = true;
8932 }
8933 }
8934
8935 if (HasBetterConversion)
8936 return true;
8937
Douglas Gregord3cb3562009-07-07 23:38:56 +00008938 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00008939 // A viable function F1 is defined to be a better function than another
8940 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00008941 // conversion sequence than ICSi(F2), and then...
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008942 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Richard Smith0f59cb32015-12-18 21:45:41 +00008943 switch (CompareImplicitConversionSequences(S, Loc,
John McCall5c32be02010-08-24 20:38:10 +00008944 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008945 Cand2.Conversions[ArgIdx])) {
8946 case ImplicitConversionSequence::Better:
8947 // Cand1 has a better conversion sequence.
8948 HasBetterConversion = true;
8949 break;
8950
8951 case ImplicitConversionSequence::Worse:
8952 // Cand1 can't be better than Cand2.
8953 return false;
8954
8955 case ImplicitConversionSequence::Indistinguishable:
8956 // Do nothing.
8957 break;
8958 }
8959 }
8960
Mike Stump11289f42009-09-09 15:08:12 +00008961 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00008962 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008963 if (HasBetterConversion)
8964 return true;
8965
Douglas Gregora1f013e2008-11-07 22:36:19 +00008966 // -- the context is an initialization by user-defined conversion
8967 // (see 8.5, 13.3.1.5) and the standard conversion sequence
8968 // from the return type of F1 to the destination type (i.e.,
8969 // the type of the entity being initialized) is a better
8970 // conversion sequence than the standard conversion sequence
8971 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00008972 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00008973 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00008974 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregor2837aa22012-02-22 17:32:19 +00008975 // First check whether we prefer one of the conversion functions over the
8976 // other. This only distinguishes the results in non-standard, extension
8977 // cases such as the conversion from a lambda closure type to a function
8978 // pointer or block.
Richard Smithec2748a2014-05-17 04:36:39 +00008979 ImplicitConversionSequence::CompareKind Result =
8980 compareConversionFunctions(S, Cand1.Function, Cand2.Function);
8981 if (Result == ImplicitConversionSequence::Indistinguishable)
Richard Smith0f59cb32015-12-18 21:45:41 +00008982 Result = CompareStandardConversionSequences(S, Loc,
Richard Smithec2748a2014-05-17 04:36:39 +00008983 Cand1.FinalConversion,
8984 Cand2.FinalConversion);
Richard Smith6fdeaab2014-05-17 01:58:45 +00008985
Richard Smithec2748a2014-05-17 04:36:39 +00008986 if (Result != ImplicitConversionSequence::Indistinguishable)
8987 return Result == ImplicitConversionSequence::Better;
Richard Smith6fdeaab2014-05-17 01:58:45 +00008988
8989 // FIXME: Compare kind of reference binding if conversion functions
8990 // convert to a reference type used in direct reference binding, per
8991 // C++14 [over.match.best]p1 section 2 bullet 3.
8992 }
8993
Richard Smith32918772017-02-14 00:25:28 +00008994 // -- F1 is generated from a deduction-guide and F2 is not
Richard Smithbc491202017-02-17 20:05:37 +00008995 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
8996 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
8997 if (Guide1 && Guide2 && Guide1->isImplicit() != Guide2->isImplicit())
8998 return Guide2->isImplicit();
Richard Smith32918772017-02-14 00:25:28 +00008999
Richard Smith6fdeaab2014-05-17 01:58:45 +00009000 // -- F1 is a non-template function and F2 is a function template
9001 // specialization, or, if not that,
9002 bool Cand1IsSpecialization = Cand1.Function &&
9003 Cand1.Function->getPrimaryTemplate();
9004 bool Cand2IsSpecialization = Cand2.Function &&
9005 Cand2.Function->getPrimaryTemplate();
9006 if (Cand1IsSpecialization != Cand2IsSpecialization)
9007 return Cand2IsSpecialization;
9008
9009 // -- F1 and F2 are function template specializations, and the function
9010 // template for F1 is more specialized than the template for F2
9011 // according to the partial ordering rules described in 14.5.5.2, or,
9012 // if not that,
9013 if (Cand1IsSpecialization && Cand2IsSpecialization) {
9014 if (FunctionTemplateDecl *BetterTemplate
9015 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
9016 Cand2.Function->getPrimaryTemplate(),
9017 Loc,
9018 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
9019 : TPOC_Call,
9020 Cand1.ExplicitCallArguments,
9021 Cand2.ExplicitCallArguments))
9022 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregora1f013e2008-11-07 22:36:19 +00009023 }
9024
Richard Smith5179eb72016-06-28 19:03:57 +00009025 // FIXME: Work around a defect in the C++17 inheriting constructor wording.
9026 // A derived-class constructor beats an (inherited) base class constructor.
9027 bool Cand1IsInherited =
9028 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
9029 bool Cand2IsInherited =
9030 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
9031 if (Cand1IsInherited != Cand2IsInherited)
9032 return Cand2IsInherited;
9033 else if (Cand1IsInherited) {
9034 assert(Cand2IsInherited);
9035 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
9036 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
9037 if (Cand1Class->isDerivedFrom(Cand2Class))
9038 return true;
9039 if (Cand2Class->isDerivedFrom(Cand1Class))
9040 return false;
9041 // Inherited from sibling base classes: still ambiguous.
9042 }
9043
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009044 // Check for enable_if value-based overload resolution.
George Burgess IV3dc166912016-05-10 01:59:34 +00009045 if (Cand1.Function && Cand2.Function) {
9046 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
9047 if (Cmp != Comparison::Equal)
9048 return Cmp == Comparison::Better;
9049 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009050
Justin Lebar25c4a812016-03-29 16:24:16 +00009051 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
Artem Belevich94a55e82015-09-22 17:22:59 +00009052 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9053 return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
9054 S.IdentifyCUDAPreference(Caller, Cand2.Function);
9055 }
9056
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009057 bool HasPS1 = Cand1.Function != nullptr &&
9058 functionHasPassObjectSizeParams(Cand1.Function);
9059 bool HasPS2 = Cand2.Function != nullptr &&
9060 functionHasPassObjectSizeParams(Cand2.Function);
9061 return HasPS1 != HasPS2 && HasPS1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009062}
9063
Richard Smith2dbe4042015-11-04 19:26:32 +00009064/// Determine whether two declarations are "equivalent" for the purposes of
Richard Smith26210db2015-11-13 03:52:13 +00009065/// name lookup and overload resolution. This applies when the same internal/no
9066/// linkage entity is defined by two modules (probably by textually including
Richard Smith2dbe4042015-11-04 19:26:32 +00009067/// the same header). In such a case, we don't consider the declarations to
9068/// declare the same entity, but we also don't want lookups with both
9069/// declarations visible to be ambiguous in some cases (this happens when using
9070/// a modularized libstdc++).
9071bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
9072 const NamedDecl *B) {
Richard Smith26210db2015-11-13 03:52:13 +00009073 auto *VA = dyn_cast_or_null<ValueDecl>(A);
9074 auto *VB = dyn_cast_or_null<ValueDecl>(B);
9075 if (!VA || !VB)
9076 return false;
9077
9078 // The declarations must be declaring the same name as an internal linkage
9079 // entity in different modules.
9080 if (!VA->getDeclContext()->getRedeclContext()->Equals(
9081 VB->getDeclContext()->getRedeclContext()) ||
9082 getOwningModule(const_cast<ValueDecl *>(VA)) ==
9083 getOwningModule(const_cast<ValueDecl *>(VB)) ||
9084 VA->isExternallyVisible() || VB->isExternallyVisible())
9085 return false;
9086
9087 // Check that the declarations appear to be equivalent.
9088 //
9089 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
9090 // For constants and functions, we should check the initializer or body is
9091 // the same. For non-constant variables, we shouldn't allow it at all.
9092 if (Context.hasSameType(VA->getType(), VB->getType()))
9093 return true;
9094
9095 // Enum constants within unnamed enumerations will have different types, but
9096 // may still be similar enough to be interchangeable for our purposes.
9097 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
9098 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
9099 // Only handle anonymous enums. If the enumerations were named and
9100 // equivalent, they would have been merged to the same type.
9101 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
9102 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
9103 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
9104 !Context.hasSameType(EnumA->getIntegerType(),
9105 EnumB->getIntegerType()))
9106 return false;
9107 // Allow this only if the value is the same for both enumerators.
9108 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
9109 }
9110 }
9111
9112 // Nothing else is sufficiently similar.
9113 return false;
Richard Smith2dbe4042015-11-04 19:26:32 +00009114}
9115
9116void Sema::diagnoseEquivalentInternalLinkageDeclarations(
9117 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
9118 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
9119
9120 Module *M = getOwningModule(const_cast<NamedDecl*>(D));
9121 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
9122 << !M << (M ? M->getFullModuleName() : "");
9123
9124 for (auto *E : Equiv) {
9125 Module *M = getOwningModule(const_cast<NamedDecl*>(E));
9126 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
9127 << !M << (M ? M->getFullModuleName() : "");
9128 }
Richard Smith896c66e2015-10-21 07:13:52 +00009129}
9130
Mike Stump11289f42009-09-09 15:08:12 +00009131/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009132/// within an overload candidate set.
9133///
James Dennettffad8b72012-06-22 08:10:18 +00009134/// \param Loc The location of the function name (or operator symbol) for
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009135/// which overload resolution occurs.
9136///
James Dennettffad8b72012-06-22 08:10:18 +00009137/// \param Best If overload resolution was successful or found a deleted
9138/// function, \p Best points to the candidate function found.
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009139///
9140/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00009141OverloadingResult
9142OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00009143 iterator &Best,
Chandler Carruth30141632011-02-25 19:41:05 +00009144 bool UserDefinedConversion) {
Artem Belevich18609102016-02-12 18:29:18 +00009145 llvm::SmallVector<OverloadCandidate *, 16> Candidates;
9146 std::transform(begin(), end(), std::back_inserter(Candidates),
9147 [](OverloadCandidate &Cand) { return &Cand; });
9148
Justin Lebar66a2ab92016-08-10 00:40:43 +00009149 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
9150 // are accepted by both clang and NVCC. However, during a particular
Artem Belevich18609102016-02-12 18:29:18 +00009151 // compilation mode only one call variant is viable. We need to
9152 // exclude non-viable overload candidates from consideration based
9153 // only on their host/device attributes. Specifically, if one
9154 // candidate call is WrongSide and the other is SameSide, we ignore
9155 // the WrongSide candidate.
Justin Lebar25c4a812016-03-29 16:24:16 +00009156 if (S.getLangOpts().CUDA) {
Artem Belevich18609102016-02-12 18:29:18 +00009157 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9158 bool ContainsSameSideCandidate =
9159 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
9160 return Cand->Function &&
9161 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9162 Sema::CFP_SameSide;
9163 });
9164 if (ContainsSameSideCandidate) {
9165 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
9166 return Cand->Function &&
9167 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9168 Sema::CFP_WrongSide;
9169 };
George Burgess IV8684b032017-01-04 19:16:29 +00009170 llvm::erase_if(Candidates, IsWrongSideCandidate);
Artem Belevich18609102016-02-12 18:29:18 +00009171 }
9172 }
9173
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009174 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00009175 Best = end();
Artem Belevich18609102016-02-12 18:29:18 +00009176 for (auto *Cand : Candidates)
John McCall5c32be02010-08-24 20:38:10 +00009177 if (Cand->Viable)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009178 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00009179 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009180 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009181
9182 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00009183 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009184 return OR_No_Viable_Function;
9185
Richard Smith2dbe4042015-11-04 19:26:32 +00009186 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
Richard Smith896c66e2015-10-21 07:13:52 +00009187
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009188 // Make sure that this function is better than every other viable
9189 // function. If not, we have an ambiguity.
Artem Belevich18609102016-02-12 18:29:18 +00009190 for (auto *Cand : Candidates) {
Mike Stump11289f42009-09-09 15:08:12 +00009191 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009192 Cand != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009193 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00009194 UserDefinedConversion)) {
Richard Smith2dbe4042015-11-04 19:26:32 +00009195 if (S.isEquivalentInternalLinkageDeclaration(Best->Function,
9196 Cand->Function)) {
9197 EquivalentCands.push_back(Cand->Function);
Richard Smith896c66e2015-10-21 07:13:52 +00009198 continue;
9199 }
9200
John McCall5c32be02010-08-24 20:38:10 +00009201 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009202 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00009203 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009204 }
Mike Stump11289f42009-09-09 15:08:12 +00009205
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009206 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00009207 if (Best->Function &&
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00009208 (Best->Function->isDeleted() ||
George Burgess IVce6284b2017-01-28 02:19:40 +00009209 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor171c45a2009-02-18 21:56:37 +00009210 return OR_Deleted;
9211
Richard Smith2dbe4042015-11-04 19:26:32 +00009212 if (!EquivalentCands.empty())
9213 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
9214 EquivalentCands);
Richard Smith896c66e2015-10-21 07:13:52 +00009215
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009216 return OR_Success;
9217}
9218
John McCall53262c92010-01-12 02:15:36 +00009219namespace {
9220
9221enum OverloadCandidateKind {
9222 oc_function,
9223 oc_method,
9224 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00009225 oc_function_template,
9226 oc_method_template,
9227 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00009228 oc_implicit_default_constructor,
9229 oc_implicit_copy_constructor,
Alexis Hunt119c10e2011-05-25 23:16:36 +00009230 oc_implicit_move_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00009231 oc_implicit_copy_assignment,
Alexis Hunt119c10e2011-05-25 23:16:36 +00009232 oc_implicit_move_assignment,
Richard Smith5179eb72016-06-28 19:03:57 +00009233 oc_inherited_constructor,
9234 oc_inherited_constructor_template
John McCall53262c92010-01-12 02:15:36 +00009235};
9236
George Burgess IVd66d37c2016-10-28 21:42:06 +00009237static OverloadCandidateKind
9238ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
9239 std::string &Description) {
John McCalle1ac8d12010-01-13 00:25:19 +00009240 bool isTemplate = false;
9241
9242 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
9243 isTemplate = true;
9244 Description = S.getTemplateArgumentBindingsText(
9245 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
9246 }
John McCallfd0b2f82010-01-06 09:43:14 +00009247
9248 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
Richard Smith5179eb72016-06-28 19:03:57 +00009249 if (!Ctor->isImplicit()) {
9250 if (isa<ConstructorUsingShadowDecl>(Found))
9251 return isTemplate ? oc_inherited_constructor_template
9252 : oc_inherited_constructor;
9253 else
9254 return isTemplate ? oc_constructor_template : oc_constructor;
9255 }
Sebastian Redl08905022011-02-05 19:23:19 +00009256
Alexis Hunt119c10e2011-05-25 23:16:36 +00009257 if (Ctor->isDefaultConstructor())
9258 return oc_implicit_default_constructor;
9259
9260 if (Ctor->isMoveConstructor())
9261 return oc_implicit_move_constructor;
9262
9263 assert(Ctor->isCopyConstructor() &&
9264 "unexpected sort of implicit constructor");
9265 return oc_implicit_copy_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00009266 }
9267
9268 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
9269 // This actually gets spelled 'candidate function' for now, but
9270 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00009271 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00009272 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00009273
Alexis Hunt119c10e2011-05-25 23:16:36 +00009274 if (Meth->isMoveAssignmentOperator())
9275 return oc_implicit_move_assignment;
9276
Douglas Gregor12695102012-02-10 08:36:38 +00009277 if (Meth->isCopyAssignmentOperator())
9278 return oc_implicit_copy_assignment;
9279
9280 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
9281 return oc_method;
John McCall53262c92010-01-12 02:15:36 +00009282 }
9283
John McCalle1ac8d12010-01-13 00:25:19 +00009284 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00009285}
9286
Richard Smith5179eb72016-06-28 19:03:57 +00009287void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
9288 // FIXME: It'd be nice to only emit a note once per using-decl per overload
9289 // set.
9290 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
9291 S.Diag(FoundDecl->getLocation(),
9292 diag::note_ovl_candidate_inherited_constructor)
9293 << Shadow->getNominatedBaseClass();
Sebastian Redl08905022011-02-05 19:23:19 +00009294}
9295
John McCall53262c92010-01-12 02:15:36 +00009296} // end anonymous namespace
9297
George Burgess IV5f21c712015-10-12 19:57:04 +00009298static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
9299 const FunctionDecl *FD) {
9300 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
9301 bool AlwaysTrue;
9302 if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
9303 return false;
9304 if (!AlwaysTrue)
9305 return false;
9306 }
9307 return true;
9308}
9309
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009310/// \brief Returns true if we can take the address of the function.
9311///
9312/// \param Complain - If true, we'll emit a diagnostic
9313/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
9314/// we in overload resolution?
9315/// \param Loc - The location of the statement we're complaining about. Ignored
9316/// if we're not complaining, or if we're in overload resolution.
9317static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
9318 bool Complain,
9319 bool InOverloadResolution,
9320 SourceLocation Loc) {
9321 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
9322 if (Complain) {
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009323 if (InOverloadResolution)
9324 S.Diag(FD->getLocStart(),
9325 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
9326 else
9327 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
9328 }
9329 return false;
9330 }
9331
George Burgess IV21081362016-07-24 23:12:40 +00009332 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
9333 return P->hasAttr<PassObjectSizeAttr>();
9334 });
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009335 if (I == FD->param_end())
9336 return true;
9337
9338 if (Complain) {
9339 // Add one to ParamNo because it's user-facing
9340 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
9341 if (InOverloadResolution)
9342 S.Diag(FD->getLocation(),
9343 diag::note_ovl_candidate_has_pass_object_size_params)
9344 << ParamNo;
9345 else
9346 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
9347 << FD << ParamNo;
9348 }
9349 return false;
9350}
9351
9352static bool checkAddressOfCandidateIsAvailable(Sema &S,
9353 const FunctionDecl *FD) {
9354 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
9355 /*InOverloadResolution=*/true,
9356 /*Loc=*/SourceLocation());
9357}
9358
9359bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
9360 bool Complain,
9361 SourceLocation Loc) {
9362 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
9363 /*InOverloadResolution=*/false,
9364 Loc);
9365}
9366
John McCall53262c92010-01-12 02:15:36 +00009367// Notes the location of an overload candidate.
Richard Smithc2bebe92016-05-11 20:37:46 +00009368void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
9369 QualType DestType, bool TakingAddress) {
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009370 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
9371 return;
9372
John McCalle1ac8d12010-01-13 00:25:19 +00009373 std::string FnDesc;
Richard Smithc2bebe92016-05-11 20:37:46 +00009374 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Found, Fn, FnDesc);
Richard Trieucaff2472011-11-23 22:32:32 +00009375 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
Saleem Abdulrasool78704fb2016-12-22 04:26:57 +00009376 << (unsigned) K << Fn << FnDesc;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009377
9378 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
Richard Trieucaff2472011-11-23 22:32:32 +00009379 Diag(Fn->getLocation(), PD);
Richard Smith5179eb72016-06-28 19:03:57 +00009380 MaybeEmitInheritedConstructorNote(*this, Found);
John McCallfd0b2f82010-01-06 09:43:14 +00009381}
9382
Nick Lewyckyed4265c2013-09-22 10:06:01 +00009383// Notes the location of all overload candidates designated through
Douglas Gregorb491ed32011-02-19 21:32:49 +00009384// OverloadedExpr
George Burgess IV5f21c712015-10-12 19:57:04 +00009385void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
9386 bool TakingAddress) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009387 assert(OverloadedExpr->getType() == Context.OverloadTy);
9388
9389 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
9390 OverloadExpr *OvlExpr = Ovl.Expression;
9391
9392 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9393 IEnd = OvlExpr->decls_end();
9394 I != IEnd; ++I) {
9395 if (FunctionTemplateDecl *FunTmpl =
9396 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Smithc2bebe92016-05-11 20:37:46 +00009397 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType,
George Burgess IV5f21c712015-10-12 19:57:04 +00009398 TakingAddress);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009399 } else if (FunctionDecl *Fun
9400 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Smithc2bebe92016-05-11 20:37:46 +00009401 NoteOverloadCandidate(*I, Fun, DestType, TakingAddress);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009402 }
9403 }
9404}
9405
John McCall0d1da222010-01-12 00:44:57 +00009406/// Diagnoses an ambiguous conversion. The partial diagnostic is the
9407/// "lead" diagnostic; it will be given two arguments, the source and
9408/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00009409void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
9410 Sema &S,
9411 SourceLocation CaretLoc,
9412 const PartialDiagnostic &PDiag) const {
9413 S.Diag(CaretLoc, PDiag)
9414 << Ambiguous.getFromType() << Ambiguous.getToType();
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00009415 // FIXME: The note limiting machinery is borrowed from
9416 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
9417 // refactoring here.
9418 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9419 unsigned CandsShown = 0;
9420 AmbiguousConversionSequence::const_iterator I, E;
9421 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
9422 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9423 break;
9424 ++CandsShown;
Richard Smithc2bebe92016-05-11 20:37:46 +00009425 S.NoteOverloadCandidate(I->first, I->second);
John McCall0d1da222010-01-12 00:44:57 +00009426 }
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00009427 if (I != E)
9428 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
John McCall12f97bc2010-01-08 04:41:39 +00009429}
9430
Richard Smith17c00b42014-11-12 01:24:00 +00009431static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009432 unsigned I, bool TakingCandidateAddress) {
John McCall6a61b522010-01-13 09:16:55 +00009433 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
9434 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00009435 assert(Cand->Function && "for now, candidate must be a function");
9436 FunctionDecl *Fn = Cand->Function;
9437
9438 // There's a conversion slot for the object argument if this is a
9439 // non-constructor method. Note that 'I' corresponds the
9440 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00009441 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00009442 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00009443 if (I == 0)
9444 isObjectArgument = true;
9445 else
9446 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00009447 }
9448
John McCalle1ac8d12010-01-13 00:25:19 +00009449 std::string FnDesc;
Richard Smithc2bebe92016-05-11 20:37:46 +00009450 OverloadCandidateKind FnKind =
9451 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
John McCalle1ac8d12010-01-13 00:25:19 +00009452
John McCall6a61b522010-01-13 09:16:55 +00009453 Expr *FromExpr = Conv.Bad.FromExpr;
9454 QualType FromTy = Conv.Bad.getFromType();
9455 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00009456
John McCallfb7ad0f2010-02-02 02:42:52 +00009457 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00009458 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00009459 Expr *E = FromExpr->IgnoreParens();
9460 if (isa<UnaryOperator>(E))
9461 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00009462 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00009463
9464 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
9465 << (unsigned) FnKind << FnDesc
9466 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9467 << ToTy << Name << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009468 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCallfb7ad0f2010-02-02 02:42:52 +00009469 return;
9470 }
9471
John McCall6d174642010-01-23 08:10:49 +00009472 // Do some hand-waving analysis to see if the non-viability is due
9473 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00009474 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
9475 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
9476 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
9477 CToTy = RT->getPointeeType();
9478 else {
9479 // TODO: detect and diagnose the full richness of const mismatches.
9480 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
Richard Trieucc3949d2016-02-18 22:34:54 +00009481 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
9482 CFromTy = FromPT->getPointeeType();
9483 CToTy = ToPT->getPointeeType();
9484 }
John McCall47000992010-01-14 03:28:57 +00009485 }
9486
9487 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
9488 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall47000992010-01-14 03:28:57 +00009489 Qualifiers FromQs = CFromTy.getQualifiers();
9490 Qualifiers ToQs = CToTy.getQualifiers();
9491
9492 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
9493 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
9494 << (unsigned) FnKind << FnDesc
9495 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9496 << FromTy
9497 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
9498 << (unsigned) isObjectArgument << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009499 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall47000992010-01-14 03:28:57 +00009500 return;
9501 }
9502
John McCall31168b02011-06-15 23:02:42 +00009503 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00009504 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCall31168b02011-06-15 23:02:42 +00009505 << (unsigned) FnKind << FnDesc
9506 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9507 << FromTy
9508 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
9509 << (unsigned) isObjectArgument << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009510 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall31168b02011-06-15 23:02:42 +00009511 return;
9512 }
9513
Douglas Gregoraec25842011-04-26 23:16:46 +00009514 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
9515 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
9516 << (unsigned) FnKind << FnDesc
9517 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9518 << FromTy
9519 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
9520 << (unsigned) isObjectArgument << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009521 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Douglas Gregoraec25842011-04-26 23:16:46 +00009522 return;
9523 }
9524
Andrey Bokhanko45d41322016-05-11 18:38:21 +00009525 if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
9526 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
9527 << (unsigned) FnKind << FnDesc
9528 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9529 << FromTy << FromQs.hasUnaligned() << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009530 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Andrey Bokhanko45d41322016-05-11 18:38:21 +00009531 return;
9532 }
9533
John McCall47000992010-01-14 03:28:57 +00009534 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
9535 assert(CVR && "unexpected qualifiers mismatch");
9536
9537 if (isObjectArgument) {
9538 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
9539 << (unsigned) FnKind << FnDesc
9540 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9541 << FromTy << (CVR - 1);
9542 } else {
9543 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
9544 << (unsigned) FnKind << FnDesc
9545 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9546 << FromTy << (CVR - 1) << I+1;
9547 }
Richard Smith5179eb72016-06-28 19:03:57 +00009548 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall47000992010-01-14 03:28:57 +00009549 return;
9550 }
9551
Sebastian Redla72462c2011-09-24 17:48:32 +00009552 // Special diagnostic for failure to convert an initializer list, since
9553 // telling the user that it has type void is not useful.
9554 if (FromExpr && isa<InitListExpr>(FromExpr)) {
9555 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
9556 << (unsigned) FnKind << FnDesc
9557 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9558 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009559 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Sebastian Redla72462c2011-09-24 17:48:32 +00009560 return;
9561 }
9562
John McCall6d174642010-01-23 08:10:49 +00009563 // Diagnose references or pointers to incomplete types differently,
9564 // since it's far from impossible that the incompleteness triggered
9565 // the failure.
9566 QualType TempFromTy = FromTy.getNonReferenceType();
9567 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
9568 TempFromTy = PTy->getPointeeType();
9569 if (TempFromTy->isIncompleteType()) {
David Blaikieac928932016-03-04 22:29:11 +00009570 // Emit the generic diagnostic and, optionally, add the hints to it.
John McCall6d174642010-01-23 08:10:49 +00009571 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
9572 << (unsigned) FnKind << FnDesc
9573 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
David Blaikieac928932016-03-04 22:29:11 +00009574 << FromTy << ToTy << (unsigned) isObjectArgument << I+1
9575 << (unsigned) (Cand->Fix.Kind);
9576
Richard Smith5179eb72016-06-28 19:03:57 +00009577 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall6d174642010-01-23 08:10:49 +00009578 return;
9579 }
9580
Douglas Gregor56f2e342010-06-30 23:01:39 +00009581 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009582 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00009583 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
9584 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
9585 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9586 FromPtrTy->getPointeeType()) &&
9587 !FromPtrTy->getPointeeType()->isIncompleteType() &&
9588 !ToPtrTy->getPointeeType()->isIncompleteType() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00009589 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00009590 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009591 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00009592 }
9593 } else if (const ObjCObjectPointerType *FromPtrTy
9594 = FromTy->getAs<ObjCObjectPointerType>()) {
9595 if (const ObjCObjectPointerType *ToPtrTy
9596 = ToTy->getAs<ObjCObjectPointerType>())
9597 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
9598 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
9599 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9600 FromPtrTy->getPointeeType()) &&
9601 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009602 BaseToDerivedConversion = 2;
9603 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009604 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
9605 !FromTy->isIncompleteType() &&
9606 !ToRefTy->getPointeeType()->isIncompleteType() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00009607 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009608 BaseToDerivedConversion = 3;
9609 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
9610 ToTy.getNonReferenceType().getCanonicalType() ==
9611 FromTy.getNonReferenceType().getCanonicalType()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009612 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
9613 << (unsigned) FnKind << FnDesc
9614 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9615 << (unsigned) isObjectArgument << I + 1;
Richard Smith5179eb72016-06-28 19:03:57 +00009616 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009617 return;
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009618 }
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009619 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009620
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009621 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009622 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009623 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00009624 << (unsigned) FnKind << FnDesc
9625 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009626 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009627 << FromTy << ToTy << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009628 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Douglas Gregor56f2e342010-06-30 23:01:39 +00009629 return;
9630 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009631
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00009632 if (isa<ObjCObjectPointerType>(CFromTy) &&
9633 isa<PointerType>(CToTy)) {
9634 Qualifiers FromQs = CFromTy.getQualifiers();
9635 Qualifiers ToQs = CToTy.getQualifiers();
9636 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9637 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
9638 << (unsigned) FnKind << FnDesc
9639 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9640 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009641 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00009642 return;
9643 }
9644 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009645
9646 if (TakingCandidateAddress &&
9647 !checkAddressOfCandidateIsAvailable(S, Cand->Function))
9648 return;
9649
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009650 // Emit the generic diagnostic and, optionally, add the hints to it.
9651 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
9652 FDiag << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00009653 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009654 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
9655 << (unsigned) (Cand->Fix.Kind);
9656
9657 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer490afa62012-01-14 21:05:10 +00009658 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
9659 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009660 FDiag << *HI;
9661 S.Diag(Fn->getLocation(), FDiag);
9662
Richard Smith5179eb72016-06-28 19:03:57 +00009663 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall6a61b522010-01-13 09:16:55 +00009664}
9665
Larisse Voufo98b20f12013-07-19 23:00:19 +00009666/// Additional arity mismatch diagnosis specific to a function overload
9667/// candidates. This is not covered by the more general DiagnoseArityMismatch()
9668/// over a candidate in any candidate set.
Richard Smith17c00b42014-11-12 01:24:00 +00009669static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
9670 unsigned NumArgs) {
John McCall6a61b522010-01-13 09:16:55 +00009671 FunctionDecl *Fn = Cand->Function;
John McCall6a61b522010-01-13 09:16:55 +00009672 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009673
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009674 // With invalid overloaded operators, it's possible that we think we
Larisse Voufo98b20f12013-07-19 23:00:19 +00009675 // have an arity mismatch when in fact it looks like we have the
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009676 // right number of arguments, because only overloaded operators have
9677 // the weird behavior of overloading member and non-member functions.
9678 // Just don't report anything.
9679 if (Fn->isInvalidDecl() &&
9680 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009681 return true;
9682
9683 if (NumArgs < MinParams) {
9684 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
9685 (Cand->FailureKind == ovl_fail_bad_deduction &&
9686 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
9687 } else {
9688 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
9689 (Cand->FailureKind == ovl_fail_bad_deduction &&
9690 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
9691 }
9692
9693 return false;
9694}
9695
9696/// General arity mismatch diagnosis over a candidate in a candidate set.
Richard Smithc2bebe92016-05-11 20:37:46 +00009697static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
9698 unsigned NumFormalArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009699 assert(isa<FunctionDecl>(D) &&
9700 "The templated declaration should at least be a function"
9701 " when diagnosing bad template argument deduction due to too many"
9702 " or too few arguments");
9703
9704 FunctionDecl *Fn = cast<FunctionDecl>(D);
9705
9706 // TODO: treat calls to a missing default constructor as a special case
9707 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
9708 unsigned MinParams = Fn->getMinRequiredArguments();
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009709
John McCall6a61b522010-01-13 09:16:55 +00009710 // at least / at most / exactly
9711 unsigned mode, modeCount;
9712 if (NumFormalArgs < MinParams) {
Alp Toker9cacbab2014-01-20 20:26:09 +00009713 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
9714 FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00009715 mode = 0; // "at least"
9716 else
9717 mode = 2; // "exactly"
9718 modeCount = MinParams;
9719 } else {
Alp Toker9cacbab2014-01-20 20:26:09 +00009720 if (MinParams != FnTy->getNumParams())
John McCall6a61b522010-01-13 09:16:55 +00009721 mode = 1; // "at most"
9722 else
9723 mode = 2; // "exactly"
Alp Toker9cacbab2014-01-20 20:26:09 +00009724 modeCount = FnTy->getNumParams();
John McCall6a61b522010-01-13 09:16:55 +00009725 }
9726
9727 std::string Description;
Richard Smithc2bebe92016-05-11 20:37:46 +00009728 OverloadCandidateKind FnKind =
9729 ClassifyOverloadCandidate(S, Found, Fn, Description);
John McCall6a61b522010-01-13 09:16:55 +00009730
Richard Smith10ff50d2012-05-11 05:16:41 +00009731 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
9732 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
Craig Topperc3ec1492014-05-26 06:22:03 +00009733 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9734 << mode << Fn->getParamDecl(0) << NumFormalArgs;
Richard Smith10ff50d2012-05-11 05:16:41 +00009735 else
9736 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Craig Topperc3ec1492014-05-26 06:22:03 +00009737 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9738 << mode << modeCount << NumFormalArgs;
Richard Smith5179eb72016-06-28 19:03:57 +00009739 MaybeEmitInheritedConstructorNote(S, Found);
John McCalle1ac8d12010-01-13 00:25:19 +00009740}
9741
Larisse Voufo98b20f12013-07-19 23:00:19 +00009742/// Arity mismatch diagnosis specific to a function overload candidate.
Richard Smith17c00b42014-11-12 01:24:00 +00009743static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
9744 unsigned NumFormalArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009745 if (!CheckArityMismatch(S, Cand, NumFormalArgs))
Richard Smithc2bebe92016-05-11 20:37:46 +00009746 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
Larisse Voufo98b20f12013-07-19 23:00:19 +00009747}
Larisse Voufo47c08452013-07-19 22:53:23 +00009748
Richard Smith17c00b42014-11-12 01:24:00 +00009749static TemplateDecl *getDescribedTemplate(Decl *Templated) {
Serge Pavlov7dcc97e2016-04-19 06:19:52 +00009750 if (TemplateDecl *TD = Templated->getDescribedTemplate())
9751 return TD;
Larisse Voufo98b20f12013-07-19 23:00:19 +00009752 llvm_unreachable("Unsupported: Getting the described template declaration"
9753 " for bad deduction diagnosis");
9754}
9755
9756/// Diagnose a failed template-argument deduction.
Richard Smithc2bebe92016-05-11 20:37:46 +00009757static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
Richard Smith17c00b42014-11-12 01:24:00 +00009758 DeductionFailureInfo &DeductionFailure,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009759 unsigned NumArgs,
9760 bool TakingCandidateAddress) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009761 TemplateParameter Param = DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009762 NamedDecl *ParamD;
9763 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
9764 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
9765 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
Larisse Voufo98b20f12013-07-19 23:00:19 +00009766 switch (DeductionFailure.Result) {
John McCall8b9ed552010-02-01 18:53:26 +00009767 case Sema::TDK_Success:
9768 llvm_unreachable("TDK_success while diagnosing bad deduction");
9769
9770 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00009771 assert(ParamD && "no parameter found for incomplete deduction result");
Larisse Voufo98b20f12013-07-19 23:00:19 +00009772 S.Diag(Templated->getLocation(),
9773 diag::note_ovl_candidate_incomplete_deduction)
9774 << ParamD->getDeclName();
Richard Smith5179eb72016-06-28 19:03:57 +00009775 MaybeEmitInheritedConstructorNote(S, Found);
John McCall8b9ed552010-02-01 18:53:26 +00009776 return;
9777 }
9778
John McCall42d7d192010-08-05 09:05:08 +00009779 case Sema::TDK_Underqualified: {
9780 assert(ParamD && "no parameter found for bad qualifiers deduction result");
9781 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
9782
Larisse Voufo98b20f12013-07-19 23:00:19 +00009783 QualType Param = DeductionFailure.getFirstArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00009784
9785 // Param will have been canonicalized, but it should just be a
9786 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00009787 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00009788 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00009789 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00009790 assert(S.Context.hasSameType(Param, NonCanonParam));
9791
9792 // Arg has also been canonicalized, but there's nothing we can do
9793 // about that. It also doesn't matter as much, because it won't
9794 // have any template parameters in it (because deduction isn't
9795 // done on dependent types).
Larisse Voufo98b20f12013-07-19 23:00:19 +00009796 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00009797
Larisse Voufo98b20f12013-07-19 23:00:19 +00009798 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
9799 << ParamD->getDeclName() << Arg << NonCanonParam;
Richard Smith5179eb72016-06-28 19:03:57 +00009800 MaybeEmitInheritedConstructorNote(S, Found);
John McCall42d7d192010-08-05 09:05:08 +00009801 return;
9802 }
9803
9804 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00009805 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009806 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009807 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009808 which = 0;
Richard Smith593d6a12016-12-23 01:30:39 +00009809 else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
9810 // Deduction might have failed because we deduced arguments of two
9811 // different types for a non-type template parameter.
9812 // FIXME: Use a different TDK value for this.
9813 QualType T1 =
9814 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
9815 QualType T2 =
9816 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
9817 if (!S.Context.hasSameType(T1, T2)) {
9818 S.Diag(Templated->getLocation(),
9819 diag::note_ovl_candidate_inconsistent_deduction_types)
9820 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
9821 << *DeductionFailure.getSecondArg() << T2;
9822 MaybeEmitInheritedConstructorNote(S, Found);
9823 return;
9824 }
9825
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009826 which = 1;
Richard Smith593d6a12016-12-23 01:30:39 +00009827 } else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009828 which = 2;
9829 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009830
Larisse Voufo98b20f12013-07-19 23:00:19 +00009831 S.Diag(Templated->getLocation(),
9832 diag::note_ovl_candidate_inconsistent_deduction)
9833 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
9834 << *DeductionFailure.getSecondArg();
Richard Smith5179eb72016-06-28 19:03:57 +00009835 MaybeEmitInheritedConstructorNote(S, Found);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009836 return;
9837 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00009838
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009839 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009840 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009841 if (ParamD->getDeclName())
Larisse Voufo98b20f12013-07-19 23:00:19 +00009842 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009843 diag::note_ovl_candidate_explicit_arg_mismatch_named)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009844 << ParamD->getDeclName();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009845 else {
9846 int index = 0;
9847 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
9848 index = TTP->getIndex();
9849 else if (NonTypeTemplateParmDecl *NTTP
9850 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
9851 index = NTTP->getIndex();
9852 else
9853 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
Larisse Voufo98b20f12013-07-19 23:00:19 +00009854 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009855 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009856 << (index + 1);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009857 }
Richard Smith5179eb72016-06-28 19:03:57 +00009858 MaybeEmitInheritedConstructorNote(S, Found);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009859 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009860
Douglas Gregor02eb4832010-05-08 18:13:28 +00009861 case Sema::TDK_TooManyArguments:
9862 case Sema::TDK_TooFewArguments:
Richard Smithc2bebe92016-05-11 20:37:46 +00009863 DiagnoseArityMismatch(S, Found, Templated, NumArgs);
Douglas Gregor02eb4832010-05-08 18:13:28 +00009864 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00009865
9866 case Sema::TDK_InstantiationDepth:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009867 S.Diag(Templated->getLocation(),
9868 diag::note_ovl_candidate_instantiation_depth);
Richard Smith5179eb72016-06-28 19:03:57 +00009869 MaybeEmitInheritedConstructorNote(S, Found);
Douglas Gregord09efd42010-05-08 20:07:26 +00009870 return;
9871
9872 case Sema::TDK_SubstitutionFailure: {
Richard Smith9ca64612012-05-07 09:03:25 +00009873 // Format the template argument list into the argument string.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009874 SmallString<128> TemplateArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00009875 if (TemplateArgumentList *Args =
Larisse Voufo98b20f12013-07-19 23:00:19 +00009876 DeductionFailure.getTemplateArgumentList()) {
Richard Smith9ca64612012-05-07 09:03:25 +00009877 TemplateArgString = " ";
9878 TemplateArgString += S.getTemplateArgumentBindingsText(
Larisse Voufo98b20f12013-07-19 23:00:19 +00009879 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
Richard Smith9ca64612012-05-07 09:03:25 +00009880 }
9881
Richard Smith6f8d2c62012-05-09 05:17:00 +00009882 // If this candidate was disabled by enable_if, say so.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009883 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
Richard Smith6f8d2c62012-05-09 05:17:00 +00009884 if (PDiag && PDiag->second.getDiagID() ==
9885 diag::err_typename_nested_not_found_enable_if) {
9886 // FIXME: Use the source range of the condition, and the fully-qualified
9887 // name of the enable_if template. These are both present in PDiag.
9888 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
9889 << "'enable_if'" << TemplateArgString;
9890 return;
9891 }
9892
Richard Smith9ca64612012-05-07 09:03:25 +00009893 // Format the SFINAE diagnostic into the argument string.
9894 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
9895 // formatted message in another diagnostic.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009896 SmallString<128> SFINAEArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00009897 SourceRange R;
Richard Smith6f8d2c62012-05-09 05:17:00 +00009898 if (PDiag) {
Richard Smith9ca64612012-05-07 09:03:25 +00009899 SFINAEArgString = ": ";
9900 R = SourceRange(PDiag->first, PDiag->first);
9901 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
9902 }
9903
Larisse Voufo98b20f12013-07-19 23:00:19 +00009904 S.Diag(Templated->getLocation(),
9905 diag::note_ovl_candidate_substitution_failure)
9906 << TemplateArgString << SFINAEArgString << R;
Richard Smith5179eb72016-06-28 19:03:57 +00009907 MaybeEmitInheritedConstructorNote(S, Found);
Douglas Gregord09efd42010-05-08 20:07:26 +00009908 return;
9909 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009910
Richard Smithc92d2062017-01-05 23:02:44 +00009911 case Sema::TDK_DeducedMismatch:
9912 case Sema::TDK_DeducedMismatchNested: {
Richard Smith9b534542015-12-31 02:02:54 +00009913 // Format the template argument list into the argument string.
9914 SmallString<128> TemplateArgString;
9915 if (TemplateArgumentList *Args =
9916 DeductionFailure.getTemplateArgumentList()) {
9917 TemplateArgString = " ";
9918 TemplateArgString += S.getTemplateArgumentBindingsText(
9919 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9920 }
9921
9922 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
9923 << (*DeductionFailure.getCallArgIndex() + 1)
9924 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
Richard Smithc92d2062017-01-05 23:02:44 +00009925 << TemplateArgString
9926 << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
Richard Smith9b534542015-12-31 02:02:54 +00009927 break;
9928 }
9929
Richard Trieue3732352013-04-08 21:11:40 +00009930 case Sema::TDK_NonDeducedMismatch: {
Richard Smith44ecdbd2013-01-31 05:19:49 +00009931 // FIXME: Provide a source location to indicate what we couldn't match.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009932 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
9933 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
Richard Trieue3732352013-04-08 21:11:40 +00009934 if (FirstTA.getKind() == TemplateArgument::Template &&
9935 SecondTA.getKind() == TemplateArgument::Template) {
9936 TemplateName FirstTN = FirstTA.getAsTemplate();
9937 TemplateName SecondTN = SecondTA.getAsTemplate();
9938 if (FirstTN.getKind() == TemplateName::Template &&
9939 SecondTN.getKind() == TemplateName::Template) {
9940 if (FirstTN.getAsTemplateDecl()->getName() ==
9941 SecondTN.getAsTemplateDecl()->getName()) {
9942 // FIXME: This fixes a bad diagnostic where both templates are named
9943 // the same. This particular case is a bit difficult since:
9944 // 1) It is passed as a string to the diagnostic printer.
9945 // 2) The diagnostic printer only attempts to find a better
9946 // name for types, not decls.
9947 // Ideally, this should folded into the diagnostic printer.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009948 S.Diag(Templated->getLocation(),
Richard Trieue3732352013-04-08 21:11:40 +00009949 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
9950 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
9951 return;
9952 }
9953 }
9954 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009955
9956 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
9957 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
9958 return;
9959
Faisal Vali2b391ab2013-09-26 19:54:12 +00009960 // FIXME: For generic lambda parameters, check if the function is a lambda
9961 // call operator, and if so, emit a prettier and more informative
9962 // diagnostic that mentions 'auto' and lambda in addition to
9963 // (or instead of?) the canonical template type parameters.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009964 S.Diag(Templated->getLocation(),
9965 diag::note_ovl_candidate_non_deduced_mismatch)
9966 << FirstTA << SecondTA;
Richard Smith44ecdbd2013-01-31 05:19:49 +00009967 return;
Richard Trieue3732352013-04-08 21:11:40 +00009968 }
John McCall8b9ed552010-02-01 18:53:26 +00009969 // TODO: diagnose these individually, then kill off
9970 // note_ovl_candidate_bad_deduction, which is uselessly vague.
Richard Smith44ecdbd2013-01-31 05:19:49 +00009971 case Sema::TDK_MiscellaneousDeductionFailure:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009972 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
Richard Smith5179eb72016-06-28 19:03:57 +00009973 MaybeEmitInheritedConstructorNote(S, Found);
John McCall8b9ed552010-02-01 18:53:26 +00009974 return;
Artem Belevich13e9b4d2016-12-07 19:27:16 +00009975 case Sema::TDK_CUDATargetMismatch:
9976 S.Diag(Templated->getLocation(),
9977 diag::note_cuda_ovl_candidate_target_mismatch);
9978 return;
John McCall8b9ed552010-02-01 18:53:26 +00009979 }
9980}
9981
Larisse Voufo98b20f12013-07-19 23:00:19 +00009982/// Diagnose a failed template-argument deduction, for function calls.
Richard Smith17c00b42014-11-12 01:24:00 +00009983static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009984 unsigned NumArgs,
9985 bool TakingCandidateAddress) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009986 unsigned TDK = Cand->DeductionFailure.Result;
9987 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
9988 if (CheckArityMismatch(S, Cand, NumArgs))
9989 return;
9990 }
Richard Smithc2bebe92016-05-11 20:37:46 +00009991 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009992 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
Larisse Voufo98b20f12013-07-19 23:00:19 +00009993}
9994
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009995/// CUDA: diagnose an invalid call across targets.
Richard Smith17c00b42014-11-12 01:24:00 +00009996static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009997 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
9998 FunctionDecl *Callee = Cand->Function;
9999
10000 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
10001 CalleeTarget = S.IdentifyCUDATarget(Callee);
10002
10003 std::string FnDesc;
Richard Smithc2bebe92016-05-11 20:37:46 +000010004 OverloadCandidateKind FnKind =
10005 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc);
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010006
10007 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
Eli Bendersky9a220fc2014-09-29 20:38:29 +000010008 << (unsigned)FnKind << CalleeTarget << CallerTarget;
10009
10010 // This could be an implicit constructor for which we could not infer the
10011 // target due to a collsion. Diagnose that case.
10012 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
10013 if (Meth != nullptr && Meth->isImplicit()) {
10014 CXXRecordDecl *ParentClass = Meth->getParent();
10015 Sema::CXXSpecialMember CSM;
10016
10017 switch (FnKind) {
10018 default:
10019 return;
10020 case oc_implicit_default_constructor:
10021 CSM = Sema::CXXDefaultConstructor;
10022 break;
10023 case oc_implicit_copy_constructor:
10024 CSM = Sema::CXXCopyConstructor;
10025 break;
10026 case oc_implicit_move_constructor:
10027 CSM = Sema::CXXMoveConstructor;
10028 break;
10029 case oc_implicit_copy_assignment:
10030 CSM = Sema::CXXCopyAssignment;
10031 break;
10032 case oc_implicit_move_assignment:
10033 CSM = Sema::CXXMoveAssignment;
10034 break;
10035 };
10036
10037 bool ConstRHS = false;
10038 if (Meth->getNumParams()) {
10039 if (const ReferenceType *RT =
10040 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
10041 ConstRHS = RT->getPointeeType().isConstQualified();
10042 }
10043 }
10044
10045 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
10046 /* ConstRHS */ ConstRHS,
10047 /* Diagnose */ true);
10048 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010049}
10050
Richard Smith17c00b42014-11-12 01:24:00 +000010051static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010052 FunctionDecl *Callee = Cand->Function;
10053 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
10054
10055 S.Diag(Callee->getLocation(),
George Burgess IV177399e2017-01-09 04:12:14 +000010056 diag::note_ovl_candidate_disabled_by_function_cond_attr)
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010057 << Attr->getCond()->getSourceRange() << Attr->getMessage();
10058}
10059
Yaxun Liu5b746652016-12-18 05:18:55 +000010060static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) {
10061 FunctionDecl *Callee = Cand->Function;
10062
10063 S.Diag(Callee->getLocation(),
10064 diag::note_ovl_candidate_disabled_by_extension);
10065}
10066
John McCall8b9ed552010-02-01 18:53:26 +000010067/// Generates a 'note' diagnostic for an overload candidate. We've
10068/// already generated a primary error at the call site.
10069///
10070/// It really does need to be a single diagnostic with its caret
10071/// pointed at the candidate declaration. Yes, this creates some
10072/// major challenges of technical writing. Yes, this makes pointing
10073/// out problems with specific arguments quite awkward. It's still
10074/// better than generating twenty screens of text for every failed
10075/// overload.
10076///
10077/// It would be great to be able to express per-candidate problems
10078/// more richly for those diagnostic clients that cared, but we'd
10079/// still have to be just as careful with the default diagnostics.
Richard Smith17c00b42014-11-12 01:24:00 +000010080static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010081 unsigned NumArgs,
10082 bool TakingCandidateAddress) {
John McCall53262c92010-01-12 02:15:36 +000010083 FunctionDecl *Fn = Cand->Function;
10084
John McCall12f97bc2010-01-08 04:41:39 +000010085 // Note deleted candidates, but only if they're viable.
George Burgess IV177399e2017-01-09 04:12:14 +000010086 if (Cand->Viable) {
10087 if (Fn->isDeleted() || S.isFunctionConsideredUnavailable(Fn)) {
10088 std::string FnDesc;
10089 OverloadCandidateKind FnKind =
Richard Smithc2bebe92016-05-11 20:37:46 +000010090 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +000010091
George Burgess IV177399e2017-01-09 04:12:14 +000010092 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
10093 << FnKind << FnDesc
10094 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
10095 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10096 return;
10097 }
John McCall12f97bc2010-01-08 04:41:39 +000010098
George Burgess IV177399e2017-01-09 04:12:14 +000010099 // We don't really have anything else to say about viable candidates.
Richard Smithc2bebe92016-05-11 20:37:46 +000010100 S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +000010101 return;
10102 }
John McCall0d1da222010-01-12 00:44:57 +000010103
John McCall6a61b522010-01-13 09:16:55 +000010104 switch (Cand->FailureKind) {
10105 case ovl_fail_too_many_arguments:
10106 case ovl_fail_too_few_arguments:
10107 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +000010108
John McCall6a61b522010-01-13 09:16:55 +000010109 case ovl_fail_bad_deduction:
Richard Smithc2bebe92016-05-11 20:37:46 +000010110 return DiagnoseBadDeduction(S, Cand, NumArgs,
10111 TakingCandidateAddress);
John McCall8b9ed552010-02-01 18:53:26 +000010112
John McCall578a1f82014-12-14 01:46:53 +000010113 case ovl_fail_illegal_constructor: {
10114 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
10115 << (Fn->getPrimaryTemplate() ? 1 : 0);
Richard Smith5179eb72016-06-28 19:03:57 +000010116 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall578a1f82014-12-14 01:46:53 +000010117 return;
10118 }
10119
John McCallfe796dd2010-01-23 05:17:32 +000010120 case ovl_fail_trivial_conversion:
10121 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +000010122 case ovl_fail_final_conversion_not_exact:
Richard Smithc2bebe92016-05-11 20:37:46 +000010123 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +000010124
John McCall65eb8792010-02-25 01:37:24 +000010125 case ovl_fail_bad_conversion: {
10126 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Richard Smith6eedfe72017-01-09 08:01:21 +000010127 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +000010128 if (Cand->Conversions[I].isBad())
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010129 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010130
John McCall6a61b522010-01-13 09:16:55 +000010131 // FIXME: this currently happens when we're called from SemaInit
10132 // when user-conversion overload fails. Figure out how to handle
10133 // those conditions and diagnose them well.
Richard Smithc2bebe92016-05-11 20:37:46 +000010134 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +000010135 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010136
10137 case ovl_fail_bad_target:
10138 return DiagnoseBadTarget(S, Cand);
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010139
10140 case ovl_fail_enable_if:
10141 return DiagnoseFailedEnableIfAttr(S, Cand);
George Burgess IV7204ed92016-01-07 02:26:57 +000010142
Yaxun Liu5b746652016-12-18 05:18:55 +000010143 case ovl_fail_ext_disabled:
10144 return DiagnoseOpenCLExtensionDisabled(S, Cand);
10145
Richard Smithf9c59b72017-01-08 21:45:44 +000010146 case ovl_fail_inhctor_slice:
Richard Smith836a3b42017-01-13 20:46:54 +000010147 // It's generally not interesting to note copy/move constructors here.
10148 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
10149 return;
Richard Smithf9c59b72017-01-08 21:45:44 +000010150 S.Diag(Fn->getLocation(),
Richard Smith836a3b42017-01-13 20:46:54 +000010151 diag::note_ovl_candidate_inherited_constructor_slice)
10152 << (Fn->getPrimaryTemplate() ? 1 : 0)
10153 << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
Richard Smithf9c59b72017-01-08 21:45:44 +000010154 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10155 return;
10156
George Burgess IV7204ed92016-01-07 02:26:57 +000010157 case ovl_fail_addr_not_available: {
10158 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
10159 (void)Available;
10160 assert(!Available);
10161 break;
10162 }
John McCall65eb8792010-02-25 01:37:24 +000010163 }
John McCalld3224162010-01-08 00:58:21 +000010164}
10165
Richard Smith17c00b42014-11-12 01:24:00 +000010166static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
John McCalld3224162010-01-08 00:58:21 +000010167 // Desugar the type of the surrogate down to a function type,
10168 // retaining as many typedefs as possible while still showing
10169 // the function type (and, therefore, its parameter types).
10170 QualType FnType = Cand->Surrogate->getConversionType();
10171 bool isLValueReference = false;
10172 bool isRValueReference = false;
10173 bool isPointer = false;
10174 if (const LValueReferenceType *FnTypeRef =
10175 FnType->getAs<LValueReferenceType>()) {
10176 FnType = FnTypeRef->getPointeeType();
10177 isLValueReference = true;
10178 } else if (const RValueReferenceType *FnTypeRef =
10179 FnType->getAs<RValueReferenceType>()) {
10180 FnType = FnTypeRef->getPointeeType();
10181 isRValueReference = true;
10182 }
10183 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
10184 FnType = FnTypePtr->getPointeeType();
10185 isPointer = true;
10186 }
10187 // Desugar down to a function type.
10188 FnType = QualType(FnType->getAs<FunctionType>(), 0);
10189 // Reconstruct the pointer/reference as appropriate.
10190 if (isPointer) FnType = S.Context.getPointerType(FnType);
10191 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
10192 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
10193
10194 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
10195 << FnType;
10196}
10197
Richard Smith17c00b42014-11-12 01:24:00 +000010198static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
10199 SourceLocation OpLoc,
10200 OverloadCandidate *Cand) {
Richard Smith6eedfe72017-01-09 08:01:21 +000010201 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
John McCalld3224162010-01-08 00:58:21 +000010202 std::string TypeStr("operator");
10203 TypeStr += Opc;
10204 TypeStr += "(";
10205 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Richard Smith6eedfe72017-01-09 08:01:21 +000010206 if (Cand->Conversions.size() == 1) {
John McCalld3224162010-01-08 00:58:21 +000010207 TypeStr += ")";
10208 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
10209 } else {
10210 TypeStr += ", ";
10211 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
10212 TypeStr += ")";
10213 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
10214 }
10215}
10216
Richard Smith17c00b42014-11-12 01:24:00 +000010217static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
10218 OverloadCandidate *Cand) {
Richard Smith6eedfe72017-01-09 08:01:21 +000010219 for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
John McCall0d1da222010-01-12 00:44:57 +000010220 if (ICS.isBad()) break; // all meaningless after first invalid
10221 if (!ICS.isAmbiguous()) continue;
10222
Richard Smithc2bebe92016-05-11 20:37:46 +000010223 ICS.DiagnoseAmbiguousConversion(
10224 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +000010225 }
10226}
10227
Larisse Voufo98b20f12013-07-19 23:00:19 +000010228static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
John McCall3712d9e2010-01-15 23:32:50 +000010229 if (Cand->Function)
10230 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +000010231 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +000010232 return Cand->Surrogate->getLocation();
10233 return SourceLocation();
10234}
10235
Larisse Voufo98b20f12013-07-19 23:00:19 +000010236static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
Chandler Carruth73fddfe2011-09-10 00:51:24 +000010237 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010238 case Sema::TDK_Success:
Richard Smith6eedfe72017-01-09 08:01:21 +000010239 case Sema::TDK_NonDependentConversionFailure:
10240 llvm_unreachable("non-deduction failure while diagnosing bad deduction");
Benjamin Kramer8a8051f2011-09-10 21:52:04 +000010241
Douglas Gregorc5c01a62012-09-13 21:01:57 +000010242 case Sema::TDK_Invalid:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010243 case Sema::TDK_Incomplete:
10244 return 1;
10245
10246 case Sema::TDK_Underqualified:
10247 case Sema::TDK_Inconsistent:
10248 return 2;
10249
10250 case Sema::TDK_SubstitutionFailure:
Richard Smith9b534542015-12-31 02:02:54 +000010251 case Sema::TDK_DeducedMismatch:
Richard Smithc92d2062017-01-05 23:02:44 +000010252 case Sema::TDK_DeducedMismatchNested:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010253 case Sema::TDK_NonDeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +000010254 case Sema::TDK_MiscellaneousDeductionFailure:
Artem Belevich13e9b4d2016-12-07 19:27:16 +000010255 case Sema::TDK_CUDATargetMismatch:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010256 return 3;
10257
10258 case Sema::TDK_InstantiationDepth:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010259 return 4;
10260
10261 case Sema::TDK_InvalidExplicitArguments:
10262 return 5;
10263
10264 case Sema::TDK_TooManyArguments:
10265 case Sema::TDK_TooFewArguments:
10266 return 6;
10267 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +000010268 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010269}
10270
Richard Smith17c00b42014-11-12 01:24:00 +000010271namespace {
John McCallad2587a2010-01-12 00:48:53 +000010272struct CompareOverloadCandidatesForDisplay {
10273 Sema &S;
Richard Smith0f59cb32015-12-18 21:45:41 +000010274 SourceLocation Loc;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +000010275 size_t NumArgs;
10276
Richard Smith0f59cb32015-12-18 21:45:41 +000010277 CompareOverloadCandidatesForDisplay(Sema &S, SourceLocation Loc, size_t nArgs)
Kaelyn Takatab96b3be2014-05-01 21:15:24 +000010278 : S(S), NumArgs(nArgs) {}
John McCall12f97bc2010-01-08 04:41:39 +000010279
10280 bool operator()(const OverloadCandidate *L,
10281 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +000010282 // Fast-path this check.
10283 if (L == R) return false;
10284
John McCall12f97bc2010-01-08 04:41:39 +000010285 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +000010286 if (L->Viable) {
10287 if (!R->Viable) return true;
10288
10289 // TODO: introduce a tri-valued comparison for overload
10290 // candidates. Would be more worthwhile if we had a sort
10291 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +000010292 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
10293 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +000010294 } else if (R->Viable)
10295 return false;
John McCall12f97bc2010-01-08 04:41:39 +000010296
John McCall3712d9e2010-01-15 23:32:50 +000010297 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +000010298
John McCall3712d9e2010-01-15 23:32:50 +000010299 // Criteria by which we can sort non-viable candidates:
10300 if (!L->Viable) {
10301 // 1. Arity mismatches come after other candidates.
10302 if (L->FailureKind == ovl_fail_too_many_arguments ||
Kaelyn Takatab96b3be2014-05-01 21:15:24 +000010303 L->FailureKind == ovl_fail_too_few_arguments) {
10304 if (R->FailureKind == ovl_fail_too_many_arguments ||
10305 R->FailureKind == ovl_fail_too_few_arguments) {
Kaelyn Takata50c4ffc2014-05-07 00:43:38 +000010306 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
10307 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
10308 if (LDist == RDist) {
10309 if (L->FailureKind == R->FailureKind)
10310 // Sort non-surrogates before surrogates.
10311 return !L->IsSurrogate && R->IsSurrogate;
10312 // Sort candidates requiring fewer parameters than there were
10313 // arguments given after candidates requiring more parameters
10314 // than there were arguments given.
10315 return L->FailureKind == ovl_fail_too_many_arguments;
10316 }
Kaelyn Takatab96b3be2014-05-01 21:15:24 +000010317 return LDist < RDist;
10318 }
John McCall3712d9e2010-01-15 23:32:50 +000010319 return false;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +000010320 }
John McCall3712d9e2010-01-15 23:32:50 +000010321 if (R->FailureKind == ovl_fail_too_many_arguments ||
10322 R->FailureKind == ovl_fail_too_few_arguments)
10323 return true;
John McCall12f97bc2010-01-08 04:41:39 +000010324
John McCallfe796dd2010-01-23 05:17:32 +000010325 // 2. Bad conversions come first and are ordered by the number
10326 // of bad conversions and quality of good conversions.
10327 if (L->FailureKind == ovl_fail_bad_conversion) {
10328 if (R->FailureKind != ovl_fail_bad_conversion)
10329 return true;
10330
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010331 // The conversion that can be fixed with a smaller number of changes,
10332 // comes first.
10333 unsigned numLFixes = L->Fix.NumConversionsFixed;
10334 unsigned numRFixes = R->Fix.NumConversionsFixed;
10335 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
10336 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +000010337 if (numLFixes != numRFixes) {
David Blaikie7a3cbb22015-03-09 02:02:07 +000010338 return numLFixes < numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +000010339 }
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010340
John McCallfe796dd2010-01-23 05:17:32 +000010341 // If there's any ordering between the defined conversions...
10342 // FIXME: this might not be transitive.
Richard Smith6eedfe72017-01-09 08:01:21 +000010343 assert(L->Conversions.size() == R->Conversions.size());
John McCallfe796dd2010-01-23 05:17:32 +000010344
10345 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +000010346 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Richard Smith6eedfe72017-01-09 08:01:21 +000010347 for (unsigned E = L->Conversions.size(); I != E; ++I) {
Richard Smith0f59cb32015-12-18 21:45:41 +000010348 switch (CompareImplicitConversionSequences(S, Loc,
John McCall5c32be02010-08-24 20:38:10 +000010349 L->Conversions[I],
10350 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +000010351 case ImplicitConversionSequence::Better:
10352 leftBetter++;
10353 break;
10354
10355 case ImplicitConversionSequence::Worse:
10356 leftBetter--;
10357 break;
10358
10359 case ImplicitConversionSequence::Indistinguishable:
10360 break;
10361 }
10362 }
10363 if (leftBetter > 0) return true;
10364 if (leftBetter < 0) return false;
10365
10366 } else if (R->FailureKind == ovl_fail_bad_conversion)
10367 return false;
10368
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010369 if (L->FailureKind == ovl_fail_bad_deduction) {
10370 if (R->FailureKind != ovl_fail_bad_deduction)
10371 return true;
10372
10373 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10374 return RankDeductionFailure(L->DeductionFailure)
Eli Friedman1e7a0c62011-10-14 23:10:30 +000010375 < RankDeductionFailure(R->DeductionFailure);
Eli Friedmane2c600c2011-10-14 21:52:24 +000010376 } else if (R->FailureKind == ovl_fail_bad_deduction)
10377 return false;
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010378
John McCall3712d9e2010-01-15 23:32:50 +000010379 // TODO: others?
10380 }
10381
10382 // Sort everything else by location.
10383 SourceLocation LLoc = GetLocationForCandidate(L);
10384 SourceLocation RLoc = GetLocationForCandidate(R);
10385
10386 // Put candidates without locations (e.g. builtins) at the end.
10387 if (LLoc.isInvalid()) return false;
10388 if (RLoc.isInvalid()) return true;
10389
10390 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +000010391 }
10392};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010393}
John McCall12f97bc2010-01-08 04:41:39 +000010394
John McCallfe796dd2010-01-23 05:17:32 +000010395/// CompleteNonViableCandidate - Normally, overload resolution only
Richard Smith6eedfe72017-01-09 08:01:21 +000010396/// computes up to the first bad conversion. Produces the FixIt set if
10397/// possible.
Richard Smith17c00b42014-11-12 01:24:00 +000010398static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
10399 ArrayRef<Expr *> Args) {
John McCallfe796dd2010-01-23 05:17:32 +000010400 assert(!Cand->Viable);
10401
10402 // Don't do anything on failures other than bad conversion.
10403 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
10404
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010405 // We only want the FixIts if all the arguments can be corrected.
10406 bool Unfixable = false;
Anna Zaks1b068122011-07-28 19:46:48 +000010407 // Use a implicit copy initialization to check conversion fixes.
10408 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010409
Richard Smith6eedfe72017-01-09 08:01:21 +000010410 // Attempt to fix the bad conversion.
10411 unsigned ConvCount = Cand->Conversions.size();
10412 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
10413 ++ConvIdx) {
John McCallfe796dd2010-01-23 05:17:32 +000010414 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
Richard Smith6eedfe72017-01-09 08:01:21 +000010415 if (Cand->Conversions[ConvIdx].isInitialized() &&
10416 Cand->Conversions[ConvIdx].isBad()) {
10417 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
John McCallfe796dd2010-01-23 05:17:32 +000010418 break;
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010419 }
John McCallfe796dd2010-01-23 05:17:32 +000010420 }
10421
Douglas Gregoradc7a702010-04-16 17:45:54 +000010422 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +000010423 // operation somehow.
10424 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +000010425
Richard Smith14ead302017-01-10 20:19:21 +000010426 unsigned ConvIdx = 0;
10427 ArrayRef<QualType> ParamTypes;
John McCallfe796dd2010-01-23 05:17:32 +000010428
10429 if (Cand->IsSurrogate) {
10430 QualType ConvType
10431 = Cand->Surrogate->getConversionType().getNonReferenceType();
10432 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10433 ConvType = ConvPtrType->getPointeeType();
Richard Smith14ead302017-01-10 20:19:21 +000010434 ParamTypes = ConvType->getAs<FunctionProtoType>()->getParamTypes();
10435 // Conversion 0 is 'this', which doesn't have a corresponding argument.
10436 ConvIdx = 1;
John McCallfe796dd2010-01-23 05:17:32 +000010437 } else if (Cand->Function) {
Richard Smith14ead302017-01-10 20:19:21 +000010438 ParamTypes =
10439 Cand->Function->getType()->getAs<FunctionProtoType>()->getParamTypes();
John McCallfe796dd2010-01-23 05:17:32 +000010440 if (isa<CXXMethodDecl>(Cand->Function) &&
Richard Smith14ead302017-01-10 20:19:21 +000010441 !isa<CXXConstructorDecl>(Cand->Function)) {
10442 // Conversion 0 is 'this', which doesn't have a corresponding argument.
10443 ConvIdx = 1;
Richard Smith6eedfe72017-01-09 08:01:21 +000010444 }
Richard Smith14ead302017-01-10 20:19:21 +000010445 } else {
10446 // Builtin operator.
10447 assert(ConvCount <= 3);
10448 ParamTypes = Cand->BuiltinTypes.ParamTypes;
John McCallfe796dd2010-01-23 05:17:32 +000010449 }
10450
10451 // Fill in the rest of the conversions.
Richard Smith14ead302017-01-10 20:19:21 +000010452 for (unsigned ArgIdx = 0; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Richard Smith6eedfe72017-01-09 08:01:21 +000010453 if (Cand->Conversions[ConvIdx].isInitialized()) {
Richard Smith14ead302017-01-10 20:19:21 +000010454 // We've already checked this conversion.
10455 } else if (ArgIdx < ParamTypes.size()) {
10456 if (ParamTypes[ArgIdx]->isDependentType())
Richard Smith6eedfe72017-01-09 08:01:21 +000010457 Cand->Conversions[ConvIdx].setAsIdentityConversion(
10458 Args[ArgIdx]->getType());
10459 else {
10460 Cand->Conversions[ConvIdx] =
Richard Smith14ead302017-01-10 20:19:21 +000010461 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ArgIdx],
Richard Smith6eedfe72017-01-09 08:01:21 +000010462 SuppressUserConversions,
10463 /*InOverloadResolution=*/true,
10464 /*AllowObjCWritebackConversion=*/
10465 S.getLangOpts().ObjCAutoRefCount);
10466 // Store the FixIt in the candidate if it exists.
10467 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
10468 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10469 }
10470 } else
John McCallfe796dd2010-01-23 05:17:32 +000010471 Cand->Conversions[ConvIdx].setEllipsis();
10472 }
10473}
10474
Douglas Gregor5251f1b2008-10-21 16:13:35 +000010475/// PrintOverloadCandidates - When overload resolution fails, prints
10476/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +000010477/// set.
Richard Smithb2f0f052016-10-10 18:54:32 +000010478void OverloadCandidateSet::NoteCandidates(
10479 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
10480 StringRef Opc, SourceLocation OpLoc,
10481 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
John McCall12f97bc2010-01-08 04:41:39 +000010482 // Sort the candidates by viability and position. Sorting directly would
10483 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010484 SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +000010485 if (OCD == OCD_AllCandidates) Cands.reserve(size());
10486 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
Richard Smithb2f0f052016-10-10 18:54:32 +000010487 if (!Filter(*Cand))
10488 continue;
John McCallfe796dd2010-01-23 05:17:32 +000010489 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +000010490 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +000010491 else if (OCD == OCD_AllCandidates) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010492 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010493 if (Cand->Function || Cand->IsSurrogate)
10494 Cands.push_back(Cand);
10495 // Otherwise, this a non-viable builtin candidate. We do not, in general,
10496 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +000010497 }
10498 }
10499
John McCallad2587a2010-01-12 00:48:53 +000010500 std::sort(Cands.begin(), Cands.end(),
Richard Smith0f59cb32015-12-18 21:45:41 +000010501 CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size()));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010502
John McCall0d1da222010-01-12 00:44:57 +000010503 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +000010504
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010505 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Douglas Gregor79591782012-10-23 23:11:23 +000010506 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010507 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +000010508 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10509 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +000010510
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010511 // Set an arbitrary limit on the number of candidate functions we'll spam
10512 // the user with. FIXME: This limit should depend on details of the
10513 // candidate list.
Douglas Gregor79591782012-10-23 23:11:23 +000010514 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010515 break;
10516 }
10517 ++CandsShown;
10518
John McCalld3224162010-01-08 00:58:21 +000010519 if (Cand->Function)
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010520 NoteFunctionCandidate(S, Cand, Args.size(),
10521 /*TakingCandidateAddress=*/false);
John McCalld3224162010-01-08 00:58:21 +000010522 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +000010523 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010524 else {
10525 assert(Cand->Viable &&
10526 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +000010527 // Generally we only see ambiguities including viable builtin
10528 // operators if overload resolution got screwed up by an
10529 // ambiguous user-defined conversion.
10530 //
10531 // FIXME: It's quite possible for different conversions to see
10532 // different ambiguities, though.
10533 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +000010534 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +000010535 ReportedAmbiguousConversions = true;
10536 }
John McCalld3224162010-01-08 00:58:21 +000010537
John McCall0d1da222010-01-12 00:44:57 +000010538 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +000010539 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +000010540 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +000010541 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010542
10543 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +000010544 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +000010545}
10546
Larisse Voufo98b20f12013-07-19 23:00:19 +000010547static SourceLocation
10548GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
10549 return Cand->Specialization ? Cand->Specialization->getLocation()
10550 : SourceLocation();
10551}
10552
Richard Smith17c00b42014-11-12 01:24:00 +000010553namespace {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010554struct CompareTemplateSpecCandidatesForDisplay {
10555 Sema &S;
10556 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
10557
10558 bool operator()(const TemplateSpecCandidate *L,
10559 const TemplateSpecCandidate *R) {
10560 // Fast-path this check.
10561 if (L == R)
10562 return false;
10563
10564 // Assuming that both candidates are not matches...
10565
10566 // Sort by the ranking of deduction failures.
10567 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10568 return RankDeductionFailure(L->DeductionFailure) <
10569 RankDeductionFailure(R->DeductionFailure);
10570
10571 // Sort everything else by location.
10572 SourceLocation LLoc = GetLocationForCandidate(L);
10573 SourceLocation RLoc = GetLocationForCandidate(R);
10574
10575 // Put candidates without locations (e.g. builtins) at the end.
10576 if (LLoc.isInvalid())
10577 return false;
10578 if (RLoc.isInvalid())
10579 return true;
10580
10581 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10582 }
10583};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010584}
Larisse Voufo98b20f12013-07-19 23:00:19 +000010585
10586/// Diagnose a template argument deduction failure.
10587/// We are treating these failures as overload failures due to bad
10588/// deductions.
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010589void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
10590 bool ForTakingAddress) {
Richard Smithc2bebe92016-05-11 20:37:46 +000010591 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010592 DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010593}
10594
10595void TemplateSpecCandidateSet::destroyCandidates() {
10596 for (iterator i = begin(), e = end(); i != e; ++i) {
10597 i->DeductionFailure.Destroy();
10598 }
10599}
10600
10601void TemplateSpecCandidateSet::clear() {
10602 destroyCandidates();
10603 Candidates.clear();
10604}
10605
10606/// NoteCandidates - When no template specialization match is found, prints
10607/// diagnostic messages containing the non-matching specializations that form
10608/// the candidate set.
10609/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
10610/// OCD == OCD_AllCandidates and Cand->Viable == false.
10611void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
10612 // Sort the candidates by position (assuming no candidate is a match).
10613 // Sorting directly would be prohibitive, so we make a set of pointers
10614 // and sort those.
10615 SmallVector<TemplateSpecCandidate *, 32> Cands;
10616 Cands.reserve(size());
10617 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10618 if (Cand->Specialization)
10619 Cands.push_back(Cand);
Alp Tokerd4733632013-12-05 04:47:09 +000010620 // Otherwise, this is a non-matching builtin candidate. We do not,
Larisse Voufo98b20f12013-07-19 23:00:19 +000010621 // in general, want to list every possible builtin candidate.
10622 }
10623
10624 std::sort(Cands.begin(), Cands.end(),
10625 CompareTemplateSpecCandidatesForDisplay(S));
10626
10627 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
10628 // for generalization purposes (?).
10629 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10630
10631 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
10632 unsigned CandsShown = 0;
10633 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10634 TemplateSpecCandidate *Cand = *I;
10635
10636 // Set an arbitrary limit on the number of candidates we'll spam
10637 // the user with. FIXME: This limit should depend on details of the
10638 // candidate list.
10639 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10640 break;
10641 ++CandsShown;
10642
10643 assert(Cand->Specialization &&
10644 "Non-matching built-in candidates are not added to Cands.");
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010645 Cand->NoteDeductionFailure(S, ForTakingAddress);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010646 }
10647
10648 if (I != E)
10649 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
10650}
10651
Douglas Gregorb491ed32011-02-19 21:32:49 +000010652// [PossiblyAFunctionType] --> [Return]
10653// NonFunctionType --> NonFunctionType
10654// R (A) --> R(A)
10655// R (*)(A) --> R (A)
10656// R (&)(A) --> R (A)
10657// R (S::*)(A) --> R (A)
10658QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
10659 QualType Ret = PossiblyAFunctionType;
10660 if (const PointerType *ToTypePtr =
10661 PossiblyAFunctionType->getAs<PointerType>())
10662 Ret = ToTypePtr->getPointeeType();
10663 else if (const ReferenceType *ToTypeRef =
10664 PossiblyAFunctionType->getAs<ReferenceType>())
10665 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +000010666 else if (const MemberPointerType *MemTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +000010667 PossiblyAFunctionType->getAs<MemberPointerType>())
10668 Ret = MemTypePtr->getPointeeType();
10669 Ret =
10670 Context.getCanonicalType(Ret).getUnqualifiedType();
10671 return Ret;
10672}
Douglas Gregorcd695e52008-11-10 20:40:00 +000010673
Richard Smith9095e5b2016-11-01 01:31:23 +000010674static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
10675 bool Complain = true) {
10676 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
10677 S.DeduceReturnType(FD, Loc, Complain))
10678 return true;
10679
10680 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
10681 if (S.getLangOpts().CPlusPlus1z &&
10682 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
10683 !S.ResolveExceptionSpec(Loc, FPT))
10684 return true;
10685
10686 return false;
10687}
10688
Richard Smith17c00b42014-11-12 01:24:00 +000010689namespace {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010690// A helper class to help with address of function resolution
10691// - allows us to avoid passing around all those ugly parameters
Richard Smith17c00b42014-11-12 01:24:00 +000010692class AddressOfFunctionResolver {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010693 Sema& S;
10694 Expr* SourceExpr;
10695 const QualType& TargetType;
10696 QualType TargetFunctionType; // Extracted function type from target type
10697
10698 bool Complain;
10699 //DeclAccessPair& ResultFunctionAccessPair;
10700 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010701
Douglas Gregorb491ed32011-02-19 21:32:49 +000010702 bool TargetTypeIsNonStaticMemberFunction;
10703 bool FoundNonTemplateFunction;
David Majnemera4f7c7a2013-08-01 06:13:59 +000010704 bool StaticMemberFunctionFromBoundPointer;
George Burgess IV5f2ef452015-10-12 18:40:58 +000010705 bool HasComplained;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010706
Douglas Gregorb491ed32011-02-19 21:32:49 +000010707 OverloadExpr::FindResult OvlExprInfo;
10708 OverloadExpr *OvlExpr;
10709 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010710 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Larisse Voufo98b20f12013-07-19 23:00:19 +000010711 TemplateSpecCandidateSet FailedCandidates;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010712
Douglas Gregorb491ed32011-02-19 21:32:49 +000010713public:
Larisse Voufo98b20f12013-07-19 23:00:19 +000010714 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
10715 const QualType &TargetType, bool Complain)
10716 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
10717 Complain(Complain), Context(S.getASTContext()),
10718 TargetTypeIsNonStaticMemberFunction(
10719 !!TargetType->getAs<MemberPointerType>()),
10720 FoundNonTemplateFunction(false),
David Majnemera4f7c7a2013-08-01 06:13:59 +000010721 StaticMemberFunctionFromBoundPointer(false),
George Burgess IV5f2ef452015-10-12 18:40:58 +000010722 HasComplained(false),
Larisse Voufo98b20f12013-07-19 23:00:19 +000010723 OvlExprInfo(OverloadExpr::find(SourceExpr)),
10724 OvlExpr(OvlExprInfo.Expression),
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010725 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010726 ExtractUnqualifiedFunctionTypeFromTargetType();
Chandler Carruthffce2452011-03-29 08:08:18 +000010727
David Majnemera4f7c7a2013-08-01 06:13:59 +000010728 if (TargetFunctionType->isFunctionType()) {
10729 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
10730 if (!UME->isImplicitAccess() &&
10731 !S.ResolveSingleFunctionTemplateSpecialization(UME))
10732 StaticMemberFunctionFromBoundPointer = true;
10733 } else if (OvlExpr->hasExplicitTemplateArgs()) {
10734 DeclAccessPair dap;
10735 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
10736 OvlExpr, false, &dap)) {
10737 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
10738 if (!Method->isStatic()) {
10739 // If the target type is a non-function type and the function found
10740 // is a non-static member function, pretend as if that was the
10741 // target, it's the only possible type to end up with.
10742 TargetTypeIsNonStaticMemberFunction = true;
Chandler Carruthffce2452011-03-29 08:08:18 +000010743
David Majnemera4f7c7a2013-08-01 06:13:59 +000010744 // And skip adding the function if its not in the proper form.
10745 // We'll diagnose this due to an empty set of functions.
10746 if (!OvlExprInfo.HasFormOfMemberPointer)
10747 return;
Chandler Carruthffce2452011-03-29 08:08:18 +000010748 }
10749
David Majnemera4f7c7a2013-08-01 06:13:59 +000010750 Matches.push_back(std::make_pair(dap, Fn));
Douglas Gregor9b146582009-07-08 20:55:45 +000010751 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010752 return;
Douglas Gregor9b146582009-07-08 20:55:45 +000010753 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010754
10755 if (OvlExpr->hasExplicitTemplateArgs())
James Y Knight04ec5bf2015-12-24 02:59:37 +000010756 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +000010757
Douglas Gregorb491ed32011-02-19 21:32:49 +000010758 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
10759 // C++ [over.over]p4:
10760 // If more than one function is selected, [...]
George Burgess IV2a6150d2015-10-16 01:17:38 +000010761 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010762 if (FoundNonTemplateFunction)
10763 EliminateAllTemplateMatches();
10764 else
10765 EliminateAllExceptMostSpecializedTemplate();
10766 }
10767 }
Artem Belevich94a55e82015-09-22 17:22:59 +000010768
Justin Lebar25c4a812016-03-29 16:24:16 +000010769 if (S.getLangOpts().CUDA && Matches.size() > 1)
Artem Belevich94a55e82015-09-22 17:22:59 +000010770 EliminateSuboptimalCudaMatches();
Douglas Gregorb491ed32011-02-19 21:32:49 +000010771 }
George Burgess IV5f2ef452015-10-12 18:40:58 +000010772
10773 bool hasComplained() const { return HasComplained; }
10774
Douglas Gregorb491ed32011-02-19 21:32:49 +000010775private:
George Burgess IV6da4c202016-03-23 02:33:58 +000010776 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
10777 QualType Discard;
10778 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
Richard Smith3c4f8d22016-10-16 17:54:23 +000010779 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
George Burgess IV2a6150d2015-10-16 01:17:38 +000010780 }
10781
George Burgess IV6da4c202016-03-23 02:33:58 +000010782 /// \return true if A is considered a better overload candidate for the
10783 /// desired type than B.
10784 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
10785 // If A doesn't have exactly the correct type, we don't want to classify it
10786 // as "better" than anything else. This way, the user is required to
10787 // disambiguate for us if there are multiple candidates and no exact match.
10788 return candidateHasExactlyCorrectType(A) &&
10789 (!candidateHasExactlyCorrectType(B) ||
George Burgess IV3dc166912016-05-10 01:59:34 +000010790 compareEnableIfAttrs(S, A, B) == Comparison::Better);
George Burgess IV6da4c202016-03-23 02:33:58 +000010791 }
10792
10793 /// \return true if we were able to eliminate all but one overload candidate,
10794 /// false otherwise.
George Burgess IV2a6150d2015-10-16 01:17:38 +000010795 bool eliminiateSuboptimalOverloadCandidates() {
10796 // Same algorithm as overload resolution -- one pass to pick the "best",
10797 // another pass to be sure that nothing is better than the best.
10798 auto Best = Matches.begin();
10799 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
10800 if (isBetterCandidate(I->second, Best->second))
10801 Best = I;
10802
10803 const FunctionDecl *BestFn = Best->second;
10804 auto IsBestOrInferiorToBest = [this, BestFn](
10805 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
10806 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
10807 };
10808
10809 // Note: We explicitly leave Matches unmodified if there isn't a clear best
10810 // option, so we can potentially give the user a better error
10811 if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest))
10812 return false;
10813 Matches[0] = *Best;
10814 Matches.resize(1);
10815 return true;
10816 }
10817
Douglas Gregorb491ed32011-02-19 21:32:49 +000010818 bool isTargetTypeAFunction() const {
10819 return TargetFunctionType->isFunctionType();
10820 }
10821
10822 // [ToType] [Return]
10823
10824 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
10825 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
10826 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
10827 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
10828 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
10829 }
10830
10831 // return true if any matching specializations were found
10832 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
10833 const DeclAccessPair& CurAccessFunPair) {
10834 if (CXXMethodDecl *Method
10835 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
10836 // Skip non-static function templates when converting to pointer, and
10837 // static when converting to member pointer.
10838 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10839 return false;
10840 }
10841 else if (TargetTypeIsNonStaticMemberFunction)
10842 return false;
10843
10844 // C++ [over.over]p2:
10845 // If the name is a function template, template argument deduction is
10846 // done (14.8.2.2), and if the argument deduction succeeds, the
10847 // resulting template argument list is used to generate a single
10848 // function template specialization, which is added to the set of
10849 // overloaded functions considered.
Craig Topperc3ec1492014-05-26 06:22:03 +000010850 FunctionDecl *Specialization = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +000010851 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregorb491ed32011-02-19 21:32:49 +000010852 if (Sema::TemplateDeductionResult Result
10853 = S.DeduceTemplateArguments(FunctionTemplate,
10854 &OvlExplicitTemplateArgs,
10855 TargetFunctionType, Specialization,
Richard Smithbaa47832016-12-01 02:11:49 +000010856 Info, /*IsAddressOfFunction*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010857 // Make a note of the failed deduction for diagnostics.
10858 FailedCandidates.addCandidate()
Richard Smithc2bebe92016-05-11 20:37:46 +000010859 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
Larisse Voufo98b20f12013-07-19 23:00:19 +000010860 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregorb491ed32011-02-19 21:32:49 +000010861 return false;
10862 }
10863
Douglas Gregor19a41f12013-04-17 08:45:07 +000010864 // Template argument deduction ensures that we have an exact match or
10865 // compatible pointer-to-function arguments that would be adjusted by ICS.
Douglas Gregorb491ed32011-02-19 21:32:49 +000010866 // This function template specicalization works.
Douglas Gregor19a41f12013-04-17 08:45:07 +000010867 assert(S.isSameOrCompatibleFunctionType(
10868 Context.getCanonicalType(Specialization->getType()),
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010869 Context.getCanonicalType(TargetFunctionType)));
George Burgess IV5f21c712015-10-12 19:57:04 +000010870
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010871 if (!S.checkAddressOfFunctionIsAvailable(Specialization))
George Burgess IV5f21c712015-10-12 19:57:04 +000010872 return false;
10873
Douglas Gregorb491ed32011-02-19 21:32:49 +000010874 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
10875 return true;
10876 }
10877
10878 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
10879 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +000010880 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +000010881 // Skip non-static functions when converting to pointer, and static
10882 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +000010883 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10884 return false;
10885 }
10886 else if (TargetTypeIsNonStaticMemberFunction)
10887 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010888
Chandler Carruthc25c6ee2009-12-29 06:17:27 +000010889 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000010890 if (S.getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010891 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
Justin Lebarb0080032016-08-10 01:09:11 +000010892 if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010893 return false;
10894
Richard Smith2a7d4812013-05-04 07:00:32 +000010895 // If any candidate has a placeholder return type, trigger its deduction
10896 // now.
Richard Smith9095e5b2016-11-01 01:31:23 +000010897 if (completeFunctionType(S, FunDecl, SourceExpr->getLocStart(),
10898 Complain)) {
George Burgess IV5f2ef452015-10-12 18:40:58 +000010899 HasComplained |= Complain;
Richard Smith2a7d4812013-05-04 07:00:32 +000010900 return false;
George Burgess IV5f2ef452015-10-12 18:40:58 +000010901 }
Richard Smith2a7d4812013-05-04 07:00:32 +000010902
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010903 if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
George Burgess IV5f21c712015-10-12 19:57:04 +000010904 return false;
10905
George Burgess IV6da4c202016-03-23 02:33:58 +000010906 // If we're in C, we need to support types that aren't exactly identical.
10907 if (!S.getLangOpts().CPlusPlus ||
10908 candidateHasExactlyCorrectType(FunDecl)) {
George Burgess IV5f21c712015-10-12 19:57:04 +000010909 Matches.push_back(std::make_pair(
10910 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +000010911 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010912 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +000010913 }
Mike Stump11289f42009-09-09 15:08:12 +000010914 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010915
10916 return false;
10917 }
10918
10919 bool FindAllFunctionsThatMatchTargetTypeExactly() {
10920 bool Ret = false;
10921
10922 // If the overload expression doesn't have the form of a pointer to
10923 // member, don't try to convert it to a pointer-to-member type.
10924 if (IsInvalidFormOfPointerToMemberFunction())
10925 return false;
10926
10927 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10928 E = OvlExpr->decls_end();
10929 I != E; ++I) {
10930 // Look through any using declarations to find the underlying function.
10931 NamedDecl *Fn = (*I)->getUnderlyingDecl();
10932
10933 // C++ [over.over]p3:
10934 // Non-member functions and static member functions match
10935 // targets of type "pointer-to-function" or "reference-to-function."
10936 // Nonstatic member functions match targets of
10937 // type "pointer-to-member-function."
10938 // Note that according to DR 247, the containing class does not matter.
10939 if (FunctionTemplateDecl *FunctionTemplate
10940 = dyn_cast<FunctionTemplateDecl>(Fn)) {
10941 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
10942 Ret = true;
10943 }
10944 // If we have explicit template arguments supplied, skip non-templates.
10945 else if (!OvlExpr->hasExplicitTemplateArgs() &&
10946 AddMatchingNonTemplateFunction(Fn, I.getPair()))
10947 Ret = true;
10948 }
10949 assert(Ret || Matches.empty());
10950 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010951 }
10952
Douglas Gregorb491ed32011-02-19 21:32:49 +000010953 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +000010954 // [...] and any given function template specialization F1 is
10955 // eliminated if the set contains a second function template
10956 // specialization whose function template is more specialized
10957 // than the function template of F1 according to the partial
10958 // ordering rules of 14.5.5.2.
10959
10960 // The algorithm specified above is quadratic. We instead use a
10961 // two-pass algorithm (similar to the one used to identify the
10962 // best viable function in an overload set) that identifies the
10963 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +000010964
10965 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
10966 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
10967 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010968
Larisse Voufo98b20f12013-07-19 23:00:19 +000010969 // TODO: It looks like FailedCandidates does not serve much purpose
10970 // here, since the no_viable diagnostic has index 0.
10971 UnresolvedSetIterator Result = S.getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +000010972 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +000010973 SourceExpr->getLocStart(), S.PDiag(),
Richard Smith5179eb72016-06-28 19:03:57 +000010974 S.PDiag(diag::err_addr_ovl_ambiguous)
10975 << Matches[0].second->getDeclName(),
10976 S.PDiag(diag::note_ovl_candidate)
10977 << (unsigned)oc_function_template,
Larisse Voufo98b20f12013-07-19 23:00:19 +000010978 Complain, TargetFunctionType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010979
Douglas Gregorb491ed32011-02-19 21:32:49 +000010980 if (Result != MatchesCopy.end()) {
10981 // Make it the first and only element
10982 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
10983 Matches[0].second = cast<FunctionDecl>(*Result);
10984 Matches.resize(1);
George Burgess IV5f2ef452015-10-12 18:40:58 +000010985 } else
10986 HasComplained |= Complain;
John McCall58cc69d2010-01-27 01:50:18 +000010987 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010988
Douglas Gregorb491ed32011-02-19 21:32:49 +000010989 void EliminateAllTemplateMatches() {
10990 // [...] any function template specializations in the set are
10991 // eliminated if the set also contains a non-template function, [...]
10992 for (unsigned I = 0, N = Matches.size(); I != N; ) {
Craig Topperc3ec1492014-05-26 06:22:03 +000010993 if (Matches[I].second->getPrimaryTemplate() == nullptr)
Douglas Gregorb491ed32011-02-19 21:32:49 +000010994 ++I;
10995 else {
10996 Matches[I] = Matches[--N];
Artem Belevich94a55e82015-09-22 17:22:59 +000010997 Matches.resize(N);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010998 }
10999 }
11000 }
11001
Artem Belevich94a55e82015-09-22 17:22:59 +000011002 void EliminateSuboptimalCudaMatches() {
11003 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
11004 }
11005
Douglas Gregorb491ed32011-02-19 21:32:49 +000011006public:
11007 void ComplainNoMatchesFound() const {
11008 assert(Matches.empty());
11009 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
11010 << OvlExpr->getName() << TargetFunctionType
11011 << OvlExpr->getSourceRange();
Richard Smith0d905472013-08-14 00:00:44 +000011012 if (FailedCandidates.empty())
George Burgess IV5f21c712015-10-12 19:57:04 +000011013 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11014 /*TakingAddress=*/true);
Richard Smith0d905472013-08-14 00:00:44 +000011015 else {
11016 // We have some deduction failure messages. Use them to diagnose
11017 // the function templates, and diagnose the non-template candidates
11018 // normally.
11019 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11020 IEnd = OvlExpr->decls_end();
11021 I != IEnd; ++I)
11022 if (FunctionDecl *Fun =
11023 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011024 if (!functionHasPassObjectSizeParams(Fun))
Richard Smithc2bebe92016-05-11 20:37:46 +000011025 S.NoteOverloadCandidate(*I, Fun, TargetFunctionType,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011026 /*TakingAddress=*/true);
Richard Smith0d905472013-08-14 00:00:44 +000011027 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
11028 }
11029 }
11030
Douglas Gregorb491ed32011-02-19 21:32:49 +000011031 bool IsInvalidFormOfPointerToMemberFunction() const {
11032 return TargetTypeIsNonStaticMemberFunction &&
11033 !OvlExprInfo.HasFormOfMemberPointer;
11034 }
David Majnemera4f7c7a2013-08-01 06:13:59 +000011035
Douglas Gregorb491ed32011-02-19 21:32:49 +000011036 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
11037 // TODO: Should we condition this on whether any functions might
11038 // have matched, or is it more appropriate to do that in callers?
11039 // TODO: a fixit wouldn't hurt.
11040 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
11041 << TargetType << OvlExpr->getSourceRange();
11042 }
David Majnemera4f7c7a2013-08-01 06:13:59 +000011043
11044 bool IsStaticMemberFunctionFromBoundPointer() const {
11045 return StaticMemberFunctionFromBoundPointer;
11046 }
11047
11048 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
11049 S.Diag(OvlExpr->getLocStart(),
11050 diag::err_invalid_form_pointer_member_function)
11051 << OvlExpr->getSourceRange();
11052 }
11053
Douglas Gregorb491ed32011-02-19 21:32:49 +000011054 void ComplainOfInvalidConversion() const {
11055 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
11056 << OvlExpr->getName() << TargetType;
11057 }
11058
11059 void ComplainMultipleMatchesFound() const {
11060 assert(Matches.size() > 1);
11061 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
11062 << OvlExpr->getName()
11063 << OvlExpr->getSourceRange();
George Burgess IV5f21c712015-10-12 19:57:04 +000011064 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11065 /*TakingAddress=*/true);
Douglas Gregorb491ed32011-02-19 21:32:49 +000011066 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +000011067
11068 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
11069
Douglas Gregorb491ed32011-02-19 21:32:49 +000011070 int getNumMatches() const { return Matches.size(); }
11071
11072 FunctionDecl* getMatchingFunctionDecl() const {
Craig Topperc3ec1492014-05-26 06:22:03 +000011073 if (Matches.size() != 1) return nullptr;
Douglas Gregorb491ed32011-02-19 21:32:49 +000011074 return Matches[0].second;
11075 }
11076
11077 const DeclAccessPair* getMatchingFunctionAccessPair() const {
Craig Topperc3ec1492014-05-26 06:22:03 +000011078 if (Matches.size() != 1) return nullptr;
Douglas Gregorb491ed32011-02-19 21:32:49 +000011079 return &Matches[0].first;
11080 }
11081};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000011082}
Richard Smith17c00b42014-11-12 01:24:00 +000011083
Douglas Gregorb491ed32011-02-19 21:32:49 +000011084/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
11085/// an overloaded function (C++ [over.over]), where @p From is an
11086/// expression with overloaded function type and @p ToType is the type
11087/// we're trying to resolve to. For example:
11088///
11089/// @code
11090/// int f(double);
11091/// int f(int);
11092///
11093/// int (*pfd)(double) = f; // selects f(double)
11094/// @endcode
11095///
11096/// This routine returns the resulting FunctionDecl if it could be
11097/// resolved, and NULL otherwise. When @p Complain is true, this
11098/// routine will emit diagnostics if there is an error.
11099FunctionDecl *
Abramo Bagnara5001caa2011-11-19 11:44:21 +000011100Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
11101 QualType TargetType,
11102 bool Complain,
11103 DeclAccessPair &FoundResult,
11104 bool *pHadMultipleCandidates) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000011105 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara5001caa2011-11-19 11:44:21 +000011106
11107 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
11108 Complain);
Douglas Gregorb491ed32011-02-19 21:32:49 +000011109 int NumMatches = Resolver.getNumMatches();
Craig Topperc3ec1492014-05-26 06:22:03 +000011110 FunctionDecl *Fn = nullptr;
George Burgess IV5f2ef452015-10-12 18:40:58 +000011111 bool ShouldComplain = Complain && !Resolver.hasComplained();
11112 if (NumMatches == 0 && ShouldComplain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000011113 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
11114 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
11115 else
11116 Resolver.ComplainNoMatchesFound();
11117 }
George Burgess IV5f2ef452015-10-12 18:40:58 +000011118 else if (NumMatches > 1 && ShouldComplain)
Douglas Gregorb491ed32011-02-19 21:32:49 +000011119 Resolver.ComplainMultipleMatchesFound();
11120 else if (NumMatches == 1) {
11121 Fn = Resolver.getMatchingFunctionDecl();
11122 assert(Fn);
Richard Smith9095e5b2016-11-01 01:31:23 +000011123 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
11124 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
Douglas Gregorb491ed32011-02-19 21:32:49 +000011125 FoundResult = *Resolver.getMatchingFunctionAccessPair();
David Majnemera4f7c7a2013-08-01 06:13:59 +000011126 if (Complain) {
11127 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
11128 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
11129 else
11130 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
11131 }
Sebastian Redldf4b80e2009-10-17 21:12:09 +000011132 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +000011133
11134 if (pHadMultipleCandidates)
11135 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregorb491ed32011-02-19 21:32:49 +000011136 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +000011137}
11138
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011139/// \brief Given an expression that refers to an overloaded function, try to
George Burgess IV3cde9bf2016-03-19 21:36:10 +000011140/// resolve that function to a single function that can have its address taken.
11141/// This will modify `Pair` iff it returns non-null.
11142///
11143/// This routine can only realistically succeed if all but one candidates in the
11144/// overload set for SrcExpr cannot have their addresses taken.
11145FunctionDecl *
11146Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
11147 DeclAccessPair &Pair) {
11148 OverloadExpr::FindResult R = OverloadExpr::find(E);
11149 OverloadExpr *Ovl = R.Expression;
11150 FunctionDecl *Result = nullptr;
11151 DeclAccessPair DAP;
11152 // Don't use the AddressOfResolver because we're specifically looking for
11153 // cases where we have one overload candidate that lacks
11154 // enable_if/pass_object_size/...
11155 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
11156 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
11157 if (!FD)
11158 return nullptr;
11159
11160 if (!checkAddressOfFunctionIsAvailable(FD))
11161 continue;
11162
11163 // We have more than one result; quit.
11164 if (Result)
11165 return nullptr;
11166 DAP = I.getPair();
11167 Result = FD;
11168 }
11169
11170 if (Result)
11171 Pair = DAP;
11172 return Result;
11173}
11174
George Burgess IVbeca4a32016-06-08 00:34:22 +000011175/// \brief Given an overloaded function, tries to turn it into a non-overloaded
11176/// function reference using resolveAddressOfOnlyViableOverloadCandidate. This
11177/// will perform access checks, diagnose the use of the resultant decl, and, if
11178/// necessary, perform a function-to-pointer decay.
11179///
11180/// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails.
11181/// Otherwise, returns true. This may emit diagnostics and return true.
11182bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate(
11183 ExprResult &SrcExpr) {
11184 Expr *E = SrcExpr.get();
11185 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
11186
11187 DeclAccessPair DAP;
11188 FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP);
11189 if (!Found)
11190 return false;
11191
11192 // Emitting multiple diagnostics for a function that is both inaccessible and
11193 // unavailable is consistent with our behavior elsewhere. So, always check
11194 // for both.
11195 DiagnoseUseOfDecl(Found, E->getExprLoc());
11196 CheckAddressOfMemberAccess(E, DAP);
11197 Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
11198 if (Fixed->getType()->isFunctionType())
11199 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
11200 else
11201 SrcExpr = Fixed;
11202 return true;
11203}
11204
George Burgess IV3cde9bf2016-03-19 21:36:10 +000011205/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011206/// resolve that overloaded function expression down to a single function.
11207///
11208/// This routine can only resolve template-ids that refer to a single function
11209/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011210/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011211/// as described in C++0x [temp.arg.explicit]p3.
Alp Toker67b47ac2013-10-20 18:48:56 +000011212///
11213/// If no template-ids are found, no diagnostics are emitted and NULL is
11214/// returned.
John McCall0009fcc2011-04-26 20:42:42 +000011215FunctionDecl *
11216Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
11217 bool Complain,
11218 DeclAccessPair *FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011219 // C++ [over.over]p1:
11220 // [...] [Note: any redundant set of parentheses surrounding the
11221 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011222 // C++ [over.over]p1:
11223 // [...] The overloaded function name can be preceded by the &
11224 // operator.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011225
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011226 // If we didn't actually find any template-ids, we're done.
John McCall0009fcc2011-04-26 20:42:42 +000011227 if (!ovl->hasExplicitTemplateArgs())
Craig Topperc3ec1492014-05-26 06:22:03 +000011228 return nullptr;
John McCall1acbbb52010-02-02 06:20:04 +000011229
11230 TemplateArgumentListInfo ExplicitTemplateArgs;
James Y Knight04ec5bf2015-12-24 02:59:37 +000011231 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
Larisse Voufo98b20f12013-07-19 23:00:19 +000011232 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011233
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011234 // Look through all of the overloaded functions, searching for one
11235 // whose type matches exactly.
Craig Topperc3ec1492014-05-26 06:22:03 +000011236 FunctionDecl *Matched = nullptr;
John McCall0009fcc2011-04-26 20:42:42 +000011237 for (UnresolvedSetIterator I = ovl->decls_begin(),
11238 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011239 // C++0x [temp.arg.explicit]p3:
11240 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011241 // where deduction is not done, if a template argument list is
11242 // specified and it, along with any default template arguments,
11243 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011244 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +000011245 FunctionTemplateDecl *FunctionTemplate
11246 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011247
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011248 // C++ [over.over]p2:
11249 // If the name is a function template, template argument deduction is
11250 // done (14.8.2.2), and if the argument deduction succeeds, the
11251 // resulting template argument list is used to generate a single
11252 // function template specialization, which is added to the set of
11253 // overloaded functions considered.
Craig Topperc3ec1492014-05-26 06:22:03 +000011254 FunctionDecl *Specialization = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +000011255 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011256 if (TemplateDeductionResult Result
11257 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
Douglas Gregor19a41f12013-04-17 08:45:07 +000011258 Specialization, Info,
Richard Smithbaa47832016-12-01 02:11:49 +000011259 /*IsAddressOfFunction*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000011260 // Make a note of the failed deduction for diagnostics.
11261 // TODO: Actually use the failed-deduction info?
11262 FailedCandidates.addCandidate()
Richard Smithc2bebe92016-05-11 20:37:46 +000011263 .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
Larisse Voufo98b20f12013-07-19 23:00:19 +000011264 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011265 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011266 }
11267
John McCall0009fcc2011-04-26 20:42:42 +000011268 assert(Specialization && "no specialization and no error?");
11269
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011270 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +000011271 if (Matched) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000011272 if (Complain) {
John McCall0009fcc2011-04-26 20:42:42 +000011273 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
11274 << ovl->getName();
11275 NoteAllOverloadCandidates(ovl);
Douglas Gregorb491ed32011-02-19 21:32:49 +000011276 }
Craig Topperc3ec1492014-05-26 06:22:03 +000011277 return nullptr;
John McCall0009fcc2011-04-26 20:42:42 +000011278 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000011279
John McCall0009fcc2011-04-26 20:42:42 +000011280 Matched = Specialization;
11281 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011282 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011283
Richard Smith9095e5b2016-11-01 01:31:23 +000011284 if (Matched &&
11285 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
Craig Topperc3ec1492014-05-26 06:22:03 +000011286 return nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +000011287
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011288 return Matched;
11289}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011290
Douglas Gregor1beec452011-03-12 01:48:56 +000011291
11292
11293
John McCall50a2c2c2011-10-11 23:14:30 +000011294// Resolve and fix an overloaded expression that can be resolved
11295// because it identifies a single function template specialization.
11296//
Douglas Gregor1beec452011-03-12 01:48:56 +000011297// Last three arguments should only be supplied if Complain = true
John McCall50a2c2c2011-10-11 23:14:30 +000011298//
11299// Return true if it was logically possible to so resolve the
11300// expression, regardless of whether or not it succeeded. Always
11301// returns true if 'complain' is set.
11302bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
11303 ExprResult &SrcExpr, bool doFunctionPointerConverion,
Craig Toppere335f252015-10-04 04:53:55 +000011304 bool complain, SourceRange OpRangeForComplaining,
Douglas Gregor1beec452011-03-12 01:48:56 +000011305 QualType DestTypeForComplaining,
John McCall0009fcc2011-04-26 20:42:42 +000011306 unsigned DiagIDForComplaining) {
John McCall50a2c2c2011-10-11 23:14:30 +000011307 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregor1beec452011-03-12 01:48:56 +000011308
John McCall50a2c2c2011-10-11 23:14:30 +000011309 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregor1beec452011-03-12 01:48:56 +000011310
John McCall0009fcc2011-04-26 20:42:42 +000011311 DeclAccessPair found;
11312 ExprResult SingleFunctionExpression;
11313 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
11314 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011315 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall50a2c2c2011-10-11 23:14:30 +000011316 SrcExpr = ExprError();
11317 return true;
11318 }
John McCall0009fcc2011-04-26 20:42:42 +000011319
11320 // It is only correct to resolve to an instance method if we're
11321 // resolving a form that's permitted to be a pointer to member.
11322 // Otherwise we'll end up making a bound member expression, which
11323 // is illegal in all the contexts we resolve like this.
11324 if (!ovl.HasFormOfMemberPointer &&
11325 isa<CXXMethodDecl>(fn) &&
11326 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall50a2c2c2011-10-11 23:14:30 +000011327 if (!complain) return false;
11328
11329 Diag(ovl.Expression->getExprLoc(),
11330 diag::err_bound_member_function)
11331 << 0 << ovl.Expression->getSourceRange();
11332
11333 // TODO: I believe we only end up here if there's a mix of
11334 // static and non-static candidates (otherwise the expression
11335 // would have 'bound member' type, not 'overload' type).
11336 // Ideally we would note which candidate was chosen and why
11337 // the static candidates were rejected.
11338 SrcExpr = ExprError();
11339 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000011340 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +000011341
Sylvestre Ledrua5202662012-07-31 06:56:50 +000011342 // Fix the expression to refer to 'fn'.
John McCall0009fcc2011-04-26 20:42:42 +000011343 SingleFunctionExpression =
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011344 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
John McCall0009fcc2011-04-26 20:42:42 +000011345
11346 // If desired, do function-to-pointer decay.
John McCall50a2c2c2011-10-11 23:14:30 +000011347 if (doFunctionPointerConverion) {
John McCall0009fcc2011-04-26 20:42:42 +000011348 SingleFunctionExpression =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011349 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
John McCall50a2c2c2011-10-11 23:14:30 +000011350 if (SingleFunctionExpression.isInvalid()) {
11351 SrcExpr = ExprError();
11352 return true;
11353 }
11354 }
John McCall0009fcc2011-04-26 20:42:42 +000011355 }
11356
11357 if (!SingleFunctionExpression.isUsable()) {
11358 if (complain) {
11359 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
11360 << ovl.Expression->getName()
11361 << DestTypeForComplaining
11362 << OpRangeForComplaining
11363 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall50a2c2c2011-10-11 23:14:30 +000011364 NoteAllOverloadCandidates(SrcExpr.get());
11365
11366 SrcExpr = ExprError();
11367 return true;
11368 }
11369
11370 return false;
John McCall0009fcc2011-04-26 20:42:42 +000011371 }
11372
John McCall50a2c2c2011-10-11 23:14:30 +000011373 SrcExpr = SingleFunctionExpression;
11374 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000011375}
11376
Douglas Gregorcabea402009-09-22 15:41:20 +000011377/// \brief Add a single candidate to the overload set.
11378static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +000011379 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +000011380 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011381 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000011382 OverloadCandidateSet &CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +000011383 bool PartialOverloading,
11384 bool KnownValid) {
John McCalla0296f72010-03-19 07:35:19 +000011385 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +000011386 if (isa<UsingShadowDecl>(Callee))
11387 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
11388
Douglas Gregorcabea402009-09-22 15:41:20 +000011389 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith95ce4f62011-06-26 22:19:54 +000011390 if (ExplicitTemplateArgs) {
11391 assert(!KnownValid && "Explicit template arguments?");
11392 return;
11393 }
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011394 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
11395 /*SuppressUsedConversions=*/false,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011396 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000011397 return;
John McCalld14a8642009-11-21 08:51:07 +000011398 }
11399
11400 if (FunctionTemplateDecl *FuncTemplate
11401 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +000011402 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011403 ExplicitTemplateArgs, Args, CandidateSet,
11404 /*SuppressUsedConversions=*/false,
11405 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +000011406 return;
11407 }
11408
Richard Smith95ce4f62011-06-26 22:19:54 +000011409 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregorcabea402009-09-22 15:41:20 +000011410}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011411
Douglas Gregorcabea402009-09-22 15:41:20 +000011412/// \brief Add the overload candidates named by callee and/or found by argument
11413/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +000011414void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011415 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000011416 OverloadCandidateSet &CandidateSet,
11417 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +000011418
11419#ifndef NDEBUG
11420 // Verify that ArgumentDependentLookup is consistent with the rules
11421 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +000011422 //
Douglas Gregorcabea402009-09-22 15:41:20 +000011423 // Let X be the lookup set produced by unqualified lookup (3.4.1)
11424 // and let Y be the lookup set produced by argument dependent
11425 // lookup (defined as follows). If X contains
11426 //
11427 // -- a declaration of a class member, or
11428 //
11429 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +000011430 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +000011431 //
11432 // -- a declaration that is neither a function or a function
11433 // template
11434 //
11435 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +000011436
John McCall57500772009-12-16 12:17:52 +000011437 if (ULE->requiresADL()) {
11438 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11439 E = ULE->decls_end(); I != E; ++I) {
11440 assert(!(*I)->getDeclContext()->isRecord());
11441 assert(isa<UsingShadowDecl>(*I) ||
11442 !(*I)->getDeclContext()->isFunctionOrMethod());
11443 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +000011444 }
11445 }
11446#endif
11447
John McCall57500772009-12-16 12:17:52 +000011448 // It would be nice to avoid this copy.
11449 TemplateArgumentListInfo TABuffer;
Craig Topperc3ec1492014-05-26 06:22:03 +000011450 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
John McCall57500772009-12-16 12:17:52 +000011451 if (ULE->hasExplicitTemplateArgs()) {
11452 ULE->copyTemplateArgumentsInto(TABuffer);
11453 ExplicitTemplateArgs = &TABuffer;
11454 }
11455
11456 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11457 E = ULE->decls_end(); I != E; ++I)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011458 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
11459 CandidateSet, PartialOverloading,
11460 /*KnownValid*/ true);
John McCalld14a8642009-11-21 08:51:07 +000011461
John McCall57500772009-12-16 12:17:52 +000011462 if (ULE->requiresADL())
Richard Smith100b24a2014-04-17 01:52:14 +000011463 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011464 Args, ExplicitTemplateArgs,
Richard Smithb6626742012-10-18 17:56:02 +000011465 CandidateSet, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000011466}
John McCalld681c392009-12-16 08:11:27 +000011467
Richard Smith0603bbb2013-06-12 22:56:54 +000011468/// Determine whether a declaration with the specified name could be moved into
11469/// a different namespace.
11470static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
11471 switch (Name.getCXXOverloadedOperator()) {
11472 case OO_New: case OO_Array_New:
11473 case OO_Delete: case OO_Array_Delete:
11474 return false;
11475
11476 default:
11477 return true;
11478 }
11479}
11480
Richard Smith998a5912011-06-05 22:42:48 +000011481/// Attempt to recover from an ill-formed use of a non-dependent name in a
11482/// template, where the non-dependent name was declared after the template
11483/// was defined. This is common in code written for a compilers which do not
11484/// correctly implement two-stage name lookup.
11485///
11486/// Returns true if a viable candidate was found and a diagnostic was issued.
11487static bool
11488DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
11489 const CXXScopeSpec &SS, LookupResult &R,
Richard Smith100b24a2014-04-17 01:52:14 +000011490 OverloadCandidateSet::CandidateSetKind CSK,
Richard Smith998a5912011-06-05 22:42:48 +000011491 TemplateArgumentListInfo *ExplicitTemplateArgs,
Hans Wennborg64937c62015-06-11 21:21:57 +000011492 ArrayRef<Expr *> Args,
11493 bool *DoDiagnoseEmptyLookup = nullptr) {
Richard Smith998a5912011-06-05 22:42:48 +000011494 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
11495 return false;
11496
11497 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewyckyfcd5e7a2012-03-14 20:41:00 +000011498 if (DC->isTransparentContext())
11499 continue;
11500
Richard Smith998a5912011-06-05 22:42:48 +000011501 SemaRef.LookupQualifiedName(R, DC);
11502
11503 if (!R.empty()) {
11504 R.suppressDiagnostics();
11505
11506 if (isa<CXXRecordDecl>(DC)) {
11507 // Don't diagnose names we find in classes; we get much better
11508 // diagnostics for these from DiagnoseEmptyLookup.
11509 R.clear();
Hans Wennborg64937c62015-06-11 21:21:57 +000011510 if (DoDiagnoseEmptyLookup)
11511 *DoDiagnoseEmptyLookup = true;
Richard Smith998a5912011-06-05 22:42:48 +000011512 return false;
11513 }
11514
Richard Smith100b24a2014-04-17 01:52:14 +000011515 OverloadCandidateSet Candidates(FnLoc, CSK);
Richard Smith998a5912011-06-05 22:42:48 +000011516 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
11517 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011518 ExplicitTemplateArgs, Args,
Richard Smith95ce4f62011-06-26 22:19:54 +000011519 Candidates, false, /*KnownValid*/ false);
Richard Smith998a5912011-06-05 22:42:48 +000011520
11521 OverloadCandidateSet::iterator Best;
Richard Smith95ce4f62011-06-26 22:19:54 +000011522 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smith998a5912011-06-05 22:42:48 +000011523 // No viable functions. Don't bother the user with notes for functions
11524 // which don't work and shouldn't be found anyway.
Richard Smith95ce4f62011-06-26 22:19:54 +000011525 R.clear();
Richard Smith998a5912011-06-05 22:42:48 +000011526 return false;
Richard Smith95ce4f62011-06-26 22:19:54 +000011527 }
Richard Smith998a5912011-06-05 22:42:48 +000011528
11529 // Find the namespaces where ADL would have looked, and suggest
11530 // declaring the function there instead.
11531 Sema::AssociatedNamespaceSet AssociatedNamespaces;
11532 Sema::AssociatedClassSet AssociatedClasses;
John McCall7d8b0412012-08-24 20:38:34 +000011533 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
Richard Smith998a5912011-06-05 22:42:48 +000011534 AssociatedNamespaces,
11535 AssociatedClasses);
Chandler Carruthd50f1692011-06-05 23:36:55 +000011536 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smith0603bbb2013-06-12 22:56:54 +000011537 if (canBeDeclaredInNamespace(R.getLookupName())) {
11538 DeclContext *Std = SemaRef.getStdNamespace();
11539 for (Sema::AssociatedNamespaceSet::iterator
11540 it = AssociatedNamespaces.begin(),
11541 end = AssociatedNamespaces.end(); it != end; ++it) {
11542 // Never suggest declaring a function within namespace 'std'.
11543 if (Std && Std->Encloses(*it))
11544 continue;
Richard Smith21bae432012-12-22 02:46:14 +000011545
Richard Smith0603bbb2013-06-12 22:56:54 +000011546 // Never suggest declaring a function within a namespace with a
11547 // reserved name, like __gnu_cxx.
11548 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
11549 if (NS &&
11550 NS->getQualifiedNameAsString().find("__") != std::string::npos)
11551 continue;
11552
11553 SuggestedNamespaces.insert(*it);
11554 }
Richard Smith998a5912011-06-05 22:42:48 +000011555 }
11556
11557 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
11558 << R.getLookupName();
Chandler Carruthd50f1692011-06-05 23:36:55 +000011559 if (SuggestedNamespaces.empty()) {
Richard Smith998a5912011-06-05 22:42:48 +000011560 SemaRef.Diag(Best->Function->getLocation(),
11561 diag::note_not_found_by_two_phase_lookup)
11562 << R.getLookupName() << 0;
Chandler Carruthd50f1692011-06-05 23:36:55 +000011563 } else if (SuggestedNamespaces.size() == 1) {
Richard Smith998a5912011-06-05 22:42:48 +000011564 SemaRef.Diag(Best->Function->getLocation(),
11565 diag::note_not_found_by_two_phase_lookup)
Chandler Carruthd50f1692011-06-05 23:36:55 +000011566 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smith998a5912011-06-05 22:42:48 +000011567 } else {
11568 // FIXME: It would be useful to list the associated namespaces here,
11569 // but the diagnostics infrastructure doesn't provide a way to produce
11570 // a localized representation of a list of items.
11571 SemaRef.Diag(Best->Function->getLocation(),
11572 diag::note_not_found_by_two_phase_lookup)
11573 << R.getLookupName() << 2;
11574 }
11575
11576 // Try to recover by calling this function.
11577 return true;
11578 }
11579
11580 R.clear();
11581 }
11582
11583 return false;
11584}
11585
11586/// Attempt to recover from ill-formed use of a non-dependent operator in a
11587/// template, where the non-dependent operator was declared after the template
11588/// was defined.
11589///
11590/// Returns true if a viable candidate was found and a diagnostic was issued.
11591static bool
11592DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
11593 SourceLocation OpLoc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011594 ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +000011595 DeclarationName OpName =
11596 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
11597 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
11598 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Richard Smith100b24a2014-04-17 01:52:14 +000011599 OverloadCandidateSet::CSK_Operator,
Craig Topperc3ec1492014-05-26 06:22:03 +000011600 /*ExplicitTemplateArgs=*/nullptr, Args);
Richard Smith998a5912011-06-05 22:42:48 +000011601}
11602
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000011603namespace {
Richard Smith88d67f32012-09-25 04:46:05 +000011604class BuildRecoveryCallExprRAII {
11605 Sema &SemaRef;
11606public:
11607 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
11608 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
11609 SemaRef.IsBuildingRecoveryCallExpr = true;
11610 }
11611
11612 ~BuildRecoveryCallExprRAII() {
11613 SemaRef.IsBuildingRecoveryCallExpr = false;
11614 }
11615};
11616
Alexander Kornienkoab9db512015-06-22 23:07:51 +000011617}
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000011618
Kaelyn Takata89c881b2014-10-27 18:07:29 +000011619static std::unique_ptr<CorrectionCandidateCallback>
11620MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
11621 bool HasTemplateArgs, bool AllowTypoCorrection) {
11622 if (!AllowTypoCorrection)
11623 return llvm::make_unique<NoTypoCorrectionCCC>();
11624 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
11625 HasTemplateArgs, ME);
11626}
11627
John McCalld681c392009-12-16 08:11:27 +000011628/// Attempts to recover from a call where no functions were found.
11629///
11630/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +000011631static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +000011632BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +000011633 UnresolvedLookupExpr *ULE,
11634 SourceLocation LParenLoc,
Craig Toppere3d2ecbe2014-06-28 23:22:33 +000011635 MutableArrayRef<Expr *> Args,
Richard Smith998a5912011-06-05 22:42:48 +000011636 SourceLocation RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000011637 bool EmptyLookup, bool AllowTypoCorrection) {
Richard Smith88d67f32012-09-25 04:46:05 +000011638 // Do not try to recover if it is already building a recovery call.
11639 // This stops infinite loops for template instantiations like
11640 //
11641 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
11642 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
11643 //
11644 if (SemaRef.IsBuildingRecoveryCallExpr)
11645 return ExprError();
11646 BuildRecoveryCallExprRAII RCE(SemaRef);
John McCalld681c392009-12-16 08:11:27 +000011647
11648 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +000011649 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +000011650 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCalld681c392009-12-16 08:11:27 +000011651
John McCall57500772009-12-16 12:17:52 +000011652 TemplateArgumentListInfo TABuffer;
Craig Topperc3ec1492014-05-26 06:22:03 +000011653 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
John McCall57500772009-12-16 12:17:52 +000011654 if (ULE->hasExplicitTemplateArgs()) {
11655 ULE->copyTemplateArgumentsInto(TABuffer);
11656 ExplicitTemplateArgs = &TABuffer;
11657 }
11658
John McCalld681c392009-12-16 08:11:27 +000011659 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
11660 Sema::LookupOrdinaryName);
Hans Wennborg64937c62015-06-11 21:21:57 +000011661 bool DoDiagnoseEmptyLookup = EmptyLookup;
Richard Smith998a5912011-06-05 22:42:48 +000011662 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Richard Smith100b24a2014-04-17 01:52:14 +000011663 OverloadCandidateSet::CSK_Normal,
Hans Wennborg64937c62015-06-11 21:21:57 +000011664 ExplicitTemplateArgs, Args,
11665 &DoDiagnoseEmptyLookup) &&
11666 (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup(
11667 S, SS, R,
11668 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
11669 ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
11670 ExplicitTemplateArgs, Args)))
John McCallfaf5fb42010-08-26 23:41:50 +000011671 return ExprError();
John McCalld681c392009-12-16 08:11:27 +000011672
John McCall57500772009-12-16 12:17:52 +000011673 assert(!R.empty() && "lookup results empty despite recovery");
11674
Richard Smith151c4562016-12-20 21:35:28 +000011675 // If recovery created an ambiguity, just bail out.
11676 if (R.isAmbiguous()) {
11677 R.suppressDiagnostics();
11678 return ExprError();
11679 }
11680
John McCall57500772009-12-16 12:17:52 +000011681 // Build an implicit member call if appropriate. Just drop the
11682 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +000011683 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +000011684 if ((*R.begin())->isCXXClassMember())
Aaron Ballman6924dcd2015-09-01 14:49:24 +000011685 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
11686 ExplicitTemplateArgs, S);
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000011687 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnara7945c982012-01-27 09:46:47 +000011688 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000011689 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +000011690 else
11691 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
11692
11693 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +000011694 return ExprError();
John McCall57500772009-12-16 12:17:52 +000011695
11696 // This shouldn't cause an infinite loop because we're giving it
Richard Smith998a5912011-06-05 22:42:48 +000011697 // an expression with viable lookup results, which should never
John McCall57500772009-12-16 12:17:52 +000011698 // end up here.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011699 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011700 MultiExprArg(Args.data(), Args.size()),
11701 RParenLoc);
John McCalld681c392009-12-16 08:11:27 +000011702}
Douglas Gregor4038cf42010-06-08 17:35:15 +000011703
Sam Panzer0f384432012-08-21 00:52:01 +000011704/// \brief Constructs and populates an OverloadedCandidateSet from
11705/// the given function.
11706/// \returns true when an the ExprResult output parameter has been set.
11707bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
11708 UnresolvedLookupExpr *ULE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011709 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011710 SourceLocation RParenLoc,
11711 OverloadCandidateSet *CandidateSet,
11712 ExprResult *Result) {
John McCall57500772009-12-16 12:17:52 +000011713#ifndef NDEBUG
11714 if (ULE->requiresADL()) {
11715 // To do ADL, we must have found an unqualified name.
11716 assert(!ULE->getQualifier() && "qualified name with ADL");
11717
11718 // We don't perform ADL for implicit declarations of builtins.
11719 // Verify that this was correctly set up.
11720 FunctionDecl *F;
11721 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
11722 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
11723 F->getBuiltinID() && F->isImplicit())
David Blaikie83d382b2011-09-23 05:06:16 +000011724 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011725
John McCall57500772009-12-16 12:17:52 +000011726 // We don't perform ADL in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011727 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smithb6626742012-10-18 17:56:02 +000011728 }
John McCall57500772009-12-16 12:17:52 +000011729#endif
11730
John McCall4124c492011-10-17 18:40:02 +000011731 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011732 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
Sam Panzer0f384432012-08-21 00:52:01 +000011733 *Result = ExprError();
11734 return true;
11735 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +000011736
John McCall57500772009-12-16 12:17:52 +000011737 // Add the functions denoted by the callee to the set of candidate
11738 // functions, including those from argument-dependent lookup.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011739 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
John McCalld681c392009-12-16 08:11:27 +000011740
Hans Wennborgb2747382015-06-12 21:23:23 +000011741 if (getLangOpts().MSVCCompat &&
11742 CurContext->isDependentContext() && !isSFINAEContext() &&
Hans Wennborg64937c62015-06-11 21:21:57 +000011743 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
11744
11745 OverloadCandidateSet::iterator Best;
11746 if (CandidateSet->empty() ||
11747 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) ==
11748 OR_No_Viable_Function) {
11749 // In Microsoft mode, if we are inside a template class member function then
11750 // create a type dependent CallExpr. The goal is to postpone name lookup
11751 // to instantiation time to be able to search into type dependent base
11752 // classes.
11753 CallExpr *CE = new (Context) CallExpr(
11754 Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc);
Sebastian Redlb49c46c2011-09-24 17:48:00 +000011755 CE->setTypeDependent(true);
Richard Smithed9b8f02015-09-23 21:30:47 +000011756 CE->setValueDependent(true);
11757 CE->setInstantiationDependent(true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011758 *Result = CE;
Sam Panzer0f384432012-08-21 00:52:01 +000011759 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +000011760 }
Francois Pichetbcf64712011-09-07 00:14:57 +000011761 }
John McCalld681c392009-12-16 08:11:27 +000011762
Hans Wennborg64937c62015-06-11 21:21:57 +000011763 if (CandidateSet->empty())
11764 return false;
11765
John McCall4124c492011-10-17 18:40:02 +000011766 UnbridgedCasts.restore();
Sam Panzer0f384432012-08-21 00:52:01 +000011767 return false;
11768}
John McCall4124c492011-10-17 18:40:02 +000011769
Sam Panzer0f384432012-08-21 00:52:01 +000011770/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
11771/// the completed call expression. If overload resolution fails, emits
11772/// diagnostics and returns ExprError()
11773static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11774 UnresolvedLookupExpr *ULE,
11775 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011776 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011777 SourceLocation RParenLoc,
11778 Expr *ExecConfig,
11779 OverloadCandidateSet *CandidateSet,
11780 OverloadCandidateSet::iterator *Best,
11781 OverloadingResult OverloadResult,
11782 bool AllowTypoCorrection) {
11783 if (CandidateSet->empty())
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011784 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011785 RParenLoc, /*EmptyLookup=*/true,
11786 AllowTypoCorrection);
11787
11788 switch (OverloadResult) {
John McCall57500772009-12-16 12:17:52 +000011789 case OR_Success: {
Sam Panzer0f384432012-08-21 00:52:01 +000011790 FunctionDecl *FDecl = (*Best)->Function;
Sam Panzer0f384432012-08-21 00:52:01 +000011791 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000011792 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
11793 return ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000011794 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011795 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11796 ExecConfig);
John McCall57500772009-12-16 12:17:52 +000011797 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011798
Richard Smith998a5912011-06-05 22:42:48 +000011799 case OR_No_Viable_Function: {
11800 // Try to recover by looking for viable functions which the user might
11801 // have meant to call.
Sam Panzer0f384432012-08-21 00:52:01 +000011802 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011803 Args, RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000011804 /*EmptyLookup=*/false,
11805 AllowTypoCorrection);
Richard Smith998a5912011-06-05 22:42:48 +000011806 if (!Recovery.isInvalid())
11807 return Recovery;
11808
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011809 // If the user passes in a function that we can't take the address of, we
11810 // generally end up emitting really bad error messages. Here, we attempt to
11811 // emit better ones.
11812 for (const Expr *Arg : Args) {
11813 if (!Arg->getType()->isFunctionType())
11814 continue;
11815 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
11816 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
11817 if (FD &&
11818 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
11819 Arg->getExprLoc()))
11820 return ExprError();
11821 }
11822 }
11823
11824 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_no_viable_function_in_call)
11825 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011826 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011827 break;
Richard Smith998a5912011-06-05 22:42:48 +000011828 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011829
11830 case OR_Ambiguous:
Sam Panzer0f384432012-08-21 00:52:01 +000011831 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +000011832 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011833 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011834 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000011835
Sam Panzer0f384432012-08-21 00:52:01 +000011836 case OR_Deleted: {
11837 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
11838 << (*Best)->Function->isDeleted()
11839 << ULE->getName()
11840 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
11841 << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011842 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Argyrios Kyrtzidis3eaa22a2011-11-04 15:58:13 +000011843
Sam Panzer0f384432012-08-21 00:52:01 +000011844 // We emitted an error for the unvailable/deleted function call but keep
11845 // the call in the AST.
11846 FunctionDecl *FDecl = (*Best)->Function;
11847 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011848 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11849 ExecConfig);
Sam Panzer0f384432012-08-21 00:52:01 +000011850 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011851 }
11852
Douglas Gregorb412e172010-07-25 18:17:45 +000011853 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +000011854 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011855}
11856
George Burgess IV7204ed92016-01-07 02:26:57 +000011857static void markUnaddressableCandidatesUnviable(Sema &S,
11858 OverloadCandidateSet &CS) {
11859 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
11860 if (I->Viable &&
11861 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
11862 I->Viable = false;
11863 I->FailureKind = ovl_fail_addr_not_available;
11864 }
11865 }
11866}
11867
Sam Panzer0f384432012-08-21 00:52:01 +000011868/// BuildOverloadedCallExpr - Given the call expression that calls Fn
11869/// (which eventually refers to the declaration Func) and the call
11870/// arguments Args/NumArgs, attempt to resolve the function call down
11871/// to a specific function. If overload resolution succeeds, returns
11872/// the call expression produced by overload resolution.
11873/// Otherwise, emits diagnostics and returns ExprError.
11874ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
11875 UnresolvedLookupExpr *ULE,
11876 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011877 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011878 SourceLocation RParenLoc,
11879 Expr *ExecConfig,
George Burgess IV7204ed92016-01-07 02:26:57 +000011880 bool AllowTypoCorrection,
11881 bool CalleesAddressIsTaken) {
Richard Smith100b24a2014-04-17 01:52:14 +000011882 OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
11883 OverloadCandidateSet::CSK_Normal);
Sam Panzer0f384432012-08-21 00:52:01 +000011884 ExprResult result;
11885
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011886 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
11887 &result))
Sam Panzer0f384432012-08-21 00:52:01 +000011888 return result;
11889
George Burgess IV7204ed92016-01-07 02:26:57 +000011890 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
11891 // functions that aren't addressible are considered unviable.
11892 if (CalleesAddressIsTaken)
11893 markUnaddressableCandidatesUnviable(*this, CandidateSet);
11894
Sam Panzer0f384432012-08-21 00:52:01 +000011895 OverloadCandidateSet::iterator Best;
11896 OverloadingResult OverloadResult =
11897 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
11898
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011899 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011900 RParenLoc, ExecConfig, &CandidateSet,
11901 &Best, OverloadResult,
11902 AllowTypoCorrection);
11903}
11904
John McCall4c4c1df2010-01-26 03:27:55 +000011905static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +000011906 return Functions.size() > 1 ||
11907 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
11908}
11909
Douglas Gregor084d8552009-03-13 23:49:33 +000011910/// \brief Create a unary operation that may resolve to an overloaded
11911/// operator.
11912///
11913/// \param OpLoc The location of the operator itself (e.g., '*').
11914///
Craig Toppera92ffb02015-12-10 08:51:49 +000011915/// \param Opc The UnaryOperatorKind that describes this operator.
Douglas Gregor084d8552009-03-13 23:49:33 +000011916///
James Dennett18348b62012-06-22 08:52:37 +000011917/// \param Fns The set of non-member functions that will be
Douglas Gregor084d8552009-03-13 23:49:33 +000011918/// considered by overload resolution. The caller needs to build this
11919/// set based on the context using, e.g.,
11920/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11921/// set should not contain any member functions; those will be added
11922/// by CreateOverloadedUnaryOp().
11923///
James Dennett91738ff2012-06-22 10:32:46 +000011924/// \param Input The input argument.
John McCalldadc5752010-08-24 06:29:42 +000011925ExprResult
Craig Toppera92ffb02015-12-10 08:51:49 +000011926Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
John McCall4c4c1df2010-01-26 03:27:55 +000011927 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +000011928 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +000011929 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
11930 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
11931 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011932 // TODO: provide better source location info.
11933 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +000011934
John McCall4124c492011-10-17 18:40:02 +000011935 if (checkPlaceholderForOverload(*this, Input))
11936 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011937
Craig Topperc3ec1492014-05-26 06:22:03 +000011938 Expr *Args[2] = { Input, nullptr };
Douglas Gregor084d8552009-03-13 23:49:33 +000011939 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +000011940
Douglas Gregor084d8552009-03-13 23:49:33 +000011941 // For post-increment and post-decrement, add the implicit '0' as
11942 // the second argument, so that we know this is a post-increment or
11943 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +000011944 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +000011945 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +000011946 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
11947 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +000011948 NumArgs = 2;
11949 }
11950
Richard Smithe54c3072013-05-05 15:51:06 +000011951 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
11952
Douglas Gregor084d8552009-03-13 23:49:33 +000011953 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +000011954 if (Fns.empty())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011955 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
11956 VK_RValue, OK_Ordinary, OpLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011957
Craig Topperc3ec1492014-05-26 06:22:03 +000011958 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +000011959 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000011960 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000011961 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000011962 /*ADL*/ true, IsOverloaded(Fns),
11963 Fns.begin(), Fns.end());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011964 return new (Context)
11965 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
11966 VK_RValue, OpLoc, false);
Douglas Gregor084d8552009-03-13 23:49:33 +000011967 }
11968
11969 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000011970 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
Douglas Gregor084d8552009-03-13 23:49:33 +000011971
11972 // Add the candidates from the given function set.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011973 AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000011974
11975 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000011976 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000011977
John McCall4c4c1df2010-01-26 03:27:55 +000011978 // Add candidates from ADL.
Richard Smith100b24a2014-04-17 01:52:14 +000011979 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
Craig Topperc3ec1492014-05-26 06:22:03 +000011980 /*ExplicitTemplateArgs*/nullptr,
11981 CandidateSet);
John McCall4c4c1df2010-01-26 03:27:55 +000011982
Douglas Gregor084d8552009-03-13 23:49:33 +000011983 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011984 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000011985
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011986 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11987
Douglas Gregor084d8552009-03-13 23:49:33 +000011988 // Perform overload resolution.
11989 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011990 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +000011991 case OR_Success: {
11992 // We found a built-in operator or an overloaded operator.
11993 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +000011994
Douglas Gregor084d8552009-03-13 23:49:33 +000011995 if (FnDecl) {
11996 // We matched an overloaded operator. Build a call to that
11997 // operator.
Mike Stump11289f42009-09-09 15:08:12 +000011998
Douglas Gregor084d8552009-03-13 23:49:33 +000011999 // Convert the arguments.
12000 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Craig Topperc3ec1492014-05-26 06:22:03 +000012001 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000012002
John Wiegley01296292011-04-08 18:41:53 +000012003 ExprResult InputRes =
Craig Topperc3ec1492014-05-26 06:22:03 +000012004 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012005 Best->FoundDecl, Method);
12006 if (InputRes.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000012007 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012008 Input = InputRes.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000012009 } else {
12010 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000012011 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +000012012 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000012013 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +000012014 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012015 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +000012016 Input);
Douglas Gregore6600372009-12-23 17:40:29 +000012017 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000012018 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012019 Input = InputInit.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000012020 }
12021
Douglas Gregor084d8552009-03-13 23:49:33 +000012022 // Build the actual expression node.
Nick Lewycky134af912013-02-07 05:08:22 +000012023 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012024 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000012025 if (FnExpr.isInvalid())
12026 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +000012027
Richard Smithc1564702013-11-15 02:58:23 +000012028 // Determine the result type.
Alp Toker314cc812014-01-25 16:55:45 +000012029 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000012030 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12031 ResultTy = ResultTy.getNonLValueExprType(Context);
12032
Eli Friedman030eee42009-11-18 03:58:17 +000012033 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +000012034 CallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012035 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
Lang Hames5de91cc2012-10-02 04:45:10 +000012036 ResultTy, VK, OpLoc, false);
John McCall4fa0d5f2010-05-06 18:15:07 +000012037
Alp Toker314cc812014-01-25 16:55:45 +000012038 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
Anders Carlssonf64a3da2009-10-13 21:19:37 +000012039 return ExprError();
12040
George Burgess IVce6284b2017-01-28 02:19:40 +000012041 if (CheckFunctionCall(FnDecl, TheCall,
12042 FnDecl->getType()->castAs<FunctionProtoType>()))
12043 return ExprError();
12044
John McCallb268a282010-08-23 23:25:46 +000012045 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +000012046 } else {
12047 // We matched a built-in operator. Convert the arguments, then
12048 // break out so that we will build the appropriate built-in
12049 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000012050 ExprResult InputRes =
12051 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
12052 Best->Conversions[0], AA_Passing);
12053 if (InputRes.isInvalid())
12054 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012055 Input = InputRes.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000012056 break;
Douglas Gregor084d8552009-03-13 23:49:33 +000012057 }
John Wiegley01296292011-04-08 18:41:53 +000012058 }
12059
12060 case OR_No_Viable_Function:
Richard Smith998a5912011-06-05 22:42:48 +000012061 // This is an erroneous use of an operator which can be overloaded by
12062 // a non-member function. Check for non-member operators which were
12063 // defined too late to be candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000012064 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
Richard Smith998a5912011-06-05 22:42:48 +000012065 // FIXME: Recover by calling the found function.
12066 return ExprError();
12067
John Wiegley01296292011-04-08 18:41:53 +000012068 // No viable function; fall through to handling this as a
12069 // built-in operator, which will produce an error message for us.
12070 break;
12071
12072 case OR_Ambiguous:
12073 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
12074 << UnaryOperator::getOpcodeStr(Opc)
12075 << Input->getType()
12076 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000012077 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
John Wiegley01296292011-04-08 18:41:53 +000012078 UnaryOperator::getOpcodeStr(Opc), OpLoc);
12079 return ExprError();
12080
12081 case OR_Deleted:
12082 Diag(OpLoc, diag::err_ovl_deleted_oper)
12083 << Best->Function->isDeleted()
12084 << UnaryOperator::getOpcodeStr(Opc)
12085 << getDeletedOrUnavailableSuffix(Best->Function)
12086 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000012087 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000012088 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000012089 return ExprError();
12090 }
Douglas Gregor084d8552009-03-13 23:49:33 +000012091
12092 // Either we found no viable overloaded operator or we matched a
12093 // built-in operator. In either case, fall through to trying to
12094 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +000012095 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +000012096}
12097
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012098/// \brief Create a binary operation that may resolve to an overloaded
12099/// operator.
12100///
12101/// \param OpLoc The location of the operator itself (e.g., '+').
12102///
Craig Toppera92ffb02015-12-10 08:51:49 +000012103/// \param Opc The BinaryOperatorKind that describes this operator.
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012104///
James Dennett18348b62012-06-22 08:52:37 +000012105/// \param Fns The set of non-member functions that will be
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012106/// considered by overload resolution. The caller needs to build this
12107/// set based on the context using, e.g.,
12108/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12109/// set should not contain any member functions; those will be added
12110/// by CreateOverloadedBinOp().
12111///
12112/// \param LHS Left-hand argument.
12113/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +000012114ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012115Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Craig Toppera92ffb02015-12-10 08:51:49 +000012116 BinaryOperatorKind Opc,
John McCall4c4c1df2010-01-26 03:27:55 +000012117 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012118 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012119 Expr *Args[2] = { LHS, RHS };
Craig Topperc3ec1492014-05-26 06:22:03 +000012120 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012121
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012122 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
12123 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12124
12125 // If either side is type-dependent, create an appropriate dependent
12126 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +000012127 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +000012128 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012129 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +000012130 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +000012131 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012132 return new (Context) BinaryOperator(
12133 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
12134 OpLoc, FPFeatures.fp_contract);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012135
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012136 return new (Context) CompoundAssignOperator(
12137 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
12138 Context.DependentTy, Context.DependentTy, OpLoc,
12139 FPFeatures.fp_contract);
Douglas Gregor5287f092009-11-05 00:51:44 +000012140 }
John McCall4c4c1df2010-01-26 03:27:55 +000012141
12142 // FIXME: save results of ADL from here?
Craig Topperc3ec1492014-05-26 06:22:03 +000012143 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000012144 // TODO: provide better source location info in DNLoc component.
12145 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +000012146 UnresolvedLookupExpr *Fn
Douglas Gregor0da1d432011-02-28 20:01:57 +000012147 = UnresolvedLookupExpr::Create(Context, NamingClass,
12148 NestedNameSpecifierLoc(), OpNameInfo,
12149 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000012150 Fns.begin(), Fns.end());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012151 return new (Context)
12152 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
12153 VK_RValue, OpLoc, FPFeatures.fp_contract);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012154 }
12155
John McCall4124c492011-10-17 18:40:02 +000012156 // Always do placeholder-like conversions on the RHS.
12157 if (checkPlaceholderForOverload(*this, Args[1]))
12158 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012159
John McCall526ab472011-10-25 17:37:35 +000012160 // Do placeholder-like conversion on the LHS; note that we should
12161 // not get here with a PseudoObject LHS.
12162 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall4124c492011-10-17 18:40:02 +000012163 if (checkPlaceholderForOverload(*this, Args[0]))
12164 return ExprError();
12165
Sebastian Redl6a96bf72009-11-18 23:10:33 +000012166 // If this is the assignment operator, we only perform overload resolution
12167 // if the left-hand side is a class or enumeration type. This is actually
12168 // a hack. The standard requires that we do overload resolution between the
12169 // various built-in candidates, but as DR507 points out, this can lead to
12170 // problems. So we do it this way, which pretty much follows what GCC does.
12171 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +000012172 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +000012173 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012174
John McCalle26a8722010-12-04 08:14:53 +000012175 // If this is the .* operator, which is not overloadable, just
12176 // create a built-in binary operator.
12177 if (Opc == BO_PtrMemD)
12178 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12179
Douglas Gregor084d8552009-03-13 23:49:33 +000012180 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000012181 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012182
12183 // Add the candidates from the given function set.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000012184 AddFunctionCandidates(Fns, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012185
12186 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000012187 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012188
Richard Smith0daabd72014-09-23 20:31:39 +000012189 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
12190 // performed for an assignment operator (nor for operator[] nor operator->,
12191 // which don't get here).
12192 if (Opc != BO_Assign)
12193 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
12194 /*ExplicitTemplateArgs*/ nullptr,
12195 CandidateSet);
John McCall4c4c1df2010-01-26 03:27:55 +000012196
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012197 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000012198 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012199
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012200 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12201
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012202 // Perform overload resolution.
12203 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012204 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +000012205 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012206 // We found a built-in operator or an overloaded operator.
12207 FunctionDecl *FnDecl = Best->Function;
12208
12209 if (FnDecl) {
12210 // We matched an overloaded operator. Build a call to that
12211 // operator.
12212
12213 // Convert the arguments.
12214 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +000012215 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +000012216 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000012217
Chandler Carruth8e543b32010-12-12 08:17:55 +000012218 ExprResult Arg1 =
12219 PerformCopyInitialization(
12220 InitializedEntity::InitializeParameter(Context,
12221 FnDecl->getParamDecl(0)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012222 SourceLocation(), Args[1]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000012223 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012224 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000012225
John Wiegley01296292011-04-08 18:41:53 +000012226 ExprResult Arg0 =
Craig Topperc3ec1492014-05-26 06:22:03 +000012227 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012228 Best->FoundDecl, Method);
12229 if (Arg0.isInvalid())
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000012230 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012231 Args[0] = Arg0.getAs<Expr>();
12232 Args[1] = RHS = Arg1.getAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012233 } else {
12234 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +000012235 ExprResult Arg0 = PerformCopyInitialization(
12236 InitializedEntity::InitializeParameter(Context,
12237 FnDecl->getParamDecl(0)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012238 SourceLocation(), Args[0]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000012239 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012240 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000012241
Chandler Carruth8e543b32010-12-12 08:17:55 +000012242 ExprResult Arg1 =
12243 PerformCopyInitialization(
12244 InitializedEntity::InitializeParameter(Context,
12245 FnDecl->getParamDecl(1)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012246 SourceLocation(), Args[1]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000012247 if (Arg1.isInvalid())
12248 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012249 Args[0] = LHS = Arg0.getAs<Expr>();
12250 Args[1] = RHS = Arg1.getAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012251 }
12252
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012253 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012254 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000012255 Best->FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012256 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000012257 if (FnExpr.isInvalid())
12258 return ExprError();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012259
Richard Smithc1564702013-11-15 02:58:23 +000012260 // Determine the result type.
Alp Toker314cc812014-01-25 16:55:45 +000012261 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000012262 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12263 ResultTy = ResultTy.getNonLValueExprType(Context);
12264
John McCallb268a282010-08-23 23:25:46 +000012265 CXXOperatorCallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012266 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
Lang Hames5de91cc2012-10-02 04:45:10 +000012267 Args, ResultTy, VK, OpLoc,
12268 FPFeatures.fp_contract);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012269
Alp Toker314cc812014-01-25 16:55:45 +000012270 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000012271 FnDecl))
12272 return ExprError();
12273
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000012274 ArrayRef<const Expr *> ArgsArray(Args, 2);
George Burgess IVce6284b2017-01-28 02:19:40 +000012275 const Expr *ImplicitThis = nullptr;
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000012276 // Cut off the implicit 'this'.
George Burgess IVce6284b2017-01-28 02:19:40 +000012277 if (isa<CXXMethodDecl>(FnDecl)) {
12278 ImplicitThis = ArgsArray[0];
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000012279 ArgsArray = ArgsArray.slice(1);
George Burgess IVce6284b2017-01-28 02:19:40 +000012280 }
Richard Trieu36d0b2b2015-01-13 02:32:02 +000012281
12282 // Check for a self move.
12283 if (Op == OO_Equal)
12284 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
12285
George Burgess IVce6284b2017-01-28 02:19:40 +000012286 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
12287 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
12288 VariadicDoesNotApply);
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000012289
John McCallb268a282010-08-23 23:25:46 +000012290 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012291 } else {
12292 // We matched a built-in operator. Convert the arguments, then
12293 // break out so that we will build the appropriate built-in
12294 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000012295 ExprResult ArgsRes0 =
12296 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
12297 Best->Conversions[0], AA_Passing);
12298 if (ArgsRes0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012299 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012300 Args[0] = ArgsRes0.get();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012301
John Wiegley01296292011-04-08 18:41:53 +000012302 ExprResult ArgsRes1 =
12303 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
12304 Best->Conversions[1], AA_Passing);
12305 if (ArgsRes1.isInvalid())
12306 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012307 Args[1] = ArgsRes1.get();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012308 break;
12309 }
12310 }
12311
Douglas Gregor66950a32009-09-30 21:46:01 +000012312 case OR_No_Viable_Function: {
12313 // C++ [over.match.oper]p9:
12314 // If the operator is the operator , [...] and there are no
12315 // viable functions, then the operator is assumed to be the
12316 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +000012317 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +000012318 break;
12319
Chandler Carruth8e543b32010-12-12 08:17:55 +000012320 // For class as left operand for assignment or compound assigment
12321 // operator do not fall through to handling in built-in, but report that
12322 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +000012323 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012324 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +000012325 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +000012326 Diag(OpLoc, diag::err_ovl_no_viable_oper)
12327 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +000012328 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Eli Friedmana31efa02013-08-28 20:35:35 +000012329 if (Args[0]->getType()->isIncompleteType()) {
12330 Diag(OpLoc, diag::note_assign_lhs_incomplete)
12331 << Args[0]->getType()
12332 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12333 }
Douglas Gregor66950a32009-09-30 21:46:01 +000012334 } else {
Richard Smith998a5912011-06-05 22:42:48 +000012335 // This is an erroneous use of an operator which can be overloaded by
12336 // a non-member function. Check for non-member operators which were
12337 // defined too late to be candidates.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012338 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smith998a5912011-06-05 22:42:48 +000012339 // FIXME: Recover by calling the found function.
12340 return ExprError();
12341
Douglas Gregor66950a32009-09-30 21:46:01 +000012342 // No viable function; try to create a built-in operation, which will
12343 // produce an error. Then, show the non-viable candidates.
12344 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +000012345 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012346 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +000012347 "C++ binary operator overloading is missing candidates!");
12348 if (Result.isInvalid())
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012349 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012350 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012351 return Result;
Douglas Gregor66950a32009-09-30 21:46:01 +000012352 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012353
12354 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000012355 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012356 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +000012357 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +000012358 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012359 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012360 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012361 return ExprError();
12362
12363 case OR_Deleted:
Douglas Gregor74f7d502012-02-15 19:33:52 +000012364 if (isImplicitlyDeleted(Best->Function)) {
12365 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12366 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
Richard Smithde1a4872012-12-28 12:23:24 +000012367 << Context.getRecordType(Method->getParent())
12368 << getSpecialMember(Method);
Richard Smith6f1e2c62012-04-02 20:59:25 +000012369
Richard Smithde1a4872012-12-28 12:23:24 +000012370 // The user probably meant to call this special member. Just
12371 // explain why it's deleted.
12372 NoteDeletedFunction(Method);
12373 return ExprError();
Douglas Gregor74f7d502012-02-15 19:33:52 +000012374 } else {
12375 Diag(OpLoc, diag::err_ovl_deleted_oper)
12376 << Best->Function->isDeleted()
12377 << BinaryOperator::getOpcodeStr(Opc)
12378 << getDeletedOrUnavailableSuffix(Best->Function)
12379 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12380 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012381 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000012382 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012383 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +000012384 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012385
Douglas Gregor66950a32009-09-30 21:46:01 +000012386 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +000012387 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012388}
12389
John McCalldadc5752010-08-24 06:29:42 +000012390ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +000012391Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
12392 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +000012393 Expr *Base, Expr *Idx) {
12394 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +000012395 DeclarationName OpName =
12396 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
12397
12398 // If either side is type-dependent, create an appropriate dependent
12399 // expression.
12400 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12401
Craig Topperc3ec1492014-05-26 06:22:03 +000012402 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000012403 // CHECKME: no 'operator' keyword?
12404 DeclarationNameInfo OpNameInfo(OpName, LLoc);
12405 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +000012406 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000012407 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000012408 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000012409 /*ADL*/ true, /*Overloaded*/ false,
12410 UnresolvedSetIterator(),
12411 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +000012412 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +000012413
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012414 return new (Context)
12415 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
12416 Context.DependentTy, VK_RValue, RLoc, false);
Sebastian Redladba46e2009-10-29 20:17:01 +000012417 }
12418
John McCall4124c492011-10-17 18:40:02 +000012419 // Handle placeholders on both operands.
12420 if (checkPlaceholderForOverload(*this, Args[0]))
12421 return ExprError();
12422 if (checkPlaceholderForOverload(*this, Args[1]))
12423 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012424
Sebastian Redladba46e2009-10-29 20:17:01 +000012425 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000012426 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
Sebastian Redladba46e2009-10-29 20:17:01 +000012427
12428 // Subscript can only be overloaded as a member function.
12429
12430 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000012431 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000012432
12433 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000012434 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000012435
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012436 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12437
Sebastian Redladba46e2009-10-29 20:17:01 +000012438 // Perform overload resolution.
12439 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012440 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +000012441 case OR_Success: {
12442 // We found a built-in operator or an overloaded operator.
12443 FunctionDecl *FnDecl = Best->Function;
12444
12445 if (FnDecl) {
12446 // We matched an overloaded operator. Build a call to that
12447 // operator.
12448
John McCalla0296f72010-03-19 07:35:19 +000012449 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall58cc69d2010-01-27 01:50:18 +000012450
Sebastian Redladba46e2009-10-29 20:17:01 +000012451 // Convert the arguments.
12452 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley01296292011-04-08 18:41:53 +000012453 ExprResult Arg0 =
Craig Topperc3ec1492014-05-26 06:22:03 +000012454 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012455 Best->FoundDecl, Method);
12456 if (Arg0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000012457 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012458 Args[0] = Arg0.get();
Sebastian Redladba46e2009-10-29 20:17:01 +000012459
Anders Carlssona68e51e2010-01-29 18:37:50 +000012460 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000012461 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +000012462 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000012463 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +000012464 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012465 SourceLocation(),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012466 Args[1]);
Anders Carlssona68e51e2010-01-29 18:37:50 +000012467 if (InputInit.isInvalid())
12468 return ExprError();
12469
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012470 Args[1] = InputInit.getAs<Expr>();
Anders Carlssona68e51e2010-01-29 18:37:50 +000012471
Sebastian Redladba46e2009-10-29 20:17:01 +000012472 // Build the actual expression node.
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012473 DeclarationNameInfo OpLocInfo(OpName, LLoc);
12474 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012475 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000012476 Best->FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012477 HadMultipleCandidates,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012478 OpLocInfo.getLoc(),
12479 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000012480 if (FnExpr.isInvalid())
12481 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000012482
Richard Smithc1564702013-11-15 02:58:23 +000012483 // Determine the result type
Alp Toker314cc812014-01-25 16:55:45 +000012484 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000012485 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12486 ResultTy = ResultTy.getNonLValueExprType(Context);
12487
John McCallb268a282010-08-23 23:25:46 +000012488 CXXOperatorCallExpr *TheCall =
12489 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012490 FnExpr.get(), Args,
Lang Hames5de91cc2012-10-02 04:45:10 +000012491 ResultTy, VK, RLoc,
12492 false);
Sebastian Redladba46e2009-10-29 20:17:01 +000012493
Alp Toker314cc812014-01-25 16:55:45 +000012494 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
Sebastian Redladba46e2009-10-29 20:17:01 +000012495 return ExprError();
12496
George Burgess IVce6284b2017-01-28 02:19:40 +000012497 if (CheckFunctionCall(Method, TheCall,
12498 Method->getType()->castAs<FunctionProtoType>()))
12499 return ExprError();
12500
John McCallb268a282010-08-23 23:25:46 +000012501 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +000012502 } else {
12503 // We matched a built-in operator. Convert the arguments, then
12504 // break out so that we will build the appropriate built-in
12505 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000012506 ExprResult ArgsRes0 =
12507 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
12508 Best->Conversions[0], AA_Passing);
12509 if (ArgsRes0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000012510 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012511 Args[0] = ArgsRes0.get();
John Wiegley01296292011-04-08 18:41:53 +000012512
12513 ExprResult ArgsRes1 =
12514 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
12515 Best->Conversions[1], AA_Passing);
12516 if (ArgsRes1.isInvalid())
12517 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012518 Args[1] = ArgsRes1.get();
Sebastian Redladba46e2009-10-29 20:17:01 +000012519
12520 break;
12521 }
12522 }
12523
12524 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +000012525 if (CandidateSet.empty())
12526 Diag(LLoc, diag::err_ovl_no_oper)
12527 << Args[0]->getType() << /*subscript*/ 0
12528 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12529 else
12530 Diag(LLoc, diag::err_ovl_no_viable_subscript)
12531 << Args[0]->getType()
12532 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012533 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012534 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +000012535 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000012536 }
12537
12538 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000012539 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012540 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +000012541 << Args[0]->getType() << Args[1]->getType()
12542 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012543 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012544 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000012545 return ExprError();
12546
12547 case OR_Deleted:
12548 Diag(LLoc, diag::err_ovl_deleted_oper)
12549 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012550 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +000012551 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012552 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012553 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000012554 return ExprError();
12555 }
12556
12557 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +000012558 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000012559}
12560
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012561/// BuildCallToMemberFunction - Build a call to a member
12562/// function. MemExpr is the expression that refers to the member
12563/// function (and includes the object parameter), Args/NumArgs are the
12564/// arguments to the function call (not including the object
12565/// parameter). The caller needs to validate that the member
John McCall0009fcc2011-04-26 20:42:42 +000012566/// expression refers to a non-static member function or an overloaded
12567/// member function.
John McCalldadc5752010-08-24 06:29:42 +000012568ExprResult
Mike Stump11289f42009-09-09 15:08:12 +000012569Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012570 SourceLocation LParenLoc,
12571 MultiExprArg Args,
12572 SourceLocation RParenLoc) {
John McCall0009fcc2011-04-26 20:42:42 +000012573 assert(MemExprE->getType() == Context.BoundMemberTy ||
12574 MemExprE->getType() == Context.OverloadTy);
12575
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012576 // Dig out the member expression. This holds both the object
12577 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +000012578 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012579
John McCall0009fcc2011-04-26 20:42:42 +000012580 // Determine whether this is a call to a pointer-to-member function.
12581 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
12582 assert(op->getType() == Context.BoundMemberTy);
12583 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
12584
12585 QualType fnType =
12586 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
12587
12588 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
12589 QualType resultType = proto->getCallResultType(Context);
Alp Toker314cc812014-01-25 16:55:45 +000012590 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
John McCall0009fcc2011-04-26 20:42:42 +000012591
12592 // Check that the object type isn't more qualified than the
12593 // member function we're calling.
12594 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
12595
12596 QualType objectType = op->getLHS()->getType();
12597 if (op->getOpcode() == BO_PtrMemI)
12598 objectType = objectType->castAs<PointerType>()->getPointeeType();
12599 Qualifiers objectQuals = objectType.getQualifiers();
12600
12601 Qualifiers difference = objectQuals - funcQuals;
12602 difference.removeObjCGCAttr();
12603 difference.removeAddressSpace();
12604 if (difference) {
12605 std::string qualsString = difference.getAsString();
12606 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
12607 << fnType.getUnqualifiedType()
12608 << qualsString
12609 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
12610 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +000012611
John McCall0009fcc2011-04-26 20:42:42 +000012612 CXXMemberCallExpr *call
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012613 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall0009fcc2011-04-26 20:42:42 +000012614 resultType, valueKind, RParenLoc);
12615
Alp Toker314cc812014-01-25 16:55:45 +000012616 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
Craig Topperc3ec1492014-05-26 06:22:03 +000012617 call, nullptr))
John McCall0009fcc2011-04-26 20:42:42 +000012618 return ExprError();
12619
Craig Topperc3ec1492014-05-26 06:22:03 +000012620 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
John McCall0009fcc2011-04-26 20:42:42 +000012621 return ExprError();
12622
Richard Trieu9be9c682013-06-22 02:30:38 +000012623 if (CheckOtherCall(call, proto))
12624 return ExprError();
12625
John McCall0009fcc2011-04-26 20:42:42 +000012626 return MaybeBindToTemporary(call);
12627 }
12628
David Majnemerced8bdf2015-02-25 17:36:15 +000012629 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
12630 return new (Context)
12631 CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc);
12632
John McCall4124c492011-10-17 18:40:02 +000012633 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012634 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000012635 return ExprError();
12636
John McCall10eae182009-11-30 22:42:35 +000012637 MemberExpr *MemExpr;
Craig Topperc3ec1492014-05-26 06:22:03 +000012638 CXXMethodDecl *Method = nullptr;
12639 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
12640 NestedNameSpecifier *Qualifier = nullptr;
John McCall10eae182009-11-30 22:42:35 +000012641 if (isa<MemberExpr>(NakedMemExpr)) {
12642 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +000012643 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +000012644 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +000012645 Qualifier = MemExpr->getQualifier();
John McCall4124c492011-10-17 18:40:02 +000012646 UnbridgedCasts.restore();
John McCall10eae182009-11-30 22:42:35 +000012647 } else {
12648 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +000012649 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012650
John McCall6e9f8f62009-12-03 04:06:58 +000012651 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +000012652 Expr::Classification ObjectClassification
12653 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
12654 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +000012655
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012656 // Add overload candidates
Richard Smith100b24a2014-04-17 01:52:14 +000012657 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
12658 OverloadCandidateSet::CSK_Normal);
Mike Stump11289f42009-09-09 15:08:12 +000012659
John McCall2d74de92009-12-01 22:10:20 +000012660 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000012661 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCall2d74de92009-12-01 22:10:20 +000012662 if (UnresExpr->hasExplicitTemplateArgs()) {
12663 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12664 TemplateArgs = &TemplateArgsBuffer;
12665 }
12666
John McCall10eae182009-11-30 22:42:35 +000012667 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
12668 E = UnresExpr->decls_end(); I != E; ++I) {
12669
John McCall6e9f8f62009-12-03 04:06:58 +000012670 NamedDecl *Func = *I;
12671 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
12672 if (isa<UsingShadowDecl>(Func))
12673 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
12674
Douglas Gregor02824322011-01-26 19:30:28 +000012675
Francois Pichet64225792011-01-18 05:04:39 +000012676 // Microsoft supports direct constructor calls.
David Blaikiebbafb8a2012-03-11 07:00:24 +000012677 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012678 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012679 Args, CandidateSet);
Francois Pichet64225792011-01-18 05:04:39 +000012680 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +000012681 // If explicit template arguments were provided, we can't call a
12682 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +000012683 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +000012684 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012685
John McCalla0296f72010-03-19 07:35:19 +000012686 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
George Burgess IVce6284b2017-01-28 02:19:40 +000012687 ObjectClassification, Args, CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +000012688 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000012689 } else {
George Burgess IV177399e2017-01-09 04:12:14 +000012690 AddMethodTemplateCandidate(
12691 cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC,
George Burgess IVce6284b2017-01-28 02:19:40 +000012692 TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet,
George Burgess IV177399e2017-01-09 04:12:14 +000012693 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000012694 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000012695 }
Mike Stump11289f42009-09-09 15:08:12 +000012696
John McCall10eae182009-11-30 22:42:35 +000012697 DeclarationName DeclName = UnresExpr->getMemberName();
12698
John McCall4124c492011-10-17 18:40:02 +000012699 UnbridgedCasts.restore();
12700
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012701 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012702 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +000012703 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012704 case OR_Success:
12705 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +000012706 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +000012707 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000012708 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
12709 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000012710 // If FoundDecl is different from Method (such as if one is a template
12711 // and the other a specialization), make sure DiagnoseUseOfDecl is
12712 // called on both.
12713 // FIXME: This would be more comprehensively addressed by modifying
12714 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
12715 // being used.
12716 if (Method != FoundDecl.getDecl() &&
12717 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
12718 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012719 break;
12720
12721 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +000012722 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012723 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000012724 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012725 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012726 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000012727 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012728
12729 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +000012730 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000012731 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012732 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012733 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000012734 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000012735
12736 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +000012737 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +000012738 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012739 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012740 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012741 << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012742 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000012743 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000012744 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012745 }
12746
John McCall16df1e52010-03-30 21:47:33 +000012747 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +000012748
John McCall2d74de92009-12-01 22:10:20 +000012749 // If overload resolution picked a static member, build a
12750 // non-member call based on that function.
12751 if (Method->isStatic()) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012752 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
12753 RParenLoc);
John McCall2d74de92009-12-01 22:10:20 +000012754 }
12755
John McCall10eae182009-11-30 22:42:35 +000012756 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012757 }
12758
Alp Toker314cc812014-01-25 16:55:45 +000012759 QualType ResultType = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000012760 ExprValueKind VK = Expr::getValueKindForType(ResultType);
12761 ResultType = ResultType.getNonLValueExprType(Context);
12762
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012763 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012764 CXXMemberCallExpr *TheCall =
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012765 new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall7decc9e2010-11-18 06:31:45 +000012766 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012767
Anders Carlssonc4859ba2009-10-10 00:06:20 +000012768 // Check for a valid return type.
Alp Toker314cc812014-01-25 16:55:45 +000012769 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +000012770 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +000012771 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012772
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012773 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +000012774 // We only need to do this if there was actually an overload; otherwise
12775 // it was done at lookup.
John Wiegley01296292011-04-08 18:41:53 +000012776 if (!Method->isStatic()) {
12777 ExprResult ObjectArg =
12778 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
12779 FoundDecl, Method);
12780 if (ObjectArg.isInvalid())
12781 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012782 MemExpr->setBase(ObjectArg.get());
John Wiegley01296292011-04-08 18:41:53 +000012783 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012784
12785 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +000012786 const FunctionProtoType *Proto =
12787 Method->getType()->getAs<FunctionProtoType>();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012788 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012789 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +000012790 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012791
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012792 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000012793
Richard Smith55ce3522012-06-25 20:30:08 +000012794 if (CheckFunctionCall(Method, TheCall, Proto))
John McCall2d74de92009-12-01 22:10:20 +000012795 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +000012796
George Burgess IVaea6ade2015-09-25 17:53:16 +000012797 // In the case the method to call was not selected by the overloading
12798 // resolution process, we still need to handle the enable_if attribute. Do
George Burgess IV0d546532016-11-10 21:47:12 +000012799 // that here, so it will not hide previous -- and more relevant -- errors.
George Burgess IVadd6ab52016-11-16 21:31:25 +000012800 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
George Burgess IVaea6ade2015-09-25 17:53:16 +000012801 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
George Burgess IVadd6ab52016-11-16 21:31:25 +000012802 Diag(MemE->getMemberLoc(),
George Burgess IVaea6ade2015-09-25 17:53:16 +000012803 diag::err_ovl_no_viable_member_function_in_call)
12804 << Method << Method->getSourceRange();
12805 Diag(Method->getLocation(),
George Burgess IV177399e2017-01-09 04:12:14 +000012806 diag::note_ovl_candidate_disabled_by_function_cond_attr)
George Burgess IVaea6ade2015-09-25 17:53:16 +000012807 << Attr->getCond()->getSourceRange() << Attr->getMessage();
12808 return ExprError();
12809 }
12810 }
12811
Anders Carlsson47061ee2011-05-06 14:25:31 +000012812 if ((isa<CXXConstructorDecl>(CurContext) ||
12813 isa<CXXDestructorDecl>(CurContext)) &&
12814 TheCall->getMethodDecl()->isPure()) {
12815 const CXXMethodDecl *MD = TheCall->getMethodDecl();
12816
Davide Italianoccb37382015-07-14 23:36:10 +000012817 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
12818 MemExpr->performsVirtualDispatch(getLangOpts())) {
12819 Diag(MemExpr->getLocStart(),
Anders Carlsson47061ee2011-05-06 14:25:31 +000012820 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
12821 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
12822 << MD->getParent()->getDeclName();
12823
12824 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Davide Italianoccb37382015-07-14 23:36:10 +000012825 if (getLangOpts().AppleKext)
12826 Diag(MemExpr->getLocStart(),
12827 diag::note_pure_qualified_call_kext)
12828 << MD->getParent()->getDeclName()
12829 << MD->getDeclName();
Chandler Carruth59259262011-06-27 08:31:58 +000012830 }
Anders Carlsson47061ee2011-05-06 14:25:31 +000012831 }
Nico Weber5a9259c2016-01-15 21:45:31 +000012832
12833 if (CXXDestructorDecl *DD =
12834 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
12835 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
Justin Lebard35f7062016-07-12 23:23:01 +000012836 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
Nico Weber5a9259c2016-01-15 21:45:31 +000012837 CheckVirtualDtorCall(DD, MemExpr->getLocStart(), /*IsDelete=*/false,
12838 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
12839 MemExpr->getMemberLoc());
12840 }
12841
John McCallb268a282010-08-23 23:25:46 +000012842 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012843}
12844
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012845/// BuildCallToObjectOfClassType - Build a call to an object of class
12846/// type (C++ [over.call.object]), which can end up invoking an
12847/// overloaded function call operator (@c operator()) or performing a
12848/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +000012849ExprResult
John Wiegley01296292011-04-08 18:41:53 +000012850Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregorb0846b02008-12-06 00:22:45 +000012851 SourceLocation LParenLoc,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012852 MultiExprArg Args,
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012853 SourceLocation RParenLoc) {
John McCall4124c492011-10-17 18:40:02 +000012854 if (checkPlaceholderForOverload(*this, Obj))
12855 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012856 ExprResult Object = Obj;
John McCall4124c492011-10-17 18:40:02 +000012857
12858 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012859 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000012860 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012861
Nico Weberb58e51c2014-11-19 05:21:39 +000012862 assert(Object.get()->getType()->isRecordType() &&
12863 "Requires object type argument");
John Wiegley01296292011-04-08 18:41:53 +000012864 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +000012865
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012866 // C++ [over.call.object]p1:
12867 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +000012868 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012869 // candidate functions includes at least the function call
12870 // operators of T. The function call operators of T are obtained by
12871 // ordinary lookup of the name operator() in the context of
12872 // (E).operator().
Richard Smith100b24a2014-04-17 01:52:14 +000012873 OverloadCandidateSet CandidateSet(LParenLoc,
12874 OverloadCandidateSet::CSK_Operator);
Douglas Gregor91f84212008-12-11 16:49:14 +000012875 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +000012876
John Wiegley01296292011-04-08 18:41:53 +000012877 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012878 diag::err_incomplete_object_call, Object.get()))
Douglas Gregorc473cbb2009-11-15 07:48:03 +000012879 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012880
John McCall27b18f82009-11-17 02:14:36 +000012881 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
12882 LookupQualifiedName(R, Record->getDecl());
12883 R.suppressDiagnostics();
12884
Douglas Gregorc473cbb2009-11-15 07:48:03 +000012885 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +000012886 Oper != OperEnd; ++Oper) {
John Wiegley01296292011-04-08 18:41:53 +000012887 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
George Burgess IVce6284b2017-01-28 02:19:40 +000012888 Object.get()->Classify(Context), Args, CandidateSet,
12889 /*SuppressUserConversions=*/false);
Douglas Gregor358e7742009-11-07 17:23:56 +000012890 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012891
Douglas Gregorab7897a2008-11-19 22:57:39 +000012892 // C++ [over.call.object]p2:
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012893 // In addition, for each (non-explicit in C++0x) conversion function
12894 // declared in T of the form
Douglas Gregorab7897a2008-11-19 22:57:39 +000012895 //
12896 // operator conversion-type-id () cv-qualifier;
12897 //
12898 // where cv-qualifier is the same cv-qualification as, or a
12899 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +000012900 // denotes the type "pointer to function of (P1,...,Pn) returning
12901 // R", or the type "reference to pointer to function of
12902 // (P1,...,Pn) returning R", or the type "reference to function
12903 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +000012904 // is also considered as a candidate function. Similarly,
12905 // surrogate call functions are added to the set of candidate
12906 // functions for each conversion function declared in an
12907 // accessible base class provided the function is not hidden
12908 // within T by another intervening declaration.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +000012909 const auto &Conversions =
12910 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
12911 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +000012912 NamedDecl *D = *I;
12913 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
12914 if (isa<UsingShadowDecl>(D))
12915 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012916
Douglas Gregor74ba25c2009-10-21 06:18:39 +000012917 // Skip over templated conversion functions; they aren't
12918 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +000012919 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +000012920 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +000012921
John McCall6e9f8f62009-12-03 04:06:58 +000012922 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012923 if (!Conv->isExplicit()) {
12924 // Strip the reference type (if any) and then the pointer type (if
12925 // any) to get down to what might be a function type.
12926 QualType ConvType = Conv->getConversionType().getNonReferenceType();
12927 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
12928 ConvType = ConvPtrType->getPointeeType();
John McCalld14a8642009-11-21 08:51:07 +000012929
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012930 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
12931 {
12932 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012933 Object.get(), Args, CandidateSet);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012934 }
12935 }
Douglas Gregorab7897a2008-11-19 22:57:39 +000012936 }
Mike Stump11289f42009-09-09 15:08:12 +000012937
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012938 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12939
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012940 // Perform overload resolution.
12941 OverloadCandidateSet::iterator Best;
John Wiegley01296292011-04-08 18:41:53 +000012942 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall5c32be02010-08-24 20:38:10 +000012943 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012944 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +000012945 // Overload resolution succeeded; we'll build the appropriate call
12946 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012947 break;
12948
12949 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +000012950 if (CandidateSet.empty())
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012951 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley01296292011-04-08 18:41:53 +000012952 << Object.get()->getType() << /*call*/ 1
12953 << Object.get()->getSourceRange();
John McCall02374852010-01-07 02:04:15 +000012954 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012955 Diag(Object.get()->getLocStart(),
John McCall02374852010-01-07 02:04:15 +000012956 diag::err_ovl_no_viable_object_call)
John Wiegley01296292011-04-08 18:41:53 +000012957 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012958 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012959 break;
12960
12961 case OR_Ambiguous:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012962 Diag(Object.get()->getLocStart(),
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012963 diag::err_ovl_ambiguous_object_call)
John Wiegley01296292011-04-08 18:41:53 +000012964 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012965 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012966 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000012967
12968 case OR_Deleted:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012969 Diag(Object.get()->getLocStart(),
Douglas Gregor171c45a2009-02-18 21:56:37 +000012970 diag::err_ovl_deleted_object_call)
12971 << Best->Function->isDeleted()
John Wiegley01296292011-04-08 18:41:53 +000012972 << Object.get()->getType()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012973 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley01296292011-04-08 18:41:53 +000012974 << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012975 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000012976 break;
Mike Stump11289f42009-09-09 15:08:12 +000012977 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012978
Douglas Gregorb412e172010-07-25 18:17:45 +000012979 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012980 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012981
John McCall4124c492011-10-17 18:40:02 +000012982 UnbridgedCasts.restore();
12983
Craig Topperc3ec1492014-05-26 06:22:03 +000012984 if (Best->Function == nullptr) {
Douglas Gregorab7897a2008-11-19 22:57:39 +000012985 // Since there is no function declaration, this is one of the
12986 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +000012987 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +000012988 = cast<CXXConversionDecl>(
12989 Best->Conversions[0].UserDefined.ConversionFunction);
12990
Craig Topperc3ec1492014-05-26 06:22:03 +000012991 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
12992 Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000012993 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
12994 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000012995 assert(Conv == Best->FoundDecl.getDecl() &&
12996 "Found Decl & conversion-to-functionptr should be same, right?!");
Douglas Gregorab7897a2008-11-19 22:57:39 +000012997 // We selected one of the surrogate functions that converts the
12998 // object parameter to a function pointer. Perform the conversion
12999 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013000
Fariborz Jahanian774cf792009-09-28 18:35:46 +000013001 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +000013002 // and then call it.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013003 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
13004 Conv, HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +000013005 if (Call.isInvalid())
13006 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +000013007 // Record usage of conversion in an implicit cast.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000013008 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
13009 CK_UserDefinedConversion, Call.get(),
13010 nullptr, VK_RValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013011
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000013012 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +000013013 }
13014
Craig Topperc3ec1492014-05-26 06:22:03 +000013015 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
John McCall49ec2e62010-01-28 01:54:34 +000013016
Douglas Gregorab7897a2008-11-19 22:57:39 +000013017 // We found an overloaded operator(). Build a CXXOperatorCallExpr
13018 // that calls this method, using Object for the implicit object
13019 // parameter and passing along the remaining arguments.
13020 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Nico Weber1fefe412012-11-09 06:06:14 +000013021
13022 // An error diagnostic has already been printed when parsing the declaration.
Nico Weber9512d3f2012-11-09 08:38:04 +000013023 if (Method->isInvalidDecl())
Nico Weber1fefe412012-11-09 06:06:14 +000013024 return ExprError();
13025
Chandler Carruth8e543b32010-12-12 08:17:55 +000013026 const FunctionProtoType *Proto =
13027 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013028
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000013029 unsigned NumParams = Proto->getNumParams();
Mike Stump11289f42009-09-09 15:08:12 +000013030
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000013031 DeclarationNameInfo OpLocInfo(
13032 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
13033 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Nick Lewycky134af912013-02-07 05:08:22 +000013034 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000013035 HadMultipleCandidates,
13036 OpLocInfo.getLoc(),
13037 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000013038 if (NewFn.isInvalid())
13039 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013040
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000013041 // Build the full argument list for the method call (the implicit object
13042 // parameter is placed at the beginning of the list).
George Burgess IV215f6e72016-12-13 19:22:56 +000013043 SmallVector<Expr *, 8> MethodArgs(Args.size() + 1);
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000013044 MethodArgs[0] = Object.get();
George Burgess IV215f6e72016-12-13 19:22:56 +000013045 std::copy(Args.begin(), Args.end(), MethodArgs.begin() + 1);
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000013046
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013047 // Once we've built TheCall, all of the expressions are properly
13048 // owned.
Alp Toker314cc812014-01-25 16:55:45 +000013049 QualType ResultTy = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000013050 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13051 ResultTy = ResultTy.getNonLValueExprType(Context);
13052
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000013053 CXXOperatorCallExpr *TheCall = new (Context)
George Burgess IV215f6e72016-12-13 19:22:56 +000013054 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(), MethodArgs, ResultTy,
13055 VK, RParenLoc, false);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013056
Alp Toker314cc812014-01-25 16:55:45 +000013057 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
Anders Carlsson3d5829c2009-10-13 21:49:31 +000013058 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013059
Douglas Gregor02a0acd2009-01-13 05:10:00 +000013060 // We may have default arguments. If so, we need to allocate more
13061 // slots in the call for them.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000013062 if (Args.size() < NumParams)
13063 TheCall->setNumArgs(Context, NumParams + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +000013064
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000013065 bool IsError = false;
13066
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013067 // Initialize the implicit object parameter.
John Wiegley01296292011-04-08 18:41:53 +000013068 ExprResult ObjRes =
Craig Topperc3ec1492014-05-26 06:22:03 +000013069 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000013070 Best->FoundDecl, Method);
13071 if (ObjRes.isInvalid())
13072 IsError = true;
13073 else
Benjamin Kramer62b95d82012-08-23 21:35:17 +000013074 Object = ObjRes;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013075 TheCall->setArg(0, Object.get());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000013076
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013077 // Check the argument types.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000013078 for (unsigned i = 0; i != NumParams; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013079 Expr *Arg;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000013080 if (i < Args.size()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013081 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +000013082
Douglas Gregor02a0acd2009-01-13 05:10:00 +000013083 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +000013084
John McCalldadc5752010-08-24 06:29:42 +000013085 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +000013086 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000013087 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +000013088 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +000013089 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013090
Anders Carlsson7c5fe482010-01-29 18:43:53 +000013091 IsError |= InputInit.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013092 Arg = InputInit.getAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000013093 } else {
John McCalldadc5752010-08-24 06:29:42 +000013094 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +000013095 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
13096 if (DefArg.isInvalid()) {
13097 IsError = true;
13098 break;
13099 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013100
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013101 Arg = DefArg.getAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000013102 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013103
13104 TheCall->setArg(i + 1, Arg);
13105 }
13106
13107 // If this is a variadic call, handle args passed through "...".
13108 if (Proto->isVariadic()) {
13109 // Promote the arguments (C99 6.5.2.2p7).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000013110 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
Craig Topperc3ec1492014-05-26 06:22:03 +000013111 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
13112 nullptr);
John Wiegley01296292011-04-08 18:41:53 +000013113 IsError |= Arg.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013114 TheCall->setArg(i + 1, Arg.get());
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013115 }
13116 }
13117
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000013118 if (IsError) return true;
13119
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000013120 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000013121
Richard Smith55ce3522012-06-25 20:30:08 +000013122 if (CheckFunctionCall(Method, TheCall, Proto))
Anders Carlssonbc4c1072009-08-16 01:56:34 +000013123 return true;
13124
John McCalle172be52010-08-24 06:09:16 +000013125 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013126}
13127
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013128/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +000013129/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013130/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +000013131ExprResult
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000013132Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
13133 bool *NoArrowOperatorFound) {
Chandler Carruth8e543b32010-12-12 08:17:55 +000013134 assert(Base->getType()->isRecordType() &&
13135 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +000013136
John McCall4124c492011-10-17 18:40:02 +000013137 if (checkPlaceholderForOverload(*this, Base))
13138 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000013139
John McCallbc077cf2010-02-08 23:07:23 +000013140 SourceLocation Loc = Base->getExprLoc();
13141
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013142 // C++ [over.ref]p1:
13143 //
13144 // [...] An expression x->m is interpreted as (x.operator->())->m
13145 // for a class object x of type T if T::operator->() exists and if
13146 // the operator is selected as the best match function by the
13147 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +000013148 DeclarationName OpName =
13149 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
Richard Smith100b24a2014-04-17 01:52:14 +000013150 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
Ted Kremenekc23c7e62009-07-29 21:53:49 +000013151 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +000013152
John McCallbc077cf2010-02-08 23:07:23 +000013153 if (RequireCompleteType(Loc, Base->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000013154 diag::err_typecheck_incomplete_tag, Base))
Eli Friedman132e70b2009-11-18 01:28:03 +000013155 return ExprError();
13156
John McCall27b18f82009-11-17 02:14:36 +000013157 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
13158 LookupQualifiedName(R, BaseRecord->getDecl());
13159 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +000013160
13161 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +000013162 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +000013163 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
George Burgess IVce6284b2017-01-28 02:19:40 +000013164 None, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +000013165 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013166
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013167 bool HadMultipleCandidates = (CandidateSet.size() > 1);
13168
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013169 // Perform overload resolution.
13170 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000013171 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013172 case OR_Success:
13173 // Overload resolution succeeded; we'll build the call below.
13174 break;
13175
13176 case OR_No_Viable_Function:
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000013177 if (CandidateSet.empty()) {
13178 QualType BaseType = Base->getType();
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000013179 if (NoArrowOperatorFound) {
13180 // Report this specific error to the caller instead of emitting a
13181 // diagnostic, as requested.
13182 *NoArrowOperatorFound = true;
13183 return ExprError();
13184 }
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000013185 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
13186 << BaseType << Base->getSourceRange();
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000013187 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000013188 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000013189 << FixItHint::CreateReplacement(OpLoc, ".");
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000013190 }
13191 } else
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013192 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +000013193 << "operator->" << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000013194 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000013195 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013196
13197 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000013198 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
13199 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000013200 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000013201 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000013202
13203 case OR_Deleted:
13204 Diag(OpLoc, diag::err_ovl_deleted_oper)
13205 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000013206 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000013207 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000013208 << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000013209 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000013210 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013211 }
13212
Craig Topperc3ec1492014-05-26 06:22:03 +000013213 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
John McCalla0296f72010-03-19 07:35:19 +000013214
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013215 // Convert the object parameter.
13216 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000013217 ExprResult BaseResult =
Craig Topperc3ec1492014-05-26 06:22:03 +000013218 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000013219 Best->FoundDecl, Method);
13220 if (BaseResult.isInvalid())
Douglas Gregord8061562009-08-06 03:17:00 +000013221 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013222 Base = BaseResult.get();
Douglas Gregor9ecea262008-11-21 03:04:22 +000013223
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013224 // Build the operator call.
Nick Lewycky134af912013-02-07 05:08:22 +000013225 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000013226 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000013227 if (FnExpr.isInvalid())
13228 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013229
Alp Toker314cc812014-01-25 16:55:45 +000013230 QualType ResultTy = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000013231 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13232 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +000013233 CXXOperatorCallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013234 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
Lang Hames5de91cc2012-10-02 04:45:10 +000013235 Base, ResultTy, VK, OpLoc, false);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000013236
Alp Toker314cc812014-01-25 16:55:45 +000013237 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
George Burgess IVce6284b2017-01-28 02:19:40 +000013238 return ExprError();
13239
13240 if (CheckFunctionCall(Method, TheCall,
13241 Method->getType()->castAs<FunctionProtoType>()))
13242 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +000013243
13244 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013245}
13246
Richard Smithbcc22fc2012-03-09 08:00:36 +000013247/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
13248/// a literal operator described by the provided lookup results.
13249ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
13250 DeclarationNameInfo &SuffixInfo,
13251 ArrayRef<Expr*> Args,
13252 SourceLocation LitEndLoc,
13253 TemplateArgumentListInfo *TemplateArgs) {
13254 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smithc67fdd42012-03-07 08:35:16 +000013255
Richard Smith100b24a2014-04-17 01:52:14 +000013256 OverloadCandidateSet CandidateSet(UDSuffixLoc,
13257 OverloadCandidateSet::CSK_Normal);
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000013258 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
13259 /*SuppressUserConversions=*/true);
Richard Smithc67fdd42012-03-07 08:35:16 +000013260
Richard Smithbcc22fc2012-03-09 08:00:36 +000013261 bool HadMultipleCandidates = (CandidateSet.size() > 1);
13262
Richard Smithbcc22fc2012-03-09 08:00:36 +000013263 // Perform overload resolution. This will usually be trivial, but might need
13264 // to perform substitutions for a literal operator template.
13265 OverloadCandidateSet::iterator Best;
13266 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
13267 case OR_Success:
13268 case OR_Deleted:
13269 break;
13270
13271 case OR_No_Viable_Function:
13272 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
13273 << R.getLookupName();
13274 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13275 return ExprError();
13276
13277 case OR_Ambiguous:
13278 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
13279 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
13280 return ExprError();
Richard Smithc67fdd42012-03-07 08:35:16 +000013281 }
13282
Richard Smithbcc22fc2012-03-09 08:00:36 +000013283 FunctionDecl *FD = Best->Function;
Nick Lewycky134af912013-02-07 05:08:22 +000013284 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
13285 HadMultipleCandidates,
Richard Smithbcc22fc2012-03-09 08:00:36 +000013286 SuffixInfo.getLoc(),
13287 SuffixInfo.getInfo());
13288 if (Fn.isInvalid())
13289 return true;
Richard Smithc67fdd42012-03-07 08:35:16 +000013290
13291 // Check the argument types. This should almost always be a no-op, except
13292 // that array-to-pointer decay is applied to string literals.
Richard Smithc67fdd42012-03-07 08:35:16 +000013293 Expr *ConvArgs[2];
Richard Smithe54c3072013-05-05 15:51:06 +000013294 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Richard Smithc67fdd42012-03-07 08:35:16 +000013295 ExprResult InputInit = PerformCopyInitialization(
13296 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
13297 SourceLocation(), Args[ArgIdx]);
13298 if (InputInit.isInvalid())
13299 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013300 ConvArgs[ArgIdx] = InputInit.get();
Richard Smithc67fdd42012-03-07 08:35:16 +000013301 }
13302
Alp Toker314cc812014-01-25 16:55:45 +000013303 QualType ResultTy = FD->getReturnType();
Richard Smithc67fdd42012-03-07 08:35:16 +000013304 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13305 ResultTy = ResultTy.getNonLValueExprType(Context);
13306
Richard Smithc67fdd42012-03-07 08:35:16 +000013307 UserDefinedLiteral *UDL =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013308 new (Context) UserDefinedLiteral(Context, Fn.get(),
Benjamin Kramerc215e762012-08-24 11:54:20 +000013309 llvm::makeArrayRef(ConvArgs, Args.size()),
Richard Smithc67fdd42012-03-07 08:35:16 +000013310 ResultTy, VK, LitEndLoc, UDSuffixLoc);
13311
Alp Toker314cc812014-01-25 16:55:45 +000013312 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
Richard Smithc67fdd42012-03-07 08:35:16 +000013313 return ExprError();
13314
Craig Topperc3ec1492014-05-26 06:22:03 +000013315 if (CheckFunctionCall(FD, UDL, nullptr))
Richard Smithc67fdd42012-03-07 08:35:16 +000013316 return ExprError();
13317
13318 return MaybeBindToTemporary(UDL);
13319}
13320
Sam Panzer0f384432012-08-21 00:52:01 +000013321/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
13322/// given LookupResult is non-empty, it is assumed to describe a member which
13323/// will be invoked. Otherwise, the function will be found via argument
13324/// dependent lookup.
13325/// CallExpr is set to a valid expression and FRS_Success returned on success,
13326/// otherwise CallExpr is set to ExprError() and some non-success value
13327/// is returned.
13328Sema::ForRangeStatus
Richard Smith9f690bd2015-10-27 06:02:45 +000013329Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
13330 SourceLocation RangeLoc,
Sam Panzer0f384432012-08-21 00:52:01 +000013331 const DeclarationNameInfo &NameInfo,
13332 LookupResult &MemberLookup,
13333 OverloadCandidateSet *CandidateSet,
13334 Expr *Range, ExprResult *CallExpr) {
Richard Smith9f690bd2015-10-27 06:02:45 +000013335 Scope *S = nullptr;
13336
Sam Panzer0f384432012-08-21 00:52:01 +000013337 CandidateSet->clear();
13338 if (!MemberLookup.empty()) {
13339 ExprResult MemberRef =
13340 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
13341 /*IsPtr=*/false, CXXScopeSpec(),
13342 /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +000013343 /*FirstQualifierInScope=*/nullptr,
Sam Panzer0f384432012-08-21 00:52:01 +000013344 MemberLookup,
Aaron Ballman6924dcd2015-09-01 14:49:24 +000013345 /*TemplateArgs=*/nullptr, S);
Sam Panzer0f384432012-08-21 00:52:01 +000013346 if (MemberRef.isInvalid()) {
13347 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000013348 return FRS_DiagnosticIssued;
13349 }
Craig Topperc3ec1492014-05-26 06:22:03 +000013350 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
Sam Panzer0f384432012-08-21 00:52:01 +000013351 if (CallExpr->isInvalid()) {
13352 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000013353 return FRS_DiagnosticIssued;
13354 }
13355 } else {
13356 UnresolvedSet<0> FoundNames;
Sam Panzer0f384432012-08-21 00:52:01 +000013357 UnresolvedLookupExpr *Fn =
Craig Topperc3ec1492014-05-26 06:22:03 +000013358 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
Sam Panzer0f384432012-08-21 00:52:01 +000013359 NestedNameSpecifierLoc(), NameInfo,
13360 /*NeedsADL=*/true, /*Overloaded=*/false,
Richard Smithb6626742012-10-18 17:56:02 +000013361 FoundNames.begin(), FoundNames.end());
Sam Panzer0f384432012-08-21 00:52:01 +000013362
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000013363 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
Sam Panzer0f384432012-08-21 00:52:01 +000013364 CandidateSet, CallExpr);
13365 if (CandidateSet->empty() || CandidateSetError) {
13366 *CallExpr = ExprError();
13367 return FRS_NoViableFunction;
13368 }
13369 OverloadCandidateSet::iterator Best;
13370 OverloadingResult OverloadResult =
13371 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
13372
13373 if (OverloadResult == OR_No_Viable_Function) {
13374 *CallExpr = ExprError();
13375 return FRS_NoViableFunction;
13376 }
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000013377 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
Craig Topperc3ec1492014-05-26 06:22:03 +000013378 Loc, nullptr, CandidateSet, &Best,
Sam Panzer0f384432012-08-21 00:52:01 +000013379 OverloadResult,
13380 /*AllowTypoCorrection=*/false);
13381 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
13382 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000013383 return FRS_DiagnosticIssued;
13384 }
13385 }
13386 return FRS_Success;
13387}
13388
13389
Douglas Gregorcd695e52008-11-10 20:40:00 +000013390/// FixOverloadedFunctionReference - E is an expression that refers to
13391/// a C++ overloaded function (possibly with some parentheses and
13392/// perhaps a '&' around it). We have resolved the overloaded function
13393/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +000013394/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +000013395Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +000013396 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +000013397 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000013398 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
13399 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000013400 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000013401 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013402
Douglas Gregor51c538b2009-11-20 19:42:02 +000013403 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013404 }
13405
Douglas Gregor51c538b2009-11-20 19:42:02 +000013406 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000013407 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
13408 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013409 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +000013410 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +000013411 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +000013412 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +000013413 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000013414 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013415
13416 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +000013417 ICE->getCastKind(),
Craig Topperc3ec1492014-05-26 06:22:03 +000013418 SubExpr, nullptr,
John McCall2536c6d2010-08-25 10:28:54 +000013419 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013420 }
13421
Aaron Ballmanff7bd8b2016-09-02 13:45:40 +000013422 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
13423 if (!GSE->isResultDependent()) {
13424 Expr *SubExpr =
13425 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
13426 if (SubExpr == GSE->getResultExpr())
13427 return GSE;
13428
13429 // Replace the resulting type information before rebuilding the generic
13430 // selection expression.
Aaron Ballman8b871d92016-09-02 18:31:31 +000013431 ArrayRef<Expr *> A = GSE->getAssocExprs();
13432 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
Aaron Ballmanff7bd8b2016-09-02 13:45:40 +000013433 unsigned ResultIdx = GSE->getResultIndex();
13434 AssocExprs[ResultIdx] = SubExpr;
13435
13436 return new (Context) GenericSelectionExpr(
13437 Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
13438 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
13439 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
13440 ResultIdx);
13441 }
13442 // Rather than fall through to the unreachable, return the original generic
13443 // selection expression.
13444 return GSE;
13445 }
13446
Douglas Gregor51c538b2009-11-20 19:42:02 +000013447 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +000013448 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +000013449 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +000013450 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13451 if (Method->isStatic()) {
13452 // Do nothing: static member functions aren't any different
13453 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +000013454 } else {
Alp Toker028ed912013-12-06 17:56:43 +000013455 // Fix the subexpression, which really has to be an
John McCalle66edc12009-11-24 19:00:30 +000013456 // UnresolvedLookupExpr holding an overloaded member function
13457 // or template.
John McCall16df1e52010-03-30 21:47:33 +000013458 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13459 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +000013460 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000013461 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +000013462
John McCalld14a8642009-11-21 08:51:07 +000013463 assert(isa<DeclRefExpr>(SubExpr)
13464 && "fixed to something other than a decl ref");
13465 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
13466 && "fixed to a member ref with no nested name qualifier");
13467
13468 // We have taken the address of a pointer to member
13469 // function. Perform the computation here so that we get the
13470 // appropriate pointer to member type.
13471 QualType ClassType
13472 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
13473 QualType MemPtrType
13474 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
David Majnemer02d57cc2016-06-30 03:02:03 +000013475 // Under the MS ABI, lock down the inheritance model now.
13476 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13477 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
John McCalld14a8642009-11-21 08:51:07 +000013478
John McCall7decc9e2010-11-18 06:31:45 +000013479 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
13480 VK_RValue, OK_Ordinary,
13481 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +000013482 }
13483 }
John McCall16df1e52010-03-30 21:47:33 +000013484 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13485 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000013486 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000013487 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013488
John McCalle3027922010-08-25 11:45:40 +000013489 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +000013490 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +000013491 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +000013492 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013493 }
John McCalld14a8642009-11-21 08:51:07 +000013494
Richard Smith84a0b6d2016-10-18 23:39:12 +000013495 // C++ [except.spec]p17:
13496 // An exception-specification is considered to be needed when:
13497 // - in an expression the function is the unique lookup result or the
13498 // selected member of a set of overloaded functions
13499 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13500 ResolveExceptionSpec(E->getExprLoc(), FPT);
13501
John McCalld14a8642009-11-21 08:51:07 +000013502 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +000013503 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000013504 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCalle66edc12009-11-24 19:00:30 +000013505 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +000013506 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
13507 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +000013508 }
13509
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013510 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13511 ULE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000013512 ULE->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013513 Fn,
John McCall113bee02012-03-10 09:33:50 +000013514 /*enclosing*/ false, // FIXME?
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013515 ULE->getNameLoc(),
13516 Fn->getType(),
13517 VK_LValue,
13518 Found.getDecl(),
13519 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000013520 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013521 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
13522 return DRE;
John McCalld14a8642009-11-21 08:51:07 +000013523 }
13524
John McCall10eae182009-11-30 22:42:35 +000013525 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +000013526 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000013527 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCall2d74de92009-12-01 22:10:20 +000013528 if (MemExpr->hasExplicitTemplateArgs()) {
13529 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
13530 TemplateArgs = &TemplateArgsBuffer;
13531 }
John McCall6b51f282009-11-23 01:53:49 +000013532
John McCall2d74de92009-12-01 22:10:20 +000013533 Expr *Base;
13534
John McCall7decc9e2010-11-18 06:31:45 +000013535 // If we're filling in a static method where we used to have an
13536 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +000013537 if (MemExpr->isImplicitAccess()) {
13538 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013539 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13540 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000013541 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013542 Fn,
John McCall113bee02012-03-10 09:33:50 +000013543 /*enclosing*/ false,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013544 MemExpr->getMemberLoc(),
13545 Fn->getType(),
13546 VK_LValue,
13547 Found.getDecl(),
13548 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000013549 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013550 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
13551 return DRE;
Douglas Gregorb15af892010-01-07 23:12:05 +000013552 } else {
13553 SourceLocation Loc = MemExpr->getMemberLoc();
13554 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +000013555 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman73a04092012-01-07 04:59:52 +000013556 CheckCXXThisCapture(Loc);
Douglas Gregorb15af892010-01-07 23:12:05 +000013557 Base = new (Context) CXXThisExpr(Loc,
13558 MemExpr->getBaseType(),
13559 /*isImplicit=*/true);
13560 }
John McCall2d74de92009-12-01 22:10:20 +000013561 } else
John McCallc3007a22010-10-26 07:05:15 +000013562 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +000013563
John McCall4adb38c2011-04-27 00:36:17 +000013564 ExprValueKind valueKind;
13565 QualType type;
13566 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13567 valueKind = VK_LValue;
13568 type = Fn->getType();
13569 } else {
13570 valueKind = VK_RValue;
Yunzhong Gaoeba323a2015-05-01 02:04:32 +000013571 type = Context.BoundMemberTy;
13572 }
13573
13574 MemberExpr *ME = MemberExpr::Create(
13575 Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
13576 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
13577 MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
13578 OK_Ordinary);
13579 ME->setHadMultipleCandidates(true);
13580 MarkMemberReferenced(ME);
13581 return ME;
Douglas Gregor51c538b2009-11-20 19:42:02 +000013582 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013583
John McCallc3007a22010-10-26 07:05:15 +000013584 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregorcd695e52008-11-10 20:40:00 +000013585}
13586
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013587ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +000013588 DeclAccessPair Found,
13589 FunctionDecl *Fn) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000013590 return FixOverloadedFunctionReference(E.get(), Found, Fn);
Douglas Gregor3e1e5272009-12-09 23:02:17 +000013591}